def setUp(self): self.trans = transition.Transition({('0','a','1')}) self.trans.put('0','b','1') self.trans.put('1','b','0') self.trans.put('0','c','1') self.trans.put('0','a','2') self.trans.put('0','e','1')
def test_lcm(self): tests = [ [2, 3, 6] ] for test in tests: t = trans.Transition() self.assertEqual(t._lcm(test[0], test[1]), test[2])
def __init__(self, screen): self.screen = screen self.accept_input = True self.animation = None # current playing animation self.state = ACTIVE # state that the game starts with. change to experience various features self.pallet_town_map = map.Map( pygame.image.load(os.path.join('maps', 'pallet_town.png')), (-64 * 5, 0)) self.mc = actor.Actor( pygame.image.load(os.path.join('actors', 'mc_final.png')), 64 * 4 + 4, 64 * 4) self.actor_group = pygame.sprite.Group(self.mc) # Initialize a screen transition self.trans = transition.Transition(screen) self.trans.order_swirl() # Initialize a text manager self.txtmgr = textmanager.Textmanager(screen) # Do this only if DIALOGUE is the initial game state if self.state == DIALOGUE: self.txtmgr.set_string('Boogah boogah boogah!') # Initiate a battle manager self.btlmgr = battlemanager.BattleManager(screen)
def finished(self, reply): """Override the reply finished signal to check the result of each request. The function records statistics and keep data related to relevant HTTP requests (the transitions attribute). """ common.logger.debug('Response: {} {}'.format(reply.url().toString(), reply.data)) if not reply.content: return # no response so reply is not of interest self.stats.add_response(reply.content) reply.content_type = reply.header( QNetworkRequest.ContentTypeHeader).toString().lower() referrer = reply.orig_request.rawHeader("Referer") self.response_writer.writerow([ reply.url().toString(), reply.content_type, referrer, len(reply.content) ]) visualisation.WrapperLog.new_edge(reply.url().toString(), reply.content_type, referrer, len(reply.content)) if re.match('(image|audio|video|model|message)/', reply.content_type) or reply.content_type == 'text/css': pass # ignore irrelevant content types such as media and CSS else: # have found a response that can potentially be parsed for useful content # save for checking later once interface has been updated self.transitions.append(transition.Transition(reply))
def test_get_transition_color_window(self): attributes = ['color1', 'color2', 'range', 'period', 'func', 'direction', 'trans_type', 'use_window'] tests = [ # [[[color1, color2, range, period, func, direction, trans_type, use_window]], step_number, window_size, result] [[[(255,0,0), (0,255,0), (0,10), 10, lambda x: 1 if x < 8 else 0, 1, 'base', True]], 1, 10, [(255,0,0),(255,0,0),(255,0,0),(0,255,0),(0,255,0),(0,255,0),(0,255,0),(0,255,0),(0,255,0),(0,255,0)]], [[[(255,0,0), (0,255,0), (0,10), 10, lambda x: 1 if x < 8 else 0, -1, 'base', True]], 1, 10, [(0,255,0),(0,255,0),(0,255,0),(0,255,0),(0,255,0),(0,255,0),(0,255,0),(255,0,0),(255,0,0),(255,0,0)]] ] # step across the tests for test in tests: # instantiate the Transition class t = trans.Transition() # step across the color functions for f in test[0]: cf = colorfunc.ColorFunc() # set color1 cf.color1 = rgb.RGB() cf.color1.color = f[0] # set color2 cf.color2 = rgb.RGB() cf.color2.color = f[1] # set the remaining attributes for a in range(2,len(attributes)): setattr(cf, attributes[a], f[a]) t.color_funcs.append(cf) # get the color window t.get_transition_window(test[1])
def add_transition(self): """ Create a new transition component with default settings and forwards it to the ControllerDrawingArea which is responsible for displaying it. """ if self._controller_drawing_area != None: # reset previous settings self._model.notify_reset() # instantiate new transitions object self._component = transition.Transition() self._component.label = "New Transition" self._component.key = "new_comp" self._component.rate = 1 self._component.dimension = [15, 30] # check if transitions are already available and if yes the size of them is used as template (zoom could be activated) adapt = False if self._model.data != None: for key, item in self._model.data.transitions.items(): if item != None: self._component.dimension = item.dimension adapt = True break # if no place is available it will be checked for available places which could be used as template to keep the proportions constant # between different component types if not adapt: for key, item in self._model.data.places.items(): if item != None: self._component.dimension = [item.radius, 2 * item.radius] adapt = True break # forward component if self._controller_drawing_area != None: self._controller_drawing_area.add_component(True, self._component)
def test_get_color_trans_func(self): t = trans.Transition() base = t._get_color_trans_func('base') black = t._get_color_trans_func('black') white = t._get_color_trans_func('white') self.assertEqual(base, t._get_base_transition) self.assertEqual(black, t._get_black_transition) self.assertEqual(white, t._get_white_transition)
def go_to_next_scene(self): next_scene = self.next_scene(self.world) last_scene = self if self.must_interpolate: self.world.change_scene(transition.Transition(self.world, last_scene, next_scene)) else: self.world.change_scene(next_scene)
def test_get_func_period_list(self): tests = [ [3, 77, 34, [3, 80, 114]], [[]] ] for test in tests: t = trans.Transition() funcs = [] for i in range(len(test)-1): cf = colorfunc.ColorFunc() cf.period = test[i] funcs.append(cf) self.assertEqual(t._get_func_period_list(funcs), test[len(test)-1])
def __init__(self, identify=0, etats=set(), etat_init=None, etats_final=set(), alphabet=set(), trans=transition.Transition()): self.__identify = identify self.__etats = etats self.__etat_init = etat_init self.__etats_final = etats_final self.__alphabet = alphabet self.__trans = trans
def test_get_period_lcm(self): tests = [ [[2], [3], [5], 30], [[17], [], [], 17], ] func_types = [ ('color_funcs', colorfunc.ColorFunc), ('brightness_funcs', brightnessfunc.BrightnessFunc), ('white_level_funcs', whitelevelfunc.WhiteLevelFunc) ] for test in tests: t = trans.Transition() for ft in range(len(func_types)): for i in range(len(test[ft])): cf = colorfunc.ColorFunc() cf.period = test[ft][i] getattr(t, func_types[ft][0]).append(cf) self.assertEqual(t.get_period_lcm(), test[len(test)-1])
def test_get_color_transition_distance(self): # define tests tests = [ [(255,0,0), (0,255,0), 0.5, 510, (255,255,0)], [(255,0,0), (0,255,0), 0, 510, (255,0,0)], [(255,0,0), (0,255,0), 1, 510, (0,255,0)], [(255,0,0), (0,255,0), 0.333, 510, (255,170,0)], [(255,0,0), (0,45,255), 0.75, 555, (94, 0, 255)] ] # do the test for test in tests: c1 = rgb.RGB() c1.color = test[0] c2 = rgb.RGB() c2.color = test[1] t = trans.Transition() dist = t._get_color_transition_distance(c1, c2, type='base') self.assertEqual(dist, test[3]) result = t._get_color_transition_color(c1, c2, test[2]*dist, type='base') self.assertEqual(result.color, test[4])
def test_get_period_lcm_no_funcs(self): # should raise with self.assertRaises(ValueError): t = trans.Transition() t.get_period_lcm()
def transition_probability(self, prev_state, cur_state, transition_probabilities: dict) -> float: """Returns zero probability for non-existing transitions.""" transition_prob = transition_probabilities.get( transition.Transition(prev_state, cur_state)) return 0 if transition_prob is None else transition_prob
def loop(self): t = transition.Transition() shutdown = False while shutdown is not True: task = t.getTask() task.execute()
def load_demonstration(self, isnpy=False): if isnpy: self.replay_buff.load_data(dir_path) else: hdf5file = h5py.File(DEMO_PATH, "r") folder = "demodata_" + str(0) state1 = hdf5file[folder + "/state1"].value state2 = hdf5file[folder + "/state2"].value actions = hdf5file[folder + "/actions"].value isterminals = hdf5file[folder + "/isterminals"].value health = hdf5file[folder + "/healths"].value ammo = hdf5file[folder + "/ammos"].value posx = hdf5file[folder + "/posxs"].value posy = hdf5file[folder + "/posys"].value death = hdf5file[folder + "/deaths"].value frag = hdf5file[folder + "/frags"].value for i in range(1, N_FOLDER): folder = "demodata_" + str(i) state1 = np.concatenate( (state1, hdf5file[folder + "/state1"].value), axis=0) state2 = np.concatenate( (state2, hdf5file[folder + "/state2"].value), axis=0) actions = np.concatenate( (actions, hdf5file[folder + "/actions"].value), axis=0) isterminals = np.concatenate( (isterminals, hdf5file[folder + "/isterminals"].value), axis=0) health = np.concatenate( (health, hdf5file[folder + "/healths"].value), axis=0) ammo = np.concatenate( (ammo, hdf5file[folder + "/ammos"].value), axis=0) posx = np.concatenate( (posx, hdf5file[folder + "/posxs"].value), axis=0) posy = np.concatenate( (posy, hdf5file[folder + "/posys"].value), axis=0) death = np.concatenate( (death, hdf5file[folder + "/deaths"].value), axis=0) frag = np.concatenate( (frag, hdf5file[folder + "/frags"].value), axis=0) n_transit, n_step, _ = actions.shape print("SIZE of DEMO:", actions.shape) transit = np.empty((n_step, ), dtype=object) is_dead = False is_finished = False pre_health = 100 pre_ammo = 15 pre_frag = 0 pre_death = 0 pre_posx = 0.0 pre_posy = 0.0 for i in range(n_transit): if i % 2 == 0: pre_posx = posx[i][0] pre_posy = posy[i][0] for j in range(n_step): if not is_finished: if is_dead: pre_posx = posx[i][j] pre_posy = posy[i][j] is_dead = False m_frag = frag[i][j] - pre_frag m_death = death[i][j] - pre_death m_health = health[i][j] - pre_health m_ammo = ammo[i][j] - pre_ammo m_posx = posx[i][j] - pre_posx m_posy = posy[i][j] - pre_posy if m_death >= 1: is_dead = True if isterminals[i][j] == True: is_finished = True r_d = self.reward_gen.calc_reward( m_frag, m_death, m_health, m_ammo, m_posx, m_posy) r = sum(r_d.values()) transit[j] = transition.Transition( state1[i][j], actions[i][j], state2[i][j], r, isterminals[i][j], True) pre_frag = frag[i][j] pre_death = death[i][j] pre_health = health[i][j] pre_ammo = ammo[i][j] else: transit[j] = transition.Transition( None, None, None, None, True, True) is_finished = False self.replay_buff.store(np.copy(transit))
from pathlib import Path import os os.chdir('@ANGCORR_PYTHON_DIR@') from time import time from asymmetry_plot import AngularCorrelation, AsymmetryPlotter import state as st import transition as tr t_start = time() ang_cor = AngularCorrelation( st.State(3, st.POSITIVE), [ [tr.Transition(tr.ELECTRIC, 4, tr.MAGNETIC, 6, 0.), st.State(7, st.POSITIVE)], [tr.Transition(tr.EM_UNKNOWN, 2, tr.EM_UNKNOWN, 4, 0.), st.State(5, st.PARITY_UNKNOWN)], ], ['delta_1', 'delta_2'] ) arctan_deltas, asy_45, asy_90 = ang_cor.asymmetry_grid(n_delta_steps=301) asy_plo = AsymmetryPlotter(ang_cor, arctan_deltas, asy_45, asy_90, scale_asymmetries=True, asy_45_exp=[-0.4, 0.1, 0.1], asy_90_exp=[-0.5, 0.1, 0.1], show_polarization=[True, False]) output_file_single_2d = Path('@PROJECT_BINARY_DIR@') / 'test_plot_04_mixing_inelastic_asy_2d.pdf' asy_plo.plot_single_2d(r'$\delta_1$', [r'$\delta_1$', r'$\delta_2 = \delta_1$'], False, output_file_single_2d) output_file_single_3d = Path('@PROJECT_BINARY_DIR@') / 'test_plot_04_mixing_inelastic_asy_3d.pdf'
else: delta_labels.append(r'$\delta_u$' if variable_delta_label is None else variable_delta_label) variable_delta_label = delta_labels[-1] else: delta_labels.append('') return (variable_delta_label, delta_labels) ang_cors = [ [ '02_mixing_single', AngularCorrelation(st.State(0, st.POSITIVE), [ [ tr.Transition(tr.MAGNETIC, 2, tr.ELECTRIC, 4, 0.), st.State(2, st.POSITIVE) ], [ tr.Transition(tr.EM_UNKNOWN, 2, tr.EM_UNKNOWN, 4, 0.), st.State(2, st.PARITY_UNKNOWN) ], ], [0., 'delta_1']), False, [-0.5, 0.1, 0.1], [-0.8, 0.2, 0.2], ['ana_011.pdf', '', ''] ], [ '03_mixing_elastic', AngularCorrelation(st.State(1, st.POSITIVE), [ [ tr.Transition(tr.MAGNETIC, 2, tr.ELECTRIC, 4, 0.), st.State(3, st.POSITIVE)
def test_get_color_trans_func_invalid_transition_type(self): # should raise with self.assertRaises(ValueError): t = trans.Transition() t._get_color_trans_func('wrong')
def test_forward_backward(self): """Example taken from https://en.wikipedia.org/wiki/Forward%E2%80%93backward_algorithm.""" candidates = [Rain.T, Rain.F] initial_state_probabilities = { Rain.T: 0.5, Rain.F: 0.5, } emission_probabilities_for_umbrella = { Rain.T: 0.9, Rain.F: 0.2, } emission_probabilities_for_no_umbrella = { Rain.T: 0.1, Rain.F: 0.8, } transition_probabilities = { transition.Transition(Rain.T, Rain.T): 0.7, transition.Transition(Rain.T, Rain.F): 0.3, transition.Transition(Rain.F, Rain.T): 0.3, transition.Transition(Rain.F, Rain.F): 0.7, } fw = forward_backward_algorithm.ForwardBackwardAlgorithm() fw.start_with_initial_state_probabilities(candidates, initial_state_probabilities) fw.next_step(Umbrella.T, candidates, emission_probabilities_for_umbrella, transition_probabilities) fw.next_step(Umbrella.T, candidates, emission_probabilities_for_umbrella, transition_probabilities) fw.next_step(Umbrella.F, candidates, emission_probabilities_for_no_umbrella, transition_probabilities) fw.next_step(Umbrella.T, candidates, emission_probabilities_for_umbrella, transition_probabilities) fw.next_step(Umbrella.T, candidates, emission_probabilities_for_umbrella, transition_probabilities) result = fw.compute_smoothing_probabilities() self.assertEqual(len(result), 6) DELTA = 1e-4 self.assertTrue(abs(result[0][Rain.T] - 0.6469) <= DELTA) self.assertTrue(abs(result[0][Rain.F] - 0.3531) <= DELTA) self.assertTrue(abs(result[1][Rain.T] - 0.8673) <= DELTA) self.assertTrue(abs(result[1][Rain.F] - 0.1327) <= DELTA) self.assertTrue(abs(result[2][Rain.T] - 0.8204) <= DELTA) self.assertTrue(abs(result[2][Rain.F] - 0.1796) <= DELTA) self.assertTrue(abs(result[3][Rain.T] - 0.3075) <= DELTA) self.assertTrue(abs(result[3][Rain.F] - 0.6925) <= DELTA) self.assertTrue(abs(result[4][Rain.T] - 0.8204) <= DELTA) self.assertTrue(abs(result[4][Rain.F] - 0.1796) <= DELTA) self.assertTrue(abs(result[5][Rain.T] - 0.8673) <= DELTA) self.assertTrue(abs(result[5][Rain.F] - 0.1327) <= DELTA)
def run(self): # global frames,runout global frames self.start_episode() train_episode = 0 step = 0 transitions = np.empty((N_ADV, ), dtype=object) for step in tqdm(range(N_STEPS)): if not self.game.is_episode_finished(): if step % N_ADV == 0 and not step == 0: self.replay_buff.store(np.copy(transitions)) self.reward_gen.update_origin( self.game.get_game_variable(GameVariable.POSITION_X), self.game.get_game_variable(GameVariable.POSITION_Y)) s1 = self.preprocess(self.game.get_state().screen_buffer) action = self.agent.act_eps_greedy(s1) action_idx = action.index(1) self.game.make_action(action) reward, _ = self.get_reward() isterminal = self.game.is_episode_finished() s2 = self.preprocess(self.game.get_state().screen_buffer ) if not isterminal else None transitions[step % 10] = transition.Transition( s1, action_idx, s2, reward, isterminal, False) if self.game.is_player_dead(): self.game.respawn_player() self.reward_gen.respawn_pos( self.game.get_game_variable(GameVariable.HEALTH), self.game.get_game_variable( GameVariable.SELECTED_WEAPON_AMMO), self.game.get_game_variable(GameVariable.POSITION_X), self.game.get_game_variable(GameVariable.POSITION_Y)) else: train_episode += 1 self.start_episode() self.reward_gen.new_episode( health=self.game.get_game_variable(GameVariable.HEALTH), ammo=self.game.get_game_variable( GameVariable.SELECTED_WEAPON_AMMO), posx=self.game.get_game_variable(GameVariable.POSITION_X), posy=self.game.get_game_variable(GameVariable.POSITION_Y)) self.local_step += 1 frames += 1 step += 1 self.agent.batch_learn() if frames % FREQ_COPY: self.network.copy_params() if frames % FREQ_TEST == 0: steps_test, r, r_d, f, d = self.test_score() print("\t TEST at ", frames) print("\t SPEND STEPS:", steps_test) print("\tFRAG:", f, "DEATH:", d, "REWARD:", r) print("\t", r_d) self.agent.q_network.write_score(step=frames, reward=r, frag=f, death=d) self.start_episode() self.reward_gen.new_episode( health=self.game.get_game_variable(GameVariable.HEALTH), ammo=self.game.get_game_variable( GameVariable.SELECTED_WEAPON_AMMO), posx=self.game.get_game_variable(GameVariable.POSITION_X), posy=self.game.get_game_variable(GameVariable.POSITION_Y)) print(self.name, " finished") self.finished = True
if not game.is_episode_finished(): s1 = preprocess(game.get_state().screen_buffer) game.advance_action(frame_repeat) reward = game.get_last_reward() action = game.get_last_action() if action in actions: total_reward += reward print(reward, end=',') idx = actions.index(action) isterminal = game.is_episode_finished() if not isterminal: s2 = preprocess(game.get_state().screen_buffer) else: s2 = None transitionset[step] = transition.Transition( s1, idx, s2, reward, isterminal, True) step += 1 else: transitionset[step] = transition.Transition( None, None, None, None, True, True) step += 1 print("\n") replaymemory.store(np.copy(transitionset)) total_reward = np.array(total_reward) print("Results: mean: %.1f(+-)%.1f," % (total_reward.mean(), total_reward.std()), \ "min: %.1f," % total_reward.min(), "max: %.1f," % total_reward.max()) replaymemory.save_data()
import anim import parameters import rect import os.path from draw import * from draw import _embed try: import dxvideo video_available = 1 video_select_keys = '0123456789' except ImportError: video_available = 0 linear = transition.Transition() exports = [ 'Drawable', 'Text', 'Image', 'Fill', 'BulletedList', 'Anim', 'Interactive', 'Video' ] default_camera = rect.Rect(0, 0, 400, 0, 4.0 / 3.0) class Element(object): def __str__(self): return '<animation element>' def __getattr__(self, name): if name == '_current_params' or name == '_params':
def convert(self): """ Start converting process from matrices to components. """ # Information: A lot of exceptions will be thrown because of the NoneType issue we had and it is necessary to prevent the appliation from crashing. # create a PetriNet object self._pn = petri_net.PetriNet() # set PetriNetData object self._pn.data = self._data try: # create the individual places for i in range(len(self._data.places)): # set default values for the design p = place.Place([0.0, 0.0], 15., [0., 0., 0.], [255., 255., 255.]) # set properties p.label = self._data.places[i] p.key = self._data.places[i] if self._data.initial_marking != None: p.marking = self._data.initial_marking[i] try: if self._data.capacities != None: p.capacity = self._data.capacities[i] except IndexError: pass # add place to the PetriNet object self._pn.add_place(p, ) except TypeError: pass try: # create the individual transitions for i in range(len(self._data.transitions)): # set default values for the design t = transition.Transition([0.0, 0.0], [15, 30], [0., 0., 0.], [0., 0., 0.]) # set properties t.label = self._data.transitions[i] t.key = self._data.transitions[i] if self._data.rates != None: t.rate = self._data.rates[i] # add transition to the PetirNet object self._pn.add_transition(t) except TypeError: pass try: # create the individual arcs connecting two nodes for i in range(len(self._data.transitions)): for j in range(len(self._data.places)): a_pre = None a_post = None a_test = None a_inhib = None # iteration through the matrices to figure out which arc needs to be created try: if self._data.stoichiometry.pre_arcs != None: try: if self._data.stoichiometry.pre_arcs[ i, j] != None: if self._data.stoichiometry.pre_arcs[ i, j] != 0: # create a standard pre arc a_pre = arc.Arc() a_pre.line_type = arc.Arc.LINE_TYPE_STRAIGHT a_pre.label = str( "Arc" + self._data.places[j] + "to" + self._data.transitions[i]) a_pre.key = str( "Arc" + self._data.places[j] + "to" + self._data.transitions[i]) a_pre.origin = self._pn.get_component( self._data.places[j]) a_pre.target = self._pn.get_component( self._data.transitions[i]) if self._data.stoichiometry.pre_arcs != None: a_pre.weight = self._data.stoichiometry.pre_arcs[ i, j] # add arc to the PetriNet object self._pn.add_arc(a_pre) except IndexError: pass except TypeError: pass try: if self._data.stoichiometry.post_arcs != None: try: if self._data.stoichiometry.post_arcs[ i, j] != None: if self._data.stoichiometry.post_arcs[ i, j] != 0: # create a standard post arc a_post = arc.Arc() a_post.line_type = arc.Arc.LINE_TYPE_STRAIGHT a_post.label = str( self._data.transitions[i] + "to" + self._data.places[j]) a_post.key = str( self._data.transitions[i] + "to" + self._data.places[j]) a_post.origin = self._pn.get_component( self._data.transitions[i]) a_post.target = self._pn.get_component( self._data.places[j]) if self._data.stoichiometry.post_arcs != None: a_post.weight = self._data.stoichiometry.post_arcs[ i, j] # add arc to the PetriNet object self._pn.add_arc(a_post) except IndexError: pass except TypeError: pass try: if self._data.test_arcs != None: try: if self._data.test_arcs[i, j] != None: if self._data.test_arcs[i, j] != 0: # create a test arc a_test = test_arc.TestArc() a_test.line_type = test_arc.TestArc.LINE_TYPE_ARC_LOWER a_test.label = str( "TestArc" + self._data.transitions[i] + "to" + self._data.places[j]) a_test.key = str( "TestArc" + self._data.transitions[i] + "to" + self._data.places[j]) a_test.target = self._pn.get_component( self._data.transitions[i]) a_test.origin = self._pn.get_component( self._data.places[j]) if self._data.test_arcs != None: a_test.weight = self._data.test_arcs[ i, j] # add arc to the PetriNet object self._pn.add_arc(a_test) except IndexError: pass except TypeError: pass try: if self._data.inhibitory_arcs != None: try: if self._data.inhibitory_arcs[i, j] != None: if self._data.inhibitory_arcs[i, j] != 0: # create an inhibitory arc a_inhib = inhibitory_arc.InhibitoryArc( ) a_inhib.line_type = inhibitory_arc.InhibitoryArc.LINE_TYPE_ARC_UPPER a_inhib.label = str( "InhibitoryArc" + self._data.transitions[i] + "to" + self._data.places[j]) a_inhib.key = str( "InhibitoryArc" + self._data.transitions[i] + "to" + self._data.places[j]) a_inhib.target = self._pn.get_component( self._data.transitions[i]) a_inhib.origin = self._pn.get_component( self._data.places[j]) if self._data.inhibitory_arcs != None: a_inhib.weight = self._data.inhibitory_arcs[ i, j] # add arc to the PetriNet object self._pn.add_arc(a_inhib) except IndexError: pass except TypeError: pass # determine the style of the line automatically # if two standard arcs are available the curved arcs will be chosen if a_pre != None and a_post != None: a_pre.line_type = arc.Arc.LINE_TYPE_ARC_LOWER self._pn.update(a_pre, a_pre.key) a_post.line_type = arc.Arc.LINE_TYPE_ARC_UPPER self._pn.update(a_post, a_post.key) except TypeError: pass # print len(self._pn.arcs) # if an algorithm is defined the positions of the components will be determined if self._layout != None: self.__layout_components()