def __init__(self, parametres): N_patche = parametres["Np"] self.param = parametres self.interaction = Interaction(N_patche) self.fonctionsreponse = None self.bulles = Bulles(parametres) self.T0 = 0.0
def init_interaction(self): self.interaction = Interaction() self.interaction.register_callback('pick', self.pick) self.interaction.register_callback('move', self.move) self.interaction.register_callback('place', self.place) self.interaction.register_callback('rotate_color', self.rotate_color) self.interaction.register_callback('scale', self.scale)
def render(self): utl.zero(self.img) for _i, _j in ti.ndrange(self.cam.resolution_h, self.cam.resolution_w): _ray = self.cam.get_ray(_i, _j) _dir_t_max = utl.infinitesimal _dir_t_min = utl.infinite # 求光线从参与介质中穿过的最近_dir_t_min与最远_dir_t_max for _k in ti.ndrange(self.shape.tri.shape[0]): _tri = self.shape.tri[_k] self.ver_3_tmp[0] = self.shape.ver[_tri.x] self.ver_3_tmp[1] = self.shape.ver[_tri.y] self.ver_3_tmp[2] = self.shape.ver[_tri.z] # print(ti_ver_3_tmp[2]) _is_hit, _dir_t, _u, _v = _ray.intersect_triangle(self.ver_3_tmp) if _is_hit == 1: _dir_t_max = max(_dir_t_max, _dir_t) _dir_t_min = min(_dir_t_min, _dir_t) # 如果穿过了参与介质 if _dir_t_max - _dir_t_min > 0.00001: _hit_p_max = _ray.origin + _dir_t_max * _ray.direction _hit_p_min = _ray.origin + _dir_t_min * _ray.direction # 最近-最远交点 _inter_p_max = Interaction(_hit_p_max, _ray.direction) _inter_p_min = Interaction(_hit_p_min, _ray.direction) self.img[_i, _j] = self.ray_marching(_inter_p_min, _inter_p_max) * 0.01
def what_happend(self): nb = len(self.symb) seqs = [] vas = -math.inf if len(self.actions) > 2 * nb + 1: lasts = self.actions[len(self.actions) - nb + 1:] inds = self.subfinder(lasts) for i in inds: found = False temp = [] tempi = 0 y = 0 while len(self.actions) - 3 > i + nb + y and (y == nb or self.vals[i + nb + y - 1] < 0): temp.append(self.actions[i + nb + y]) potit = self.testint(seqs) if potit is None: tempi += self.vals[i + nb + y] -(0.5 * len(seqs)) else: tempi += potit.proclivity -(0.5 * len(seqs)) y += 1 if self.vals[i + nb + y - 1] > 0: found = True # = pour prendre la dernière -> plus de chance d'être mieux if found: if tempi >= vas and tempi > -100: seqs = temp[:] vas = tempi if len(seqs) > 0: temp = self.testint(seqs) if temp is None: self.iter = Interaction(seqs[:], 0, 1) self.inters.append(self.iter) else: self.iter = temp elif random.randint(0, 1) == 0: seqs = [random.randrange(0, self.nbacts, 1) for _ in range(random.randint(1,self.nbacts-1*2))] temp = self.testint(seqs) if temp is None: self.iter = Interaction(seqs[:], vas, 1) self.inters.append(self.iter) else: self.iter = temp return seqs
def del_friend(self, username): # update data other_index = Data.users[Data.users['username'] == username].index[0] Data.users.loc[self.index, 'friends'].remove(other_index) Data.users.loc[other_index, 'friends'].remove(self.index) if Interaction.is_connected(username): other_client = Interaction.get_client(username) send(other_client.conn, f'delfr|{self.username}')
def __init__(self, group, edgetype, bait_ids=None): Interaction.__init__(self) # We first set the putative bait so it can be used later for the # ppiTrim_id if bait_ids is not None: self.set_template_baits(bait_ids) self._create_complex(group, edgetype)
def __init__(self): """initializing variables for input user.""" self.interaction = Interaction() self.api_data = Data() self.api_data.categories self.sql_setup = Sqlconnection() self.menu_selectable = False self.menu_get_product = False
def on_log(self, username): self.logged = True Interaction.clients.append(self) self.username = username line = Data.users[Data.users['username'] == username] self.friends = line['friends'].values[0] self.index = line.index[0] Interaction.manage_friends(self) self.look_for_fr_request() Data.send_stats(username, self.conn)
def __init__(self, client, interaction_spec): self.client = client self.cjar = { "browser": cookielib.CookieJar(), "rp": cookielib.CookieJar(), "service": cookielib.CookieJar() } self.interaction = Interaction(self.client, interaction_spec) self.features = None self.login_time = 0
def init_interaction(self): """ init user interaction and callbacks """ self.interaction = Interaction() self.interaction.register_callback('pick', self.pick) self.interaction.register_callback('move', self.move) self.interaction.register_callback('place', self.place) self.interaction.register_callback('rotate_color', self.rotate_color) self.interaction.register_callback('scale', self.scale) self.interaction.register_callback('close',self.close) self.interaction.register_callback('setCameraMode',self.setCameraMode)
def heuristicDiversification(self): for actions in self._actions: if not self.exist_interaction(actions): inter = Interaction(actions, 0, 1) valence = self.bootstrap(inter) if not valence is None: inter.result = valence self._interactions.append(inter) return inter return None
def create_env(self, username): # check other is conn if Interaction.is_connected(username): other_client = Interaction.get_client(username) self.env = Env((self, other_client), (self.username, other_client.username)) other_client.env = self.env Interaction.inform_inenv(other_client.username) other_client.in_env = True self.in_env = True
def init_interaction(self): self.interaction = Interaction() self.interaction.register_callback('pick', self.pick) self.interaction.register_callback('move', self.move) self.interaction.register_callback('place', self.place) self.interaction.register_callback('rotate_color', self.rotate_color) self.interaction.register_callback('scale', self.scale) self.interaction.register_callback('close', self.close) self.interaction.register_callback('reset', self.reset) self.interaction.register_callback('nogrid', self.nogrid)
def get_all_interactions(): interactions = [] response = table.scan() for s in response['Items']: interaction = Interaction(s['sessionId'], s['time'], s['responses'], s['deviceId'], s['userId']) Interaction.print_interaction(interaction) interactions.append(interaction) return interactions
def check_env_rinv(self, username): # check other is conn if Interaction.is_connected(username): other_client = Interaction.get_client(username) # check if other client is already in env if other_client.in_env: other_client.env.add_client(self) self.in_env = True self.env = other_client.env else: self.create_env(username) Interaction.inform_inenv(self.username)
def possible_actions(self): actions = [] if self.dead: actions.append(Interaction(self, "Loot", 1.5)) else: if self.interact_script: actions.append(Interaction(self, "Interact", 1.5)) if self.dialogue: actions.append(Interaction(self, "Talk", 5)) if self.killable: actions.append(Interaction(self, "Kill", 1.5)) return actions
def generate(self): regenerateScene = True while regenerateScene: availableId = 1 regenerateScene = False self.clear() self.humans = [] self.objects = [] self.interactions = [] self.room = Room() self.addItem(self.room) # We generate a number of humans using the absolute of a normal # variate with mean 1, sigma 4, capped to 15. If it's 15 we get # the remainder of /15 humanCount = int(abs(random.normalvariate(1, 4))) % 15 if humanCount == 0: humanCount = QtCore.qrand() % 3 for i in range(humanCount): human = self.generateHuman(availableId) availableId += 1 self.addItem(human) self.humans.append(human) if QtCore.qrand() % 3 == 0: human2 = self.generateComplementaryHuman( human, availableId) availableId += 1 self.addItem(human2) interaction = Interaction(human, human2) self.interactions.append(interaction) self.addItem(interaction) self.humans.append(human2) elif QtCore.qrand() % 2 == 0: obj = self.generateComplementaryObject(human, availableId) availableId += 1 interaction = Interaction(human, obj) self.interactions.append(interaction) self.addItem(interaction) self.addItem(obj) self.objects.append(obj) self.robot = Robot() self.robot.setPos(0, 0) self.addItem(self.robot) self.text = 'Humans:' + str(len(self.humans)) + ' ' + 'Objects:' + str( len(self.objects))
def parse(dir_name): print("#####PARSING#####") arn_list = [] for filename in os.listdir(dir_name): file = open(dir_name + filename, 'r') print("file: " + dir_name + filename) # On construit l'objet ARN arn = ARN(filename.split("_")[0]) file.readline() file.readline() chain = file.readline().split(" ")[1].rsplit('\t') chain_id = chain[0] chain = chain[1].rsplit('\n')[0] arn.chain = chain arn.chain_id = chain_id file.readline() # On ajoute les interactions et bases a l'ARN arn._set_bases() for line in file: line = line.rsplit('\t') base1 = Base(line[2], int(line[5])) base2 = Base(line[6], int(line[9].rsplit('\n')[0])) interaction = Interaction(base1, line[1], base2) arn._add_interaction(interaction) # On ajoute les boucles a l'ARN expr = "Catalog_results/loop." + arn.name + "*" for loop_file_name in glob.glob(expr): print("|\tloop file: " + loop_file_name) loop_file = open(loop_file_name) loop = Loop(arn.name, arn.chain_id, loop_file.readline().split(":")[1].rsplit('\n')[0]) loop_bases = loop_file.readline().split(": ")[1].split(", ") loop_bases[-1] = loop_bases[-1].rsplit('\n')[0] loop.bases = [Base(b[:1], b[1:]) for b in loop_bases] loop_file.readline() for line in loop_file: line = line.rsplit('\t') base1 = Base(line[0][:1], int(line[0][1:])) base2 = Base(line[2][:1], int(line[2][1:].rsplit('\n')[0])) interaction = Interaction(base1, line[1], base2) print("|\t|\tadding interaction " + str(interaction)) loop.add_interaction(interaction) arn._add_loop(loop) loop_file.close() file.close() arn_list.append(arn) print("#####FINISHED PARSING#####") return arn_list
def addget_primitive_interaction(self, experiment, result, valence=None, meaning=None): label = experiment.get_label() + result.get_label() if label not in self.INTERACTIONS: interaction = Interaction(label) interaction.set_experiment(experiment) interaction.set_result(result) interaction.set_valence(valence) interaction.set_meaning(meaning) self.INTERACTIONS[label] = interaction return self.INTERACTIONS[label]
def process_ppi1(irefindex_file, id_logfile, output_logfile, biochem_file, binary_file, complexes_file, obo_file, biogrid_ptm_codes_file, filtered_pmids_file=None, accepted_taxids=None): counts = Phase1Counts() filtered_pmids = read_filtered_pmids(filtered_pmids_file) id_map = read_id_mapping(id_logfile) obo_fp = open(obo_file, 'rU') ontology = obo.OBOntology(obo_fp) biochem_filter = _BiochemFilter(ontology, biogrid_ptm_codes_file) complex_filter = _ComplexFilter(ontology) input_fp = open(irefindex_file, 'rU') removed_fp = NullFile() biochem_fp = open(biochem_file, 'w') binary_fp = open(binary_file, 'w') complex_fp = open(complexes_file, 'w') logfile_fp = open(output_logfile, 'w') output_fps = (removed_fp, binary_fp, complex_fp, biochem_fp) for fp in output_fps: Interaction.write_header(fp) scanner = parse_mitab_file(input_fp, full_mitab_iterator, None, iRefIndexInteraction) for interaction, lines in scanner: line_numbers = lines[1] res = _process_interaction(interaction, id_map, filtered_pmids, logfile_fp, counts, line_numbers, ontology, biochem_filter, complex_filter, accepted_taxids) interaction.to_file(output_fps[res]) counts.to_file(logfile_fp) input_fp.close() obo_fp.close() logfile_fp.close() for fp in output_fps: fp.close()
def add_primitive_interaction(self, experiment, result, valence): label = experiment.get_label() + result.get_label() if label not in self.INTERACTIONS: interaction = Interaction(label, valence) interaction.set_experiment(experiment) interaction.set_result(result) interaction.set_valence(valence) self.INTERACTIONS[label] = interaction
def initialize_interactions(self, primitive_interactions): for interaction in primitive_interactions: meaning = interaction experiment_label = primitive_interactions[interaction][0] result_label = primitive_interactions[interaction][1] valence = primitive_interactions[interaction][2] experiment = self.addget_abstract_experiment(experiment_label) result = self.addget_result(result_label) self.addget_primitive_interaction(experiment, result, valence, meaning) for experiment in self.EXPERIMENTS.values(): interaction = Interaction(experiment.get_label() + "r2") interaction.set_valence(1) interaction.set_experiment(experiment) experiment.set_intended_interaction(interaction)
def learn_composite_interaction(self, context_interaction, enacted_interaction): if context_interaction is not None: label = context_interaction.get_label() + enacted_interaction.get_label() if label not in self.INTERACTIONS: valence = context_interaction.get_valence() + enacted_interaction.get_valence() interaction = Interaction(label, valence) interaction.set_pre_interaction(context_interaction) interaction.set_post_interaction(enacted_interaction) interaction.set_valence(valence) self.INTERACTIONS[label] = interaction print "Learn " + label else: interaction = self.INTERACTIONS[label] print 'Incrementing weight for ' + interaction.__repr__() interaction.increment_weight()
def chooseExperience(self, ite, ite_max): if len(self.actions) == 0: self.last_action = random.randint(0, self.nbacts - 1) return self.last_action elif self.last_reward < 0: if len(self.todo) == 0: if self.iter is not None: self.iter.maj( sum(self.vals[len(self.vals) - len(self.iter.action):])) if random.randint(0, 25) > 1: self.todo = self.what_happend() if len(self.todo) == 0: self.last_action = swap(self.last_action, self.nbacts - 1) else: print(self.last_action) seqs = [ random.randrange(0, self.nbacts, 1) for _ in range(random.randint(1, self.nbacts - 1 * 2)) ] temp = self.testint(seqs) if temp is None: self.iter = Interaction(seqs[:], 0, 1) self.inters.append(self.iter) else: self.iter = temp self.todo = self.iter.action[:] self.last_action = self.todo.pop(0) else: self.last_action = self.todo.pop(0) return self.last_action elif len(self.todo) > 0: self.last_action = self.todo.pop(0) return self.last_action else: if self.iter is not None: self.iter.maj( sum(self.vals[len(self.vals) - len(self.iter.action):])) return self.last_action
def generateObject(self): self.interactions = [] self.objects = [] obj = None for human in self.humans: if human is not None: if QtCore.qrand( ) % 3 == 0: #The constant can be updated acoording to need for more or less number of objects in the world try: obj = self.generateComplementaryObject( human, self.availableId) except RuntimeError: #Handling the time generation error obj = None pass print("Took more time to create a random object") #Returning so that too much time is not wasted in creating a random object which is inside the room return if obj is not None: self.availableId += 1 print("Object") print(obj) try: interaction = Interaction(human, obj) self.interactions.append( copy.deepcopy(interaction)) except Exception: print(Exception) pass if obj not in self.objects: self.objects.append(copy.deepcopy(obj)) else: print("Repeated object which will fail")
def merge(self): # TODO: FUSION NOT APPEND ? r1 = self.interactions[random.randint(0, len(self.interactions) - 1)] r2 = self.interactions[random.randint(0, len(self.interactions) - 1)] inter = Interaction(r1.action + r2.action, r1.result + r2.result, 1) return inter
def chooseExperience(self, ite, ite_max): # TODO : Greatter babillage # babillage if len(self.actions) < 40: action = random.randint(0, self.nbacts - 1) self.last_action = action self.inter = Interaction([action], 0, 1) return action else: if len(self.todo) == 0: threshold = curiosity(ite, ite_max) epsilon = random.random() if epsilon < threshold: self.whats_next() self.last_action = self.todo.pop(0) # print("DO -----> ",self.last_action) return self.last_action else: self.inter = self.purge() self.todo = self.inter.action[:] self.last_action = self.todo.pop(0) # print("PURGE ----> ",self.last_action) return self.last_action # TODO: Increase positivity else: if len(self.todo) == 1: self.last = True self.last_action = self.todo.pop(0) # print("TODO ------> ",self.last_action) return self.last_action
def setUp(self): self.browser = webdriver.Chrome(executable_path='./driver/chromedriver') self.browser.get("https://dhaka.mrbjarke.com/") self.interaction = Interaction(self.browser) self.interaction.insert_email("*****@*****.**") self.interaction.click_email_next_button() self.interaction.insert_password("P@ssw0rd1") self.interaction.click_login() self.interaction.expand_setting_dropdown() self.interaction.select_tanant_setting() self.interaction.click_config_user_button() self.interaction.wait_for_user_table_page() del self.browser.requests self.interaction.serach_user("rony") self.interaction.busy_wait_for_table_update()
def __init__(self, client, interaction_spec): self.client = client self.cjar = {"browser": cookielib.CookieJar(), "rp": cookielib.CookieJar(), "service": cookielib.CookieJar()} self.interaction = Interaction(self.client, interaction_spec) self.features = None self.login_time = 0
def get_splits(self, df, dict, y): """For list of attributes, find best split for each and return dict of results""" result = [] #For each attribute find the split that maximizes IV for d in dict: #Unpack the dictionary: attr, corr, mincnt = (d['attr'], d['corr'], d['mincnt']) try: print "Length of x: %s, y: %s" % (len(df[attr]), len(y)) i = Interaction(df[attr], y) split = i.split(mincnt, corr, verbose=False) result.append(split) except TypeError: pass return result
def init_interaction(self): """ init user interaction and callbacks """ self.interaction = Interaction() self.interaction.register_callback('pick', self.pick) self.interaction.register_callback('move', self.move) self.interaction.register_callback('place', self.place) self.interaction.register_callback('rotate_color', self.rotate_color) self.interaction.register_callback('scale', self.scale)
def main(player_first=True): WIDTH = 3 HEIGHT = 3 board = Board(WIDTH, HEIGHT) interaction = Interaction(WIDTH, HEIGHT) computer = Computer() turn = 'X' if player_first: computer_tile = 'O' else: computer_tile = 'X' while board.get_winner() is None and not board.is_cat_game(): if turn == computer_tile: x, y = computer.get_move(board, computer_tile) board.place_tile(turn, x, y) else: x, y = interaction.get_move(turn, board) board.place_tile(turn, x, y) if turn == 'X': turn = 'O' else: turn = 'X' if board.is_cat_game(): interaction.display_cat_game(board) else: interaction.display_winner(board, board.get_winner() != computer_tile)
def saveOrUpdate(self, action, res): update = False for i in range(0, len(self.interactions)): if self.interactions[i].action == action: self.interactions[i].maj(res) update = True if not update: self.interactions.append(Interaction(action, res, 1)) # TODO : Put inter sum
def addInteractions(self, actions, valence, type = True): if not type: if not self.exist_interaction(actions, type): self._interactions.append(actions) else: if not self.exist_interaction(actions, type): #Bootstrap de l'interaction avec des valeurs connues new_interaction = Interaction(actions, valence, 1) self._interactions.append(new_interaction)
def process_ppi2(input_file, output_file, output_logfile, skipped_pmids_file=None, max_complex_size=120, min_complex_size=3): counts = Phase2Counts() logfile_fp = open(output_logfile, 'w') skipped_pmids = read_filtered_pmids(skipped_pmids_file) skipped_pmids.add(0) # this is invalid pmid - not really a paper input_fp = open(input_file, 'rU') output_fp = open(output_file, 'w') Interaction.write_header(output_fp) deflator = ComplexDeflator(logfile_fp, max_complex_size, min_complex_size) for pmid, pairs, complexes in _parse_by_pmid(input_fp): counts.initial_pairs += len(pairs) counts.C += len(complexes) counts.pmids += 1 if pmid in skipped_pmids or len(pairs) < (min_complex_size - 1): new_complexes = [] unused_pairs = pairs else: new_complexes, unused_pairs = deflator(pmid, pairs, complexes) _write_unused_pairs(output_fp, unused_pairs) _write_existing_complexes(output_fp, complexes) _write_new_complexes(output_fp, new_complexes) counts.unused_pairs += len(unused_pairs) for intr in new_complexes: code = intr.edgetype counter = getattr(counts, code) counter += 1 setattr(counts, code, counter) counts.to_file(logfile_fp) input_fp.close() output_fp.close() logfile_fp.close()
def quit(self, username): client = Interaction.get_client(username) # update client attributes client.in_env = False client.env = None send(client.conn, f'env|stop') # send to friends: out env Interaction.inform_outenv(client.username) # update env attributes self.clients.remove(client) self.usernames.remove(username) self.n_clients -= 1 # check if there is still someone if self.n_clients == 0: self.active = False else: # inform other user in env for client in self.clients: send(client.conn, f'env|quit|{username}')
def main(player_first = True): WIDTH = 3 HEIGHT = 3 board = Board(WIDTH, HEIGHT) interaction = Interaction(WIDTH, HEIGHT) computer = Computer() turn = 'X' if player_first: computer_tile = 'O' else: computer_tile = 'X' while board.get_winner() is None and not board.is_cat_game(): if turn == computer_tile: x, y = computer.get_move(board, computer_tile) board.place_tile(turn, x, y) else: x, y = interaction.get_move(turn, board) board.place_tile(turn, x, y) if turn == 'X': turn = 'O' else: turn = 'X' if board.is_cat_game(): interaction.display_cat_game(board) else: interaction.display_winner(board, board.get_winner() != computer_tile)
def addget_primitive_interaction(self, experiment, result, valence=None, meaning=None): """ If a primitive interaction is not in the INTERACTIONS dictionary, add it. Otherwise just return it. :param experiment: (str) primitive experiment :param result: (str) primitive result :param valence: (int) valence of the interaction :param meaning: (str) observer's meaning of the interaction :return: (interaction) primitive interaction from the INTERACTIONS dictionary """ label = experiment.get_label() + result.get_label() if label not in self.INTERACTIONS: interaction = Interaction(label) interaction.set_experiment(experiment) interaction.set_result(result) interaction.set_valence(valence) interaction.set_meaning(meaning) self.INTERACTIONS[label] = interaction return self.INTERACTIONS[label]
def create_interaction(): """Validate the posted json object """ request = flask.request if not request.json: print("Not json") print(request) flask.abort(400) if not Interaction.validate_interaction(request.json): flask.abort(400) interaction = Interaction(request.json) interaction_db.insertInteraction(interaction) return json.dumps(interaction, default = lambda obj: obj.__dict__), 201
def learn_composite_interaction(self, context_interaction, enacted_interaction): """ Learn a new composite interaction or reinforce it if already known. :param context_interaction: (Interaction) at time t-1 :param enacted_interaction: (Interaction) just performed """ if context_interaction is not None: label = context_interaction.get_label() + enacted_interaction.get_label() if label not in self.INTERACTIONS: # valence is a sum of primitive interactions valence = context_interaction.get_valence() + enacted_interaction.get_valence() interaction = Interaction(label) interaction.set_pre_interaction(context_interaction) interaction.set_post_interaction(enacted_interaction) interaction.set_valence(valence) self.INTERACTIONS[label] = interaction print "Learn " + label else: interaction = self.INTERACTIONS[label] print 'Incrementing weight for ', interaction interaction.increment_weight()
def chooseExperience(self, ite, ite_max): if len(self.actions) == 0: self.last_action = random.randint(0, self.nbacts - 1) return self.last_action elif self.last_reward < 0: if len(self.todo) == 0: if self.iter is not None: self.iter.maj(sum(self.vals[len(self.vals) - len(self.iter.action):])) if random.randint(0, 25) > 1: self.todo = self.what_happend() if len(self.todo) == 0: self.last_action = swap(self.last_action, self.nbacts - 1) else: print(self.last_action) seqs = [random.randrange(0, self.nbacts, 1) for _ in range(random.randint(1,self.nbacts-1*2))] temp = self.testint(seqs) if temp is None: self.iter = Interaction(seqs[:], 0, 1) self.inters.append(self.iter) else: self.iter = temp self.todo = self.iter.action[:] self.last_action = self.todo.pop(0) else: self.last_action = self.todo.pop(0) return self.last_action elif len(self.todo) > 0: self.last_action = self.todo.pop(0) return self.last_action else: if self.iter is not None: self.iter.maj(sum(self.vals[len(self.vals) - len(self.iter.action):])) return self.last_action
class Check(object): def __init__(self, client, interaction_spec): self.client = client self.cjar = {"browser": cookielib.CookieJar(), "rp": cookielib.CookieJar(), "service": cookielib.CookieJar()} self.interaction = Interaction(self.client, interaction_spec) self.features = None self.login_time = 0 def my_endpoints(self): """ :returns: All the assertion consumer service endpoints this SP publishes. """ return [e for e, b in self.client.config.getattr("endpoints", "sp")[ "assertion_consumer_service"]] def intermit(self, response): """ This method is supposed to handle all needed interactions. It also deals with redirects. :param response: A response from the IdP """ _response = response _last_action = None _same_actions = 0 if _response.status_code >= 400: done = True else: done = False url = _response.url content = _response.text while not done: rdseq = [] while _response.status_code in [302, 301, 303]: url = _response.headers["location"] if url in rdseq: raise Exception("Loop detected in redirects") else: rdseq.append(url) if len(rdseq) > 8: raise Exception( "Too long sequence of redirects: %s" % rdseq) # If back to me for_me = False for redirect_uri in self.my_endpoints(): if url.startswith(redirect_uri): # Back at the RP self.client.cookiejar = self.cjar["rp"] for_me = True try: base, query = url.split("?") except ValueError: pass else: _response = parse_qs(query) return _response if for_me: done = True break else: _response = self.client.send(url, "GET") if _response.status_code >= 400: done = True break if done or url is None: break _base = url.split("?")[0] try: _spec = self.interaction.pick_interaction(_base, content) except InteractionNeeded: cnt = content.replace("\n", '').replace("\t", '').replace("\r", '') raise Exception(cnt) except KeyError: cnt = content.replace("\n", '').replace("\t", '').replace("\r", '') raise Exception(cnt) if _spec == _last_action: _same_actions += 1 if _same_actions >= 3: print >> sys.stderr, "URL: %s" % url print >> sys.stderr, content raise Exception("Interaction loop detection") else: _last_action = _spec login_start = 0 try: page_type = _spec["page-type"] except KeyError: page_type = "" else: if page_type == "login": login_start = time.time() if page_type == "discovery": _op = Discovery(_spec["control"]) elif page_type == "js_redirect": _op = JSRedirect(_spec["control"]) else: _op = Action(_spec["control"]) try: _response = _op(self.client, self, url, _response) if page_type == "login": self.login_time = time.time() - login_start if isinstance(_response, dict): logger.debug("response: %s" % (_response,)) return _response content = _response.text logger.debug("content: %s" % content) if _response.status_code >= 400: txt = "Got status code '%s', error: %s" % ( _response.status_code, content) raise Exception(txt) except InteractionNeeded: raise except Exception, err: logger.error("%s" % err) raise
class DullAgent: def __init__(self, strategy, symb): self.strategy = strategy self.last_action = None self.actions = [] self.inters = [] self.iter = None self.results = [] self.vals = [] self.todo = [] self.best_seq = [] self.symb = symb self.motiv = 0 self.nbacts = len(symb) self.trace = "" self.ite = "" self._name = "dull" def chooseExperience(self, ite, ite_max): if len(self.actions) == 0: self.last_action = random.randint(0, self.nbacts - 1) return self.last_action elif self.last_reward < 0: if len(self.todo) == 0: if self.iter is not None: self.iter.maj(sum(self.vals[len(self.vals) - len(self.iter.action):])) if random.randint(0, 25) > 1: self.todo = self.what_happend() if len(self.todo) == 0: self.last_action = swap(self.last_action, self.nbacts - 1) else: print(self.last_action) seqs = [random.randrange(0, self.nbacts, 1) for _ in range(random.randint(1,self.nbacts-1*2))] temp = self.testint(seqs) if temp is None: self.iter = Interaction(seqs[:], 0, 1) self.inters.append(self.iter) else: self.iter = temp self.todo = self.iter.action[:] self.last_action = self.todo.pop(0) else: self.last_action = self.todo.pop(0) return self.last_action elif len(self.todo) > 0: self.last_action = self.todo.pop(0) return self.last_action else: if self.iter is not None: self.iter.maj(sum(self.vals[len(self.vals) - len(self.iter.action):])) return self.last_action def get_reward(self, result): self.last_result = result self.last_reward = self.strategy.get_reward(result, self.last_action) self.motiv += self.last_reward self.ev() return self.last_reward def memory(self): action = self.last_action reward = self.last_reward self.actions.append(action) self.vals.append(reward) self.results.append(self.last_result) def what_happend(self): nb = len(self.symb) seqs = [] vas = -math.inf if len(self.actions) > 2 * nb + 1: lasts = self.actions[len(self.actions) - nb + 1:] inds = self.subfinder(lasts) for i in inds: found = False temp = [] tempi = 0 y = 0 while len(self.actions) - 3 > i + nb + y and (y == nb or self.vals[i + nb + y - 1] < 0): temp.append(self.actions[i + nb + y]) potit = self.testint(seqs) if potit is None: tempi += self.vals[i + nb + y] -(0.5 * len(seqs)) else: tempi += potit.proclivity -(0.5 * len(seqs)) y += 1 if self.vals[i + nb + y - 1] > 0: found = True # = pour prendre la dernière -> plus de chance d'être mieux if found: if tempi >= vas and tempi > -100: seqs = temp[:] vas = tempi if len(seqs) > 0: temp = self.testint(seqs) if temp is None: self.iter = Interaction(seqs[:], 0, 1) self.inters.append(self.iter) else: self.iter = temp elif random.randint(0, 1) == 0: seqs = [random.randrange(0, self.nbacts, 1) for _ in range(random.randint(1,self.nbacts-1*2))] temp = self.testint(seqs) if temp is None: self.iter = Interaction(seqs[:], vas, 1) self.inters.append(self.iter) else: self.iter = temp return seqs ''' Test if int exist in mem''' def testint(self, acts): for i in range(0, len(self.inters) - 1): if self.inters[i].action == acts: return self.inters[i] return None def subfinder(self, pattern): todo = self.actions[:] nb = 0 pos = [] for i in range(0, len(todo)): if todo[i] == pattern[0] and todo[i:i + len(pattern)] == pattern: pos.append(i) nb += 1 if len(pos) > 1: return pos[:-1] else: return [] ''' -------------------- Debug & Display --------------------''' def show_trace(self): print(self.trace) print(self.ite) def pres(self): print("Salut, ", end="") if len(self.todo) > 0: print("j'ai ", end="") print('\x1b[6;30;42m' + str(self.todo) + '\x1b[0m', end="") print("a faire.") print("Mon historique est de : " + str(self.actions)) print("pour : " + str(self.vals)) def tracer(self, reward, i): if reward > 0: mess = '\x1b[0;30;46m' else: mess = '\x1b[5;30;41m' space = "" for y in range(0, len(str(i))): space += " " self.trace += mess + str(self.symb[self.last_action]) + '\x1b[0m' + space self.ite += str(i) + " " ''' Objectif : @debug ''' def print_interactions(self, max=False): print("----------------------------------") for i in self.inters: if max: if i.result > 0: print(i) else: print(i) print("----------------------------------") def ev(self): for it in self.inters: it.evaporate()
class Viewer(object): def __init__(self): """ Initialize the viewer. """ self.init_interface() self.init_opengl() self.init_scene() self.init_interaction() init_primitives() def init_interface(self): """ initialize the window and register the render function """ glutInit() glutInitWindowSize(640, 480) glutCreateWindow("3D Modeller") glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) glutDisplayFunc(self.render) def init_interaction(self): """ init user interaction and callbacks """ self.interaction = Interaction() self.interaction.register_callback('pick', self.pick) self.interaction.register_callback('move', self.move) self.interaction.register_callback('place', self.place) self.interaction.register_callback('rotate_color', self.rotate_color) self.interaction.register_callback('scale', self.scale) def init_scene(self): """ initialize the scene object and initial scene """ self.scene = Scene() self.initial_scene() def init_opengl(self): """ initialize the opengl settings to render the scene """ self.inverseModelView = numpy.identity(4) self.modelView = numpy.identity(4) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glEnable(GL_LIGHT0) glLightfv(GL_LIGHT0, GL_POSITION, GLfloat_4(0, 0, 1, 0)) glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, GLfloat_3(0, 0, -1)) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glEnable(GL_COLOR_MATERIAL) glClearColor(1.0, 1.0, 1.0, 0.0) def main_loop(self): glutMainLoop() def render(self): """ The render pass for the scene """ self.init_view() # Enable lighting and color glEnable(GL_LIGHTING) glClearColor(0.4, 0.4, 0.4, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Load the modelview matrix from the current state of the trackball glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() loc = self.interaction.translation glTranslated(-loc[0], -loc[1], -loc[2]) glMultMatrixf(self.interaction.trackball.matrix) # store the inverse of the current modelview. currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX)) self.modelView = numpy.transpose(currentModelView) self.inverseModelView = inv(numpy.transpose(currentModelView)) # render the scene. This will call the render function for each object in the scene self.scene.render() # draw the grid glDisable(GL_LIGHTING) glCallList(G_OBJ_PLANE) glPopMatrix() # flush the buffers so that the scene can be drawn glFlush() def init_view(self): """ initialize the projection matrix """ xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT) aspect_ratio = float(xSize) / float(ySize) # load the projection matrix. Always the same glMatrixMode(GL_PROJECTION) glLoadIdentity() glViewport(0, 0, xSize, ySize) gluPerspective(70, aspect_ratio, 0.1, 1000.0) glTranslated(0, 0, -15) def initial_scene(self): cube_node = Cube() cube_node.translate(2, 0, 2) cube_node.color_index = 2 self.scene.add_node(cube_node) sphere_node = Sphere() sphere_node.translate(-2, 0, 2) sphere_node.color_index = 3 self.scene.add_node(sphere_node) sphere_node_2 = Sphere() sphere_node_2.translate(-2, 0, -2) sphere_node_2.color_index = 1 self.scene.add_node(sphere_node_2) def get_ray(self, x, y): """ Generate a ray beginning at the near plane, in the direction that the x, y coordinates are facing Consumes: x, y coordinates of mouse on screen Return: start, direction of the ray """ self.init_view() glMatrixMode(GL_MODELVIEW) glLoadIdentity() # get two points on the line. start = numpy.array(gluUnProject(x, y, 0.001)) end = numpy.array(gluUnProject(x, y, 0.999)) # convert those points into a ray direction = end - start direction = direction / norm(direction) return (start, direction) def pick(self, x, y): """ Execute pick of an object. Selects an object in the scene. """ start, direction = self.get_ray(x, y) self.scene.pick(start, direction, self.modelView) def move(self, x, y): """ Execute a move command on the scene. """ start, direction = self.get_ray(x, y) self.scene.move(start, direction, self.inverseModelView) def place(self, shape, x, y): """ Execute a placement of a new primitive into the scene. """ start, direction = self.get_ray(x, y) self.scene.place(shape, start, direction, self.inverseModelView) def rotate_color(self, forward): """ Rotate the color of the selected Node. Boolean 'forward' indicates direction of rotation. """ self.scene.rotate_color(forward) def scale(self, up): """ Scale the selected Node. Boolean up indicates scaling larger.""" self.scene.scale(up)