def choose_target_f1(self, items, agents): # 1. Initialising the support variables max_distance = -1 furthest_agent = None # 2. Searching for the furthest agent for visible_agent in self.visible_agents: if self.distance(visible_agent) > max_distance: max_distance = self.distance(visible_agent) furthest_agent = visible_agent # 3. if agents visible but no items visible, return furthest agent; if len(self.visible_items) == 0 and len(self.visible_agents) > 0: return copy(furthest_agent) # 4. if agents and items visible, return item that furthest agent would choose if it had type L1; elif len(self.visible_items) > 0 and len(self.visible_agents) > 0: if furthest_agent is not None: furthest_agent = copy(furthest_agent) furthest_agent.agent_type = 'l1' furthest_agent.level = self.level furthest_agent.radius = self.radius furthest_agent.angle = self.angle furthest_agent.visible_agents_items(items, agents) return furthest_agent.choose_target(items, agents) else: return position.position(-1, -1) else: return position.position(-1, -1)
def _path(self, start, target): """Return all squares from start up until target. >>> board = ChessBoard() >>> board._path('A1', 'E1') ['A1', 'B1', 'C1', 'D1', 'E1'] Rearranging is allowed. >>> board._path('E1', 'A1') ['A1', 'B1', 'C1', 'D1', 'E1'] Only horizontal paths are taken into account here. >>> board._path('E1', 'E8') [] There is a path from you to yourself. >>> board._path('E1', 'E1') ['E1'] """ results = [] startrow, startcol = position.position(start) targetrow, targetcol = position.position(target) if startrow != targetrow: return results if startcol > targetcol: temp = startcol startcol = targetcol targetcol = temp while targetcol - startcol > -1: results.append(piece.squarify(startrow, startcol)) startcol += 1 return results
def move_a_agent(self, a_agent): location = a_agent.position # Location of agent destination = position.position(-1, -1) target = position.position(-1, -1) if self.destination_loaded_by_other_agents(a_agent): # item is loaded by other agents so reset the memory to choose new target. a_agent.reset_memory() # If the target is selected before we have it in memory variable and we can use it if a_agent.memory.get_position() != (-1, -1) and location != a_agent.memory: #here destination = a_agent.memory else: # If there is no target we should choose a target based on visible items and agents. a_agent.visible_agents_items(self.items, self.agents) target = a_agent.choose_target(self.items, self.agents) a_agent.choose_target_state = copy(self) if target.get_position() != (-1, -1): destination = target a_agent.memory = destination # If there is no destination the probabilities for all of the actions are same. if destination.get_position() == (-1, -1): a_agent.set_actions_probability(0.2, 0.2, 0.2, 0.2, 0.2) a_agent.set_random_action() return a_agent else: (x_destination, y_destination) = destination.get_position() # Get the target position destination_index = self.find_item_by_location(x_destination, y_destination) self.the_map[y_destination][x_destination] = 4 # Update map with target position load = a_agent.is_agent_near_destination(x_destination, y_destination) if load: # If there is a an item nearby loading process starts a_agent.item_to_load = self.items[destination_index] a_agent.set_actions_probabilities('L') else: a = a_star.a_star(self, a_agent) # Find the whole path to reach the destination with A Star (x_agent, y_agent) = a_agent.get_position() # Get agent's current position route = a.pathFind(x_agent, y_agent, x_destination, y_destination) if len(route) > 1: self.mark_route_map(route,x_agent, y_agent) a_agent.route_actions = self.convert_route_to_action(route) if len(route) == 0: a_agent.set_actions_probability(0.2, 0.2, 0.2, 0.2, 0.2) a_agent.set_random_action() return a_agent action = self.get_first_action(route) # Get first action of the path a_agent.set_actions_probabilities(action) return a_agent
def graph_draw(graph): rank.rank(graph) print "done rank" tmp_graph = ordering.ordering(graph) print "done ordering" position.position(tmp_graph) print "done position" return tmp_graph
def isPromotion(self, start, target): """Return True if this is a promotion move. We assume that this is a valid move. Start with a nice board for testing promotions. >>> board = ChessBoard(PROMOTION_BOARD) A Rook moving to the last line is not promoted >>> board['A7'].isPawn() False >>> board.isPromotion('A7', 'A8') False A pawn that reaches the last line is promoted. >>> board['C7'].isPawn() True >>> board.isPromotion('C7', 'C8') True A Pawn moving to a different line is not promoted. >>> board['D6'].isPawn() True >>> board.isPromotion('D6', 'D7') False >>> board['A2'].isPawn() True >>> board.isPromotion('A2', 'A3') False For Black it should work as well. >>> board['E2'].isPawn() True >>> board.isPromotion('E2', 'E1') True >>> board['D3'].isPawn() True >>> board.isPromotion('D3', 'D2') False >>> board['B7'].isPawn() True >>> board.isPromotion('B7', 'B5') False """ if self[start].isPawn(): startrow, startcol = position.position(start) if startrow in (1, 6): targetrow, targetcol = position.position(target) if targetrow in (0, 7): return True return False
def callback(map_data, pos_data): #ser the start time start_time = time.time() #place map and position data into classes created in myMap.py and position.py theMap = mapModule.myMap(map_data.data, map_data.info.height, map_data.info.width, map_data.info.resolution) myPos = posModule.position(pos_data.pose.position.x, pos_data.pose.position.y) #calculate the node of the current position myPosNode = theMap.pos_to_node(myPos) #send current position via UDP to specified IP, PORT sendCurrentPos = str(myPos.getX()) + ',' + str(myPos.getY()) sendMessageModule.sendinstructions('192.168.84.254', 2089, sendCurrentPos) #set the goal of the operation in meters and in node myGoal = posModule.position(-0.25, 0.5) myGoalNode = theMap.pos_to_node(myGoal) #get current direction myDirection = pos_data.pose.orientation.z #get the path from the aStarSolver from aStar.py path, path_drawn = aStarModule.aStarSolver(theMap, myPosNode, myGoalNode, myDirection) #draw the RVIZ line from drawLine.py drawLineModule.line_draw(path_drawn, myPos) #check if there is a path to the goal and set the direction of next move if (path != 0) and (myPosNode != myGoalNode): direction = theMap.next_move(path[0], path[1]) else: direction = False #determine the action needed to get to the next position and send the instructions g = actionModule.determine_action(path, direction, myDirection, myGoalNode, myPosNode) #create publishers for later analysis using rosbags #publishes current and wanted directions to two different topics pub = rospy.Publisher('goal_out_pose', PoseStamped, queue_size=3) goalPose = PoseStamped() goalPose.pose.orientation.z = g pub.publish(goalPose) pub2 = pub = rospy.Publisher('current_out_pose', PoseStamped, queue_size=3) currentPose = PoseStamped() c = pos_data.pose.orientation.z currentPose.pose.orientation.z = math.acos(c) * 2 pub2.publish(currentPose) #calculates and prints the elapsed time in order to monitor the time usage of the prosess print('elapsed time: ' + str((time.time() - start_time) * 1000) + 'ms\n')
def reset_bkt_position(self, new_bkt_position): self.bkt_position = new_bkt_position # 重新将目标持仓,实际持仓等矩阵初始化 self.tar_pct_position.holding_matrix = self.bkt_position.holding_matrix.reindex( index = self.tar_pct_position.holding_matrix.index, method = 'ffill') self.real_vol_position = position(self.tar_pct_position.holding_matrix) self.real_pct_position = position(self.tar_pct_position.holding_matrix) self.tar_vol_position = position(self.tar_pct_position.holding_matrix) # 重置回测数据 self.reset_bkt_data()
def sf_test_multiple_pools(factor=None, sf_obj=single_factor_strategy(), *, direction='+', bb_obj=None, discard_factor=(), folder_names=None, holding_freq='w', benchmarks=None, stock_pools=('all', 'hs300', 'zz500', 'zz800'), bkt_start=None, bkt_end=None, select_method=0, do_bb_pure_factor=False, do_pa=False, do_active_pa=False, do_data_description=False, do_factor_corr_test=False, loc=-1): # 打印当前测试的策略名称 print('Name Of Strategy Under Test: {0}\n'.format(sf_obj.__class__.__name__)) cp_adj = data.read_data('ClosePrice_adj') temp_position = position(cp_adj) # 先要初始化bkt对象 bkt_obj = backtest(temp_position, bkt_start=bkt_start, bkt_end=bkt_end, buy_cost=0.0015, sell_cost=0.0015, bkt_stock_data=['ClosePrice_adj', 'ClosePrice_adj']) # 建立bb对象,否则之后每次循环都要建立一次新的bb对象 if bb_obj is None: bb_obj = barra_base() # 外部传入的bb对象,要检测其股票池是否为all,如果不是all,则输出警告,因为可能丢失了数据 elif bb_obj.bb_data.stock_pool != 'all': print('The stockpool of the barra_base obj from outside is NOT "all", be aware of possibile' 'data loss due to this situation!\n') # 根据股票池进行循环 for cursor, stock_pool in enumerate(stock_pools): # 进行当前股票池下的单因子测试 # 注意bb obj进行了一份深拷贝,这是因为在业绩归因的计算中,会根据不同的股票池丢弃数据,导致数据不全,因此不能传引用 # 对bkt obj做了同样的处理,尽管这里并不是必要的 sf_obj.single_factor_test(factor=factor, loc=loc, direction=direction, bkt_obj=copy.deepcopy(bkt_obj), base_obj=copy.deepcopy(bb_obj), discard_factor=discard_factor, folder_name=folder_names[cursor], bkt_start=bkt_start, bkt_end=bkt_end, holding_freq=holding_freq, benchmark=benchmarks[cursor], stock_pool=stock_pool, select_method=select_method, do_base_pure_factor=do_bb_pure_factor, do_pa=do_pa, do_active_pa=do_active_pa, do_data_description=do_data_description, do_factor_corr_test=do_factor_corr_test)
def possibleMoves(self, start): """Return list of possible moves. Each item is itself a list of moves in one direction. """ row, col = position(start) directions = [] # Go round the clock starting at the top left if row < 7: if col > 0: directions.append([squarify(row+1, col-1)]) directions.append([squarify(row+1, col)]) if col < 7: directions.append([squarify(row+1, col+1)]) # Try to move right if col < 7: directions.append([squarify(row, col+1)]) # Try the three bottom moves if row > 0: if col < 7: directions.append([squarify(row-1, col+1)]) directions.append([squarify(row-1, col)]) if col > 0: directions.append([squarify(row-1, col-1)]) # Try to move left if col > 0: directions.append([squarify(row, col-1)]) return directions
def __init__(self, x, y, direction, index, agent_type='l1'): self.position = (int(x), int(y)) self.index = index self.level = None self.radius = None self.angle = None self.co_radius = None self.co_angle = None self.last_loaded_item_pos = None if isinstance(direction, basestring): self.direction = self.convert_direction(direction) else: self.direction = float(direction) self.agent_type = agent_type self.memory = position.position(-1, -1) self.route_actions = None self.item_to_load = -1 self.actions_probability = {'L': 0.20, 'N': 0.20, 'E': 0.20, 'S': 0.20, 'W': 0.20} self.visible_agents = [] self.visible_items = [] self.next_action = None self.state_dim = [] self.intelligent_agent = False
def choose_target(self, items, agents): # 1. Choosing target (item) if type L1 if self.agent_type == "l1": return self.choose_target_l1(items, agents) # 2. Choosing target (item) if type L2 elif self.agent_type == "l2": return self.choose_target_l2(items, agents) # 2. Choosing target (item) if type L2 elif self.agent_type == "l3": return self.choose_target_l3(items, agents) # 2. Choosing target (item) if type L2 elif self.agent_type == "l4": return self.choose_target_l4(items, agents) # 2. Choosing target (item) if type L2 elif self.agent_type == "l5": return self.choose_target_l5(items, agents) # 3. Choosing target (agent) if type F1 elif self.agent_type == "f1": return self.choose_target_f1(items, agents) # 4. Choosing target (agent) if type F2 elif self.agent_type == "f2": return self.choose_target_f2(items, agents) else: # print 'TypeError: Invalid Type\n\ttype',self.agent_type,'is invalid.' return position.position(-1, -1)
def possibleMoves(self, start): """Return list of possible moves. Each item is itself a list of moves in one direction. """ row, col = position(start) directions = [] # Go round the clock starting with the two top moves if row < 6: if col > 0: directions.append([squarify(row+2, col-1)]) if col < 7: directions.append([squarify(row+2, col+1)]) # Try the two right moves if col < 6: if row < 7: directions.append([squarify(row+1, col+2)]) if row > 0: directions.append([squarify(row-1, col+2)]) # Try the two bottom moves if row > 1: if col < 7: directions.append([squarify(row-2, col+1)]) if col > 0: directions.append([squarify(row-2, col-1)]) # Try the two left moves if col > 1: if row > 0: directions.append([squarify(row-1, col-2)]) if row < 7: directions.append([squarify(row+1, col-2)]) return directions
def process_without_alignment(): # parse the pre-existing alignment files: alignments = parse_alignments() # parse the positives and negatives files positives = parse_positives(args.pos_glycans) negatives = parse_negatives(args.neg_glycans) print_positions(positives, negatives) # set up counters for passed and failed sequences passed = 0 failed = 0 # iterate through the clades for clade in sorted(alignments.keys()): # inform the user print_clade(clade) # make a glycan object with pre-existing alignments pos = position(alignment=alignments[clade], pre_aligned=True) # find glycans y, n, y_ids, n_ids = find_positions(pos, positives, negatives) # adjust the passed/failed counters passed += y failed += n return passed, failed
def attackMoves(self, start): """Return list of square that this pawn can attack. Also return the matching squares that can be an en passant target. """ row, col = position(start) directions = [] if self.colour == WHITE and row < 7: if col > 0: target = squarify(row + 1, col - 1) en_passant = squarify(row, col - 1) directions.append((target, en_passant)) if col < 7: target = squarify(row + 1, col + 1) en_passant = squarify(row, col + 1) directions.append((target, en_passant)) if self.colour == BLACK and row > 0: if col > 0: target = squarify(row - 1, col - 1) en_passant = squarify(row, col - 1) directions.append((target, en_passant)) if col < 7: target = squarify(row - 1, col + 1) en_passant = squarify(row, col + 1) directions.append((target, en_passant)) return directions
def possibleMoves(self, start): """Return list of possible moves. Each item is itself a list of moves in one direction. """ row, col = position(start) directions = [] # Go round the clock starting at the top left if row < 7: if col > 0: directions.append([squarify(row + 1, col - 1)]) directions.append([squarify(row + 1, col)]) if col < 7: directions.append([squarify(row + 1, col + 1)]) # Try to move right if col < 7: directions.append([squarify(row, col + 1)]) # Try the three bottom moves if row > 0: if col < 7: directions.append([squarify(row - 1, col + 1)]) directions.append([squarify(row - 1, col)]) if col > 0: directions.append([squarify(row - 1, col - 1)]) # Try to move left if col > 0: directions.append([squarify(row, col - 1)]) return directions
def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, style=wx.WS_EX_VALIDATE_RECURSIVELY, *args, **kwargs) self.parent = self.GetTopLevelParent() self.tree = self.parent.document self.item = self.tree.GetSelection() self.xml = self.tree.GetItemPyData(self.item) self.information = information(self) self.contentType = contentType(self) self.status = wx.StaticText(self, -1, "", name="dimPosStatus") self.status.SetForegroundColour(wx.Colour(255, 0, 0, 0)) self.dimension = dimension(self) self.position = position(self) self.__doProperties() self.__doLayout() self.InitDialog() Safety(self)
def possibleMoves(self, start): """Return list of possible moves. Each item is itself a list of moves in one direction. """ row, col = position(start) return self.diagonalMoves(row, col)
def attackMoves(self, start): """Return list of square that this pawn can attack. Also return the matching squares that can be an en passant target. """ row, col = position(start) directions = [] if self.colour == WHITE and row < 7: if col > 0: target = squarify(row+1, col-1) en_passant = squarify(row, col-1) directions.append((target, en_passant)) if col < 7: target = squarify(row+1, col+1) en_passant = squarify(row, col+1) directions.append((target, en_passant)) if self.colour == BLACK and row > 0: if col > 0: target = squarify(row-1, col-1) en_passant = squarify(row, col-1) directions.append((target, en_passant)) if col < 7: target = squarify(row-1, col+1) en_passant = squarify(row, col+1) directions.append((target, en_passant)) return directions
def __init__(self, input_position, portfolio_returns, *, benchmark_weight='default'): self.pa_position = position(input_position.holding_matrix) # 如果传入基准持仓数据,则归因超额收益 if type(benchmark_weight) != str: # 一些情况下benchmark的权重和不为1(一般为差一点),为了防止偏差,这里重新归一化 # 同时将时间索引控制在回测期间内 new_benchmark_weight = benchmark_weight.reindex(self.pa_position.holding_matrix.index).\ apply(lambda x:x if (x==0).all() else x.div(x.sum()), axis=1) self.pa_position.holding_matrix = input_position.holding_matrix.sub(new_benchmark_weight, fill_value=0) # 提示用户, 归因变成了对超额部分的归因 print('Note that with benchmark_weight being passed, the performance attribution will be base on the ' 'active part of the portfolio against the benchmark. Please make sure that the portfolio returns ' 'you passed to the pa is the corresponding active return! \n') elif benchmark_weight == 'default': self.pa_position.holding_matrix = input_position.holding_matrix # 如果有传入组合收益,则直接用这个组合收益,如果没有则自己计算 self.port_returns = portfolio_returns self.pa_returns = pd.DataFrame() self.port_expo = pd.DataFrame() self.port_pa_returns = pd.DataFrame() self.style_factor_returns = pd.Series() self.industry_factor_returns = pd.Series() self.country_factor_return = pd.Series() self.residual_returns = pd.Series() # 业绩归因为基于barra因子的业绩归因 self.bb = barra_base() self.discarded_stocks_num = pd.DataFrame() self.discarded_stocks_wgt = pd.DataFrame()
def possibleMoves(self, start): """Return list of possible moves. Each item is itself a list of moves in one direction. """ row, col = position(start) directions = [] # Go round the clock starting with the two top moves if row < 6: if col > 0: directions.append([squarify(row + 2, col - 1)]) if col < 7: directions.append([squarify(row + 2, col + 1)]) # Try the two right moves if col < 6: if row < 7: directions.append([squarify(row + 1, col + 2)]) if row > 0: directions.append([squarify(row - 1, col + 2)]) # Try the two bottom moves if row > 1: if col < 7: directions.append([squarify(row - 2, col + 1)]) if col > 0: directions.append([squarify(row - 2, col - 1)]) # Try the two left moves if col > 1: if row > 0: directions.append([squarify(row - 1, col - 2)]) if row < 7: directions.append([squarify(row + 1, col - 2)]) return directions
def motor_position_control(): global err_ki global err2_ki start = time.perf_counter() while True: # print(err_ki) waiting.waiting(start, 150) start = time.perf_counter() getValues() err = [err_ki, err2_ki] position_desired = [x_position_desired, y_position_desired] position_measured = position.position(angle, angle2) result = arm_control_function.force_control(angle, angle2, position_desired, position_measured, err) print(position_measured) result = pwm_off_set(result) write_two_pwm_Values(int(result[0]), int(result[1])) #print(result) out_function() err_ki = result[2] err2_ki = result[3] err_clear()
def choose_target_l2(self, items, agents): # 1. Initialising the support variables max_index, max_level = -1, -1 # 2. Searching for highest level item below own level for i in range(0, len(self.visible_items)): if self.visible_items[i].level > max_level: if self.visible_items[i].level < self.level: max_level = self.visible_items[i].level max_index = i # - return the result if the item was found if max_index > -1: return self.visible_items[max_index].position # 3. Else search for highest level item else: for i in range(0, len(self.visible_items)): if self.visible_items[i].level > max_level: max_level = self.visible_items[i].level max_index = i # - return the result if the item was found if max_index > -1: return self.visible_items[max_index].position # 4. Else return no item else: return position.position(-1, -1)
def __getitem__(self, square): """ >>> board = ChessBoard() >>> board['A1'].isRook() True >>> board['a1'].isRook() True >>> board[u'A1'].isRook() True >>> board[0,0].isRook() True >>> board[7,3].isQueen() True >>> board['D8'].isQueen() True >>> board['D9'].isEmpty() Traceback (most recent call last): PositionException: ... >>> board[3,8].isEmpty() Traceback (most recent call last): PositionException: ... """ # Check if the input is a string, possibly unicode if type(square) in (type('A1'), type(u'A1')): row, col = position.position(square) else: row, col = square try: return self.rows[row][col] except IndexError: raise position.PositionException, \ "Position (%s, %s) out of range." % (row, col)
def ok(self): # 问卷ok按钮回调函数,获取用户信息,保存到数据库中 # 得到用户id,用于后续测试 gender = self.gender_v.get() age = self.age_v.get() education = self.education_v.get() occupation = self.occupation_v.get() netage = self.netage_v.get() # 用户选择检查 if gender == -1: self.err_info.config(text="error:请选择您的性别(问题1)") return if age == -1: self.err_info.config(text="error:请选择您的年龄(问题2)") return if education == -1: self.err_info.config(text="error:请选择您的教育背景(问题3)") return if occupation == -1: self.err_info.config(text="error:请选择您的职业(问题4)") return if netage == -1: self.err_info.config(text="error:请选择您的网龄(问题5)") return self.err_info.config(text="") #print type(city) #city = city.encode("gb2312") # print city #print city #city = city.encode("utf-8") #print type(city) # 通过ip获取用户归属地信息 pos_info = None pos = position.position() #pos[0] = False if pos[0] == False: # 失败 self.err_info.config(text="error:获取归属地信息失败" + str(pos[1])) pos_info = pos[2] #time.sleep(10) else: pos_info = pos[1] #city = city.encode("utf-8") #province = province.encode("utf-8") res, e = self.db_saver.save_user(gender, age, education, occupation, netage, pos_info) if res == False: self.err_info.config(text="error:" + str(e)) else: #my_pickle.save(gender, age, education, occupation, netage, city, province) #self.tip.place_forget() self.user_id = e self.question_win.destroy()
def getSentences(self, article, length): # get the weights for each word in the focus document and print them word_weights = self.getWordWeights(article) sentence_index = 0 #important_sentences = [] paragraphs_tokenized = paragraphs.para_tokenize(reuters.raw(article)) position_weighted_sentences = position(paragraphs_tokenized) word_weighted_sentences = [] for paragraph_index, paragraph in enumerate(paragraphs_tokenized): for sentence in paragraph: # calculate the weight of the sentence #The heuristics: sum_word_weight = self.getSumofWordWeights(sentence, word_weights) position_weight = 0 #............ #Add them together with multipliers: sentence_weight = 1*sum_word_weight + 0.5*position_weight #add sentence to list tup = (sentence_weight, sentence_index, sentence) word_weighted_sentences.append(tup) ''' # add the sentence if it is above the least weighted sentence in the list if len(important_sentences) < length or sentence_weight > important_sentences[length - 1][0]: #store the sentence as a tuple with the sentence weight, tup = (sentence_weight, sentence_index, sentence) important_sentences.append(tup) important_sentences.sort(reverse=True) if len(important_sentences) > length: important_sentences = important_sentences[:(length - 1)] ''' sentence_index += 1 #combine the heuristics important_sentences = [] sentence_index = 0 for paragraph in paragraphs_tokenized: for sentence in paragraph: sum_word_weight = word_weighted_sentences[sentence_index][0] position_weight = position_weighted_sentences[sentence_index][0] #print(sum_word_weight) #print(position_weight) sentence_weight = 1*sum_word_weight + 100*position_weight tup = (sentence_weight, sentence_index, sentence) important_sentences.append(tup) sentence_index += 1 #clip the number of sentences important_sentences.sort(key=self.getPosition) important_sentences = important_sentences[:(length - 1)] important_sentences.sort(key=self.getPosition) return important_sentences
def __init__(self, x, y, level, index): self.position = position.position(int(x), int(y)) self.loaded = False self.level = float(level) self.index = index self.agents_load_item = list() self.already_seen = False
def choose_target_f2(self, items, agents): # 1. Initialising the support variables max_level, max_distance = -1, -1 high_level_agent, furthest_agent = None, None # 2. Searching for the furthest agent and for # the highest level agent above own level for visible_agent in self.visible_agents: if self.distance(visible_agent) > max_distance: max_distance = self.distance(visible_agent) furthest_agent = visible_agent if visible_agent.level > max_level: if visible_agent.level > self.level: max_level = visible_agent.level high_level_agent = visible_agent # 3. if agents visible but no items visible, return agent with highest level above own level, # or furthest agent if none are above own level; if len(self.visible_items) == 0 and len(self.visible_agents) > 0: if high_level_agent is None: return furthest_agent.copy() else: return high_level_agent.copy() # 5. if agents and items visible elif len(self.visible_items) > 0 and len(self.visible_agents) > 0: # a. Selecting the leader if high_level_agent is None: leader_agent = furthest_agent.copy() else: leader_agent = high_level_agent.copy() # b. and return item that this agent would choose if it had type L2; if leader_agent is not None: leader_agent.agent_type = 'l2' leader_agent.level = self.level leader_agent.radius = self.radius leader_agent.angle = self.angle leader_agent.visible_agents_items(items, agents) return leader_agent.choose_target(items, agents) else: return position.position(-1, -1) else: return position.position(-1, -1)
def __init__(self): # 策略中会用到的数据类 self.strategy_data = strategy_data() # 策略中用到的持仓类,策略最终就是为了选择这个持仓,在没有调仓日和股票代码的情况下,暂设为一个空DataFrame self.position = position() # 调仓日,注意调仓日与策略数据中的日期一般不同,暂设为一个空series self.holding_days = pd.Series() # 策略的股票池 self.strategy_data.stock_pool = 'all'
def find_estimated_target(self, sim): destination = position.position(-1, -1) self.visible_agents_items(sim.items, sim.agents) target = self.choose_target(sim.items, sim.agents) if target.get_position() != (-1, -1): destination = target self.memory = destination
def test_position(): tests = [ # [input, expected] ["a", "Position of alphabet: 1"], ["z", "Position of alphabet: 26"], ["e", "Position of alphabet: 5"], ] for inp, exp in tests: assert position(inp) == exp
def makePositions(self, rawFolder): '''''' allFiles = listdir(rawFolder) isDVorTIF = re.compile('(?P<prefix>.+)(?P<suffix>\.tif|\.dv)$') onlyDVTIF = [isDVorTIF.match(f).group(0) for f in allFiles if isDVorTIF.match(f)] posID = 1 for p in onlyDVTIF: q = position(path.join(self.dirPath,p), posID) #initial construction of positions. self.addPosition(q) posID += 1
def __init__(self,threadID): print "backEndThread init" super(backEndThread,self).__init__() self.ss = sonarSys() self.fc = fControl() self.imu = imu(0,0,0,0,0,0) self.sonarValues = {0,0,0,0,0,0} self.pos = position(0,0,0,False,False,False) self.error = {"uart":"ok","fc":"ok","ss":"ok"} self.state = "landed" if enableLogging: timeString = time.strftime("%d.%m-%H.%M") pathString = "/home/pi/master/logs/"+timeString+"/" debugname = "logTesting" debugPath = "/home/pi/master/logs/"+debugname+"/" pathString = debugPath self.ssLogs = {} if not os.path.exists(pathString): os.makedirs(pathString) #sonar system logs for key,sonar in self.ss.sonars.iteritems(): keystr = str(key) self.ssLogs[keystr] = open(pathString+key+".dat",'w') self.ssLogs[keystr].write("#Time(ms)\t Value \t Validity \t avgValue \t Diff \t Outliers \t invalidReason\t SD \n") self.ssLogs["pairs"] = open(pathString+"pairs.dat",'w') self.ssLogs["pairs"].write("#Time(ms)\t xPos \t yPos \t zPos \t xValid \t yValid \t zValid \t validreasons x-y-z \n") #flight controller logs self.fcLog = open(pathString+"fcLog.dat",'w') self.fcLog.write("#Time(ms)\t xPos \t yPos \t zPos \t xVal \t yVal \t zVal \t State \t oRoll \t oPitch \t oYaw \t oThrottle \t spX \t spY \t spZ \n") #IMU logging self.imuLog = open(pathString+"imuLog.dat",'w') self.imuLog.write("#Time(ms)\t Roll \t Pitch \t Yaw \t gX \t Gy \t gZ \n") #self.error["log"]="error" try: self.uart = uartHandler(serialPort,baudRate) except SerialException: print "Error opening serial port " + serialPort try: self.uart = uartHandler(serialPort2,baudRate) except SerialException: print "Error opening serial port " + serialPort2 try: self.uart = uartHandler(serialPort3,baudRate) except SerialException: print "Error opening serial port " + serialPort3 self.error["uart"]="fail"
def choose_target_l1(self, items, agents): # 1. Initialising the support variables max_index, max_distance = -1, -1 lost_indexes = [] # 2. Searching for max distance item while True: for i in range(0, len(self.visible_items)): if self.distance(self.visible_items[i]) > max_distance and i not in lost_indexes: max_distance = self.distance(self.visible_items[i]) max_index = i if max_index == -1: return position.position(-1, -1) if self.visible_items[max_index] < self.level: return self.visible_items[max_index] else: lost_indexes.append(max_index) max_index, max_distance = -1, -1 return position.position(-1, -1)
def possibleMoves(self, start): """Return list of possible moves. Each item is itself a list of moves in one direction. """ row, col = position(start) directions = [] directions.append(self.forwardMoves(row, col)) directions.append(self.backwardMoves(row, col)) directions.append(self.leftMoves(row, col)) directions.append(self.rightMoves(row, col)) directions = [dir for dir in directions if len(dir) > 0] return directions
def choose_target_l3(self, items, agents): # 1. Initialising the support variables min_index, min_distance = -1, 999999 # 2. Searching for min distance item for i in range(0, len(self.visible_items)): if self.distance(self.visible_items[i]) < min_distance: min_distance = self.distance(self.visible_items[i]) min_index = i if min_index == -1: return position.position(-1, -1) else: return self.visible_items[min_index]
def choose_target_l1(self,items,agents): # 1. Initialising the support variables max_index, max_distance = -1, -1 # 2. Searching for max distance item for i in range(0, len(self.visible_items)): if self.distance(self.visible_items[i]) > max_distance: max_distance = self.distance(self.visible_items[i]) max_index = i # 3. Returning the result if max_index > -1: return self.visible_items[max_index] else: return position.position(-1, -1)
def choose_target_l4(self, items, agents): # 1. Initialising the support variables min_index, min_level = -1, 999999 # 2. Searching for lowest level item for i in range(0, len(self.visible_items)): if self.visible_items[i].level < min_level: min_level = self.visible_items[i].level min_index = i # - return the result if the item was found if min_index != -1: return self.visible_items[min_index].position else: return position.position(-1, -1)
def __init__(self): self.pos = position(0, 0, 0, False, False, False) self.sonars = {} self.sonarPairs = {} self.sonars["front"] = sonar("front") self.sonars["back"] = sonar("back") self.sonars["right"] = sonar("right") self.sonars["left"] = sonar("left") self.sonars["down"] = sonar("down") self.sonars["up"] = sonar("up") self.sonarPairs["x"] = sonarPair(self.sonars["front"], self.sonars["back"], "x") self.sonarPairs["y"] = sonarPair(self.sonars["right"], self.sonars["left"], "y") self.sonarPairs["z"] = sonarPair(self.sonars["down"], self.sonars["up"], "z")
def possibleMoves(self, start): """Make list of possible moves. """ row, col = position(start) directions = [] if self.colour == WHITE: if row == 1: max = 2 else: max = 1 directions.append(self.forwardMoves(row, col, max=max)) if self.colour == BLACK: if row == 6: max = 2 else: max = 1 directions.append(self.backwardMoves(row, col, max=max)) return directions
def build_from_save(mod=None): position_objects = [] data = load('quotes.json') pos = data['positions'] for ticker, lst in pos.iteritems(): p = [] for quoteitem in lst: i = model._QUOTE_TYPES[quoteitem['type']](ticker=ticker, **quoteitem) p.append(i) position_objects.append(position.position(*p)) root = model.create_header() for pos in position_objects: p = model.PositionItem([pos], root) for q in pos.quotes(): p.appendChild(model.PositionItem([q], p)) root.appendChild(p) return root
def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) self.parent = self.GetTopLevelParent() self.tree = self.parent.document self.item = self.tree.GetSelection() self.xml = self.tree.GetItemPyData(self.item) self.orientation = paperOrientation(self) self.layout = paperLayout(self) self.format = paperFormat(self) self.status = wx.StaticText(self, -1, "", name="dimPosStatus") self.status.SetForegroundColour(wx.Color(255,0,0,0)) self.dimension = dimension(self) self.position = position(self) self.__doProperties() self.__doLayout() Safety(self)
def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, style=wx.WS_EX_VALIDATE_RECURSIVELY, *args, **kwargs) self.parent = self.GetTopLevelParent() self.tree = self.parent.document self.item = self.tree.GetSelection() self.xml = self.tree.GetItemPyData(self.item) self.information = information(self) self.contentType = contentType(self) self.status = wx.StaticText(self, -1, "", name="dimPosStatus") self.status.SetForegroundColour(wx.Colour(255,0,0,0)) self.dimension = dimension(self) self.position = position(self) self.__doProperties() self.__doLayout() self.InitDialog() Safety(self)
def afterMove(self, **kwargs): startrow, temp = position(kwargs['start']) targetrow, temp = position(kwargs['target']) if abs(startrow - targetrow) == 2: self.can_be_en_passant_target = True
def __setitem__(self, square, piece): """Put the piece at the target square. Let's give the King his proper place. >>> king = piece.King(colour=WHITE) >>> target = 'E1' >>> row, col = position.position(target) >>> board = ChessBoard(EMPTY_CHESS_BOARD) >>> board[target].isEmpty() True >>> board[row, col].isEmpty() True >>> board[target] = king >>> board[target].isKing() True >>> board[row, col].isKing() True Let's try the same for a bishop, but use row and column numbers now. We put a bishop at C8. >>> target = 'C8' >>> targetrow = 7 >>> targetcol = 2 >>> board[targetrow, targetcol].isEmpty() True >>> board[target].isEmpty() True >>> bishop = piece.Bishop() >>> board[targetrow, targetcol] = bishop >>> board[targetrow, targetcol].isBishop() True >>> board[target].isBishop() True Using unicode strings should work as well. >>> target = u'F5' >>> board[target].isEmpty() True >>> board[target] = piece.Knight() >>> board[target].isKnight() True Let's try to put a King outside the board. >>> board['E0'] = king Traceback (most recent call last): PositionException: ... >>> board[8,0] = king Traceback (most recent call last): PositionException: ... """ # Check if the input is a string, possibly unicode if type(square) in (type('A1'), type(u'A1')): row, col = position.position(square) else: row, col = square try: self.rows[row][col] = piece except IndexError: raise position.PositionException, \ "Position (%s, %s) out of range." % (row, col)
def freePath(self, start, target): """Return True if there are no pieces between the start and target square. The end points themselves need not be empty. At the moment this function is only used for castling, so only horizontal moves are taken into account. So vertical or diagonal paths are always clear. >>> board = ChessBoard() >>> board.freePath('A1', 'A8') True >>> board.freePath('A1', 'H8') True What happens if start and target are the same square? We do not care actually. >>> board.freePath('A1', 'A1') True Two direct horizontal neighbours always have a free path between them, as there are simply no squares in between. >>> board.freePath('A1', 'B1') True But with one square between them, the path will be blocked. >>> board.freePath('B1', 'D1') False It does not matter whether the end points are empty >>> board.empty('B1') >>> board.empty('D1') >>> board.freePath('B1', 'D1') False And certainly the King cannot castle in the beginning: >>> board.freePath('E1', 'A1') False Let's check that changing the end points around does not matter. >>> board.freePath('A1', 'E1') False We have started clearing a path between the King and the Rook already. Removing one more piece should do it. >>> board.empty('C1') >>> board.freePath('E1', 'A1') True >>> board.freePath('A1', 'E1') True A path in between is now also free. >>> board.freePath('B1', 'D1') True """ path = self._path(start, target) # We do not care about the start and end positions, only # intermediate positions. expected_free = path[1:-1] for square in expected_free: if not self[square].isEmpty(): return False return True startrow, startcol = position.position(start) targetrow, targetcol = position.position(target) if startrow != targetrow: return False if startcol == targetcol: e = "Start (%s) and target (%s) square are the same" % \ (start, target) raise position.ChessException, e elif startcol > targetcol: direction = -1 else: direction = 1 while abs(startcol - targetcol) != 1: startcol += direction if not self[startrow, startcol].isEmpty(): return False return True
def process(): # parse the reference sequence and ID ref = SeqIO.read(open(args.reference, 'r'), 'fasta') ref_id = ref.id ref_seq = str(ref.seq) # set up an envs dict to hold env sequences segregated by clade envs = {'A': [], 'B': [], 'C': [], 'D': [], 'E': [], 'G': [], 'AE': [], 'AG': [], 'other': [] } # parse the FASTA input file and build a dict of sequences, segregated by clade for env in SeqIO.parse(open(args.in_file, 'r'), 'fasta'): # grab the clade, ID, and sequence env_id = env.id clade = env_id.split('.')[0].upper() env_seq = str(env.seq) # refine the clade name for clade A and the CRFs if clade in ('A1', 'A2'): clade = 'A' elif clade in ['CRF01_AE', '01_AE']: clade = 'AE' elif clade in ['CRF02_AG', '02_AG']: clade = 'AG' # only look at sequences that are long enough to be relavent if len(env_seq) >= 250: # for the major clades, just append the sequence to the appropriate clade list if clade in envs.keys(): envs[clade].append([env_id, env_seq]) # for the minor clades (not present in the env dict), append the env sequence to the 'other' category else: envs['other'].append([env_id, env_seq]) # set up an alphabetical list of clades, so that we can process them in order. sorted_clades = sorted(envs.keys()) # set up a list of passed and failed counts and ids passed = 0 failed = 0 passed_ids = [] failed_ids = [] # get positions lists pos_list = parse_positives(args.pos_glycans) neg_list = parse_negatives(args.neg_glycans) print_positions(pos_list, neg_list) # set up a temporary file path (only used for MSA alignments) temp_alignment_file = os.path.join(os.path.dirname(args.in_file), 'temp_alignment.fasta') # iterate through the clades and get scores for c in sorted_clades: # let the user know what's up print_clade(c) # only process if there are sequences in the clade group if len(envs[c]) < 1: print "No sequences in this clade." continue # make the glycan object pos = position(ref=ref_seq, input_list=envs[c], align_type=args.align_type, align_file=temp_alignment_file) # determine the presence of glycans at the first position y, n, y_ids, n_ids = find_positions(pos, pos_list, neg_list) # add the passed and failed to the appropriate var passed += y failed += n passed_ids.extend(y_ids) failed_ids.extend(n_ids) # if the alignment directory isnt' defined, don't write the alignments to file if args.align_dir == '': print '' print '' print 'ALIGNMENTS ARE NOT BEING WRITTEN TO FILE.' print '' print '' # if there is an alignment directory else: # define the full path of the alignment file alignment_file = os.path.join(args.align_dir, c.upper() + '.alignment') # write the alignment pos.write_alignment(alignment_file) # if the 'print_ids' flag is on, print all of the ids that either passed or failed if args.print_ids: all_ids = passed_ids + failed_ids all_ids = sorted(all_ids) for i in all_ids: if i in passed_ids: val = 'Yes' else: val = 'No' print i + '\t' + val return passed, failed