def test_save_and_retrieve_energy(): energy = Energy(10, 5) with time_traveler() as T: T( 0); assert energy == 10 T( 1); energy.use(5) T( 2); assert energy == 5 T(3) saved = energy.used saved_used, saved_used_at = energy.used, energy.used_at T(11) assert energy == 7 loaded_energy = Energy(10, 5, used=saved_used, used_at=saved_used_at) assert loaded_energy == 7 assert loaded_energy == energy loaded_energy2 = Energy(10, 5) loaded_energy2.used = saved_used loaded_energy2.used_at = saved_used_at assert loaded_energy2 == 7 assert loaded_energy2 == energy loaded_energy3 = object.__new__(Energy) loaded_energy3.__init__(10, 5, used=saved_used, used_at=saved_used_at) assert loaded_energy3 == 7 assert loaded_energy3 == energy loaded_energy4 = object.__new__(Energy) loaded_energy4.used = saved_used loaded_energy4.used_at = saved_used_at loaded_energy4.__init__(10, 5, used=saved_used, used_at=saved_used_at) assert loaded_energy4 == 7 assert loaded_energy4 == energy
def __init__(self, config): ACharger.__init__(self, config) from relay08 import get_three_way_cutter from energy import Energy self.charger = get_three_way_cutter() self.config = config self.energy = Energy()
def init_energy(): energy = Energy(10, 10) assert isinstance(energy.recovery_interval, int) assert energy.recovery_interval == 10 energy = Energy(10, timedelta(seconds=10)) assert isinstance(energy.recovery_interval, (int, float)) assert energy.recovery_interval == 10
class Game: def __init__(self, world, datadir, configdir): self.world = world self.datadir = datadir self.configdir = configdir self.enemies = [] self.stage = Stage(self) self.sprites = Group(self.stage) self.screen = world.screen # Visor de energia para el enemigo self._create_player() self.energy = Energy(10, 10, 100, 10) self.energy.set_model(self.player.id) self.stage.player = self.player self.stage.load_level(1) if VISIBLE_DEBUG: # Visor de rendimiento self.text = Text(world.font, world.fps, "FPS: %d") def _create_player(self): control = Control(0, self.configdir) self.player = Player(self, control, self.sprites, self.datadir) shadow_player = Shadow(self.player, self.datadir) self.sprites.add([self.player, shadow_player]) def update(self): self.stage.update() self.sprites.update() self.energy.update() if VISIBLE_DEBUG: self.text.update() if DEBUG: b1, b2, b3 = pygame.mouse.get_pressed() if b1: self.stage.do_camera_effect() elif b2: self.stage.do_camera_effect(10) elif b3: self.world.fps.slow() def draw(self): self.stage.draw(self.screen) self.sprites.draw(self.screen) self.screen.blit(self.energy.image, self.energy.rect) if VISIBLE_DEBUG: self.screen.blit(self.text.image, self.text.rect) pygame.display.flip()
def equivalent_energy(): assert Energy(10, 10) == Energy(10, 10) assert Energy(5, 10) != Energy(10, 10) e1, e2 = Energy(10, 10), Energy(10, 10) e1.use(time=123) e2.use(time=123) assert e1 == e2 e1.use(time=128) assert e1 != e2
def cast_energy(): true_energy = Energy(1, 1000) false_energy = Energy(0, 1000) assert int(true_energy) == 1 assert int(false_energy) == 0 assert float(true_energy) == 1.0 assert float(false_energy) == 0.0 assert bool(true_energy) is True assert bool(false_energy) is False
def __init__(self,name,imagefile,context,skills=[],factionid=0): """ """ model = [ (0,0), (0,181), (100,181), (100,0) ] bounding_rect = [ (0,0), (0,181), (100,181), (100,0) ] #super( Character, self ).__init__( model, imagefile, offset=(0,50) ) _model = Vertel() _model.set( [ ( 0.0, 0.0, 0.0 ), ( 0.0, 171.0/600.0, 0.0 ), ( 101.0/800.0, 171.0/600.0,0.0 ), ( 101.0/800.0 , 0.0, 0.0 ) ] ) _bound = Vertel() _bound.set( [ ( 0.0, 0.0, 0.0 ), ( 0.0, 100.0/600, 0.0 ), ( 100.0/800.0, 100.0/600, 0.0 ), ( 100.0/800, 0.0, 0.0 ) ] ) super( Character, self ).__init__( imagefile, _model, _bound ) #self.name = kwargs.get('name',"Unnamed") self.name = name self.mind = Mind( ego=self, factionid=factionid ) self._controller = None self._context = context self._target = None #body stats self.strength = 10 #strength of character, in kg*m*s^-2 self.agility = 20 #agility of character, in kg*m*s^-2 self.endurance = 10 #endurance: MAX Energy Reserves, in #endurance #endurance: MAX energy output in watts in kg*m^2*s^-3 self._reach = 1.0 #arm length self._mass = 50 #mass of character, in kg self.health = 100 # self.energy = Energy() self._alive = True #alive bit, used to drop a character object references #skills self.skillbook = SkillBook(skills=skills) self.deck = Deck(maxsize=4, slots=['default']*6 ) #equipment self._equipment = Equipment() #equipment is currently held by the character self.inventory = Inventory(40.0) #items in storage self.weapon = None #modifiers self.buff = Buffable(self) #allows the character to be buffed (stat and status effects) self.status_effects = [] self._wounds = []
def initial_print(partial_state): print('The initial potential energy is:') print(np.average(Energy.potential_energy(partial_state))/pow(MPl, 4)) print('Initial Phi Gradient energy is:') print(np.average(Energy.phi_gradient_energy(partial_state))/pow(MPl, 4)) print('Initial Chi Gradient energy is:') print(np.average(Energy.chi_gradient_energy(partial_state))/pow(MPl, 4)) print('Initial Phi Kinetic energy is:') print(np.average(Energy.phi_kinetic_energy(partial_state))/pow(MPl, 4)) print('Initial Chi Kinetic energy is:') print(np.average(Energy.chi_kinetic_energy(partial_state))/pow(MPl, 4))
def test_various_used_at(): with time_traveler() as T: T(2) energy = Energy(10, 3, used=1, used_at=1) assert energy == 9 T(5) assert energy == 10 T(2) energy = Energy(10, 3, used=1, used_at=datetime.utcfromtimestamp(1)) assert energy == 9 T(5) assert energy == 10
def test_equivalent_energy(): assert Energy(10, 10) == Energy(10, 10) assert Energy(5, 10) != Energy(10, 10) e1, e2, e3 = Energy(10, 10), Energy(10, 10), Energy(8, 10) with time_traveler() as T: T(123) e1.use() e2.use() assert e1 == e2 T(128) e1.use() assert e1 != e2 assert int(e1) == int(e3) assert e1 != e3
def save_and_retrieve_energy(): energy = Energy(10, 5) with time_traveler() as T: T(0) assert energy == 10 T(1) energy.use(5) T(2) assert energy == 5 saved = energy.used saved_used, saved_used_at = energy.used, energy.used_at loaded_energy = Energy(10, 5, used=saved_used, used_at=saved_used_at) assert energy == loaded_energy T(3) assert energy == 5
def test_future_tulerance(): energy = Energy(10, 5, future_tolerance=4) with time_traveler() as T: T(5) energy.use() # used at the past T(6) assert energy.passed() == 1 assert energy == 9 # used at the near future T(4) assert energy.passed() == 0 assert energy == 9 T(3) assert energy.passed() == 0 assert energy == 9 T(2) assert energy.passed() == 0 assert energy == 9 T(1) assert energy.passed() == 0 assert energy == 9 # used at the remote future T(0) with raises(ValueError): energy.passed()
def bonus_energy(): energy = Energy(10, 300) with time_traveler() as T: T(0) energy.set(15) T(1) assert energy == 15 T(2) energy.use() T(3) assert energy.recover_in() is None T(4) energy.use() T(5) assert energy.recover_in() is None T(6) energy.use(5) T(7) assert energy.recover_in() == 299 T(8) assert energy.recover_in() == 298 T(9) energy.set(15) T(10) assert energy.recover_in() is None
def test_extra_energy(): energy = Energy(10, 300) with time_traveler() as T: T(0) energy.set(15) T(1) assert energy == 15 assert energy.recover_in() is None assert energy.recover_fully_in() is None T(2) energy.use() assert energy.recover_in() is None assert energy.recover_fully_in() is None T(6) energy.use(6) T(7) assert energy.recover_in() == 299 assert energy.recover_fully_in() == 599 T(8) assert energy.recover_in() == 298 assert energy.recover_fully_in() == 598 T(9) energy.set(15) assert energy.recover_in() is None assert energy.recover_fully_in() is None T(10) assert energy.recover_in() is None assert energy.recover_fully_in() is None
def recover_energy(): energy = Energy(10, 5) with time_traveler() as T: T(0) energy.use(1) T(1) assert energy == 9 assert energy.recover_in() == 4 T(2) assert energy == 9 assert energy.recover_in() == 3 T(3) assert energy == 9 assert energy.recover_in() == 2 T(4) assert energy == 9 assert energy.recover_in() == 1 T(5) assert energy == 10 assert energy.recover_in() == None T(6) assert energy == 10 assert energy.recover_in() == None T(99) assert energy == 10 assert energy.recover_in() == None
class C3WayCharger(ACharger): def __init__(self, config): ACharger.__init__(self, config) from relay08 import get_three_way_cutter from energy import Energy self.charger = get_three_way_cutter() self.config = config self.energy = Energy() def charge(self, charger_unit): if charger_unit[0] == None: self.charger.set_usb_line_status(0) time.sleep(charger_unit[1]) elif charger_unit[0] == CDP: self.charger.enable_cdp_charging(charger_unit[1], charger_unit[2]) elif charger_unit[0] == DCP: self.charger.enable_dcp_charging(charger_unit[1], charger_unit[2]) else: self.charger.enable_sdp_charging(charger_unit[1], charger_unit[2]) def reconnect_usb(self): for i in range(3): info = self.energy.get_battery_info() if info and info["USB"]: break self.charger.enable_sdp_charging(2, 5) else: assert False
def use_energy_while_recovering(): energy = Energy(10, 5) with time_traveler() as T: T(0) energy.use(5) T(1) assert energy == 5 T(2) energy.use(1) T(3) assert energy == 4 T(4) assert energy == 4 T(5) assert energy == 5 T(6) assert energy == 5 T(7) energy.use(1) T(8) assert energy == 4 T(9) assert energy == 4 T(10) assert energy == 5
def __init__(self, h5n, result): self._h5n = h5n self._result = result self.element_force = ElementForce(self._h5n, self) self.energy = Energy(self._h5n, self) self.strain = Strain(self._h5n, self) self.stress = Stress(self._h5n, self)
def set_max_energy(): energy = Energy(10, 300) with time_traveler() as T: T(0) assert energy == 10 T(1) energy.max = 11 T(2) assert energy == 11 T(3) energy.use() T(4) assert energy == 10 T(5) energy.max = 12 T(6) assert energy == 10 T(7) energy.max = 9 T(8) assert energy == 9 T(9) energy.max = 1 T(10) assert energy == 1 T(11) energy.max = 10 T(12) assert energy == 10
def test_restored_extra_energy(): energy = Energy(10, 300, used=-5, used_at=0) assert energy.used_at is None with time_traveler() as T: T(0) assert energy == 15 energy.use() assert energy == 14 assert energy.used_at is None
def use_energy(): energy = Energy(10, 1000) assert energy == 10 energy.use() assert energy == 9 energy.use(5) assert energy == 4 with raises(ValueError): energy.use(5)
def repr_energy(): energy = Energy(10, 300) with time_traveler() as T: T(0) assert repr(energy) == '<Energy 10/10>' T(1) energy.use() T(2) assert repr(energy) == '<Energy 9/10 recover in 04:59>'
def use_energy_in_the_future(): energy = Energy(10, 5) with time_traveler() as T: T(5) energy.use() T(6) assert energy.passed() == 1 with raises(ValueError): T(0) energy.passed()
def use_energy_after_recovered(): energy = Energy(10, 5) with time_traveler() as T: T(0) energy.use(10) T(1) assert energy == 0 T(5) energy.use(1) T(6) assert energy == 0
def float_recovery_interval(): energy = Energy(10, 0.5) with time_traveler() as T: T(0) energy == 10 T(1) energy.use(3) T(2) energy == 9 T(3) energy == 10
def test_save_and_retrieve_energy(): energy = Energy(10, 5) with time_traveler() as T: T(0) assert energy == 10 T(1) energy.use(5) T(2) assert energy == 5 T(3) saved = energy.used saved_used, saved_used_at = energy.used, energy.used_at T(11) assert energy == 7 loaded_energy = Energy(10, 5, used=saved_used, used_at=saved_used_at) assert loaded_energy == 7 assert loaded_energy == energy loaded_energy2 = Energy(10, 5) loaded_energy2.used = saved_used loaded_energy2.used_at = saved_used_at assert loaded_energy2 == 7 assert loaded_energy2 == energy loaded_energy3 = object.__new__(Energy) loaded_energy3.__init__(10, 5, used=saved_used, used_at=saved_used_at) assert loaded_energy3 == 7 assert loaded_energy3 == energy loaded_energy4 = object.__new__(Energy) loaded_energy4.used = saved_used loaded_energy4.used_at = saved_used_at loaded_energy4.__init__(10, 5, used=saved_used, used_at=saved_used_at) assert loaded_energy4 == 7 assert loaded_energy4 == energy
def test_compare_energy(): energy = Energy(10, 300) with time_traveler() as T: T(0) assert energy == 10 assert energy > 9 assert 9 < energy assert energy < 11 assert 11 > energy assert 9 < energy < 11 assert energy <= 10 assert energy >= 10 assert 10 <= energy assert 10 >= energy assert 10 <= energy <= 10
class ALevelVoltage(object): def __init__(self, level, voltage): self.energy = Energy() self.level = level self.voltage = voltage def make_level_voltage(self): assert False, "needs be implemented in subclass" def verify_level_voltage_match(self): self.make_level_voltage() info = self.energy.get_battery_info() print info assert abs(self.level - info["level"]) <= 5 assert abs(self.voltage - info["voltage"]) <= 50
def write_curent_data(self, partial_state, step_num, h): self.files_with_data['energyData'].write(repr(partial_state.a)) self.files_with_data['energyData'].write(' ') self.files_with_data['energyData'].write( repr(np.average(Energy.phi_kinetic_energy(partial_state)) / pow(MPl, 4))) self.files_with_data['energyData'].write(' ') self.files_with_data['energyData'].write( repr(np.average(Energy.chi_kinetic_energy(partial_state)) / pow(MPl, 4))) self.files_with_data['energyData'].write(' ') self.files_with_data['energyData'].write( repr(np.average(Energy.phi_gradient_energy(partial_state)) / pow(MPl, 4))) self.files_with_data['energyData'].write(' ') self.files_with_data['energyData'].write( repr(np.average(Energy.chi_gradient_energy(partial_state)) / pow(MPl, 4))) self.files_with_data['energyData'].write(' ') if write_separate_potential_energy: self.files_with_data['energyData'].write( repr(np.average(Energy.inflaton_potential_energy(partial_state)) / pow(MPl, 4))) self.files_with_data['energyData'].write(' ') self.files_with_data['energyData'].write( repr(np.average(Energy.chi_potential_energy(partial_state)) / pow(MPl, 4))) self.files_with_data['energyData'].write('\n') else: self.files_with_data['energyData'].write( repr(np.average(Energy.potential_energy(partial_state)) / pow(MPl, 4))) self.files_with_data['energyData'].write('\n') # writing fields in program units: self.files_with_data['fieldData'].write(repr(partial_state.a)) self.files_with_data['fieldData'].write(' ') self.files_with_data['fieldData'].write(repr(partial_state.pa)) self.files_with_data['fieldData'].write(' ') self.files_with_data['fieldData'].write(repr(np.average(partial_state.phi))) self.files_with_data['fieldData'].write(' ') self.files_with_data['fieldData'].write(repr(np.average(partial_state.chi))) self.files_with_data['fieldData'].write(' ') self.files_with_data['fieldData'].write(repr(np.average(partial_state.phiPi))) self.files_with_data['fieldData'].write(' ') self.files_with_data['fieldData'].write(repr(np.average(partial_state.chiPi))) self.files_with_data['fieldData'].write('\n') self.files_with_data['chiMagnitudeData'].write(repr(partial_state.a)) self.files_with_data['chiMagnitudeData'].write(' ') self.files_with_data['chiMagnitudeData'].write(repr(np.sqrt(np.average(pw2(partial_state.chi))))) self.files_with_data['chiMagnitudeData'].write('\n') self.files_with_data['dtList'].write(repr(step_num)) self.files_with_data['dtList'].write(' ') self.files_with_data['dtList'].write(repr(h)) self.files_with_data['dtList'].write('\n')
def test_recovery_quantity(): with time_traveler() as T: T(0) energy = Energy(10, 3, 2) assert energy == 10 energy.use() energy.use() energy.use() assert energy == 7 T(1) assert energy == 7 T(2) assert energy == 7 T(3) assert energy == 9 T(6) assert energy == 10
def graph_cut(W, u_0, kernel, N): """ Perform the graph cut for the initial segmentation. The current implementation is not fully functional, but the results for RIGHTVENT_MRI are usable to develop the rest of the algorithm. :param W: The weights matrices computed previously :param u_0: The unary weights for the graphcut: based on prob_map :param kernel: The kernel used :param N: size of the image :return: The segmentation as a vector, the Energy """ eg = Energy(N, np.count_nonzero(kernel) * N) eg.set_neighbors(W) eg.set_unary(u_0) E = eg.minimize() print(E) y_0 = eg.get_labeling() return y_0, E, eg
def pickle_energy(): try: import cPickle as pickle except ImportError: import pickle energy = Energy(10, 5) with time_traveler() as T: T(0) assert energy == 10 T(1) energy.use(5) T(2) assert energy == 5 dump = pickle.dumps(energy) loaded_energy = pickle.loads(dump) assert energy == loaded_energy T(3) assert energy == 5
def test_use_energy(): energy = Energy(10, 1000) assert energy == 10 energy.use() assert energy == 9 energy.use(5) assert energy == 4 with raises(ValueError): energy.use(5) energy.use(10, timestamp() + 10000) assert energy.current(timestamp() + 10000) == 0 with raises(ValueError): energy.use(10, timestamp() + 10010) energy.use(10, timestamp() + 10010, force=True) assert energy.recover_in(timestamp() + 10010) == 11000 assert energy.current(timestamp() + 10010) == 0 assert energy.debt(timestamp() + 10010) == 10 energy.use(10, timestamp() + 10010, force=True) assert energy.recover_in(timestamp() + 10010) == 21000 assert energy.debt(timestamp() + 10010) == 20
def __init__(self, world, datadir, configdir): self.world = world self.datadir = datadir self.configdir = configdir self.enemies = [] self.stage = Stage(self) self.sprites = Group(self.stage) self.screen = world.screen # Visor de energia para el enemigo self._create_player() self.energy = Energy(10, 10, 100, 10) self.energy.set_model(self.player.id) self.stage.player = self.player self.stage.load_level(1) if VISIBLE_DEBUG: # Visor de rendimiento self.text = Text(world.font, world.fps, "FPS: %d")
def test_set_max_energy(): energy = Energy(10, 300) with time_traveler() as T: T( 0); assert energy == 10 T( 1); energy.max = 11 T( 2); assert energy == 11 T( 3); energy.use() T( 4); assert energy == 10 T( 5); energy.max = 12 T( 6); assert energy == 10 T( 7); energy.max = 9 T( 8); assert energy == 9 T( 9); energy.max = 1 T(10); assert energy == 1 T(11); energy.max = 10 T(12); assert energy == 10
def test_use_energy_at_the_future(): energy = Energy(10, 5) with time_traveler() as T: T(5) energy.use() T(6) assert energy.passed() == 1 with raises(ValueError): T(4) energy.passed() with raises(ValueError): T(3) energy.passed() with raises(ValueError): T(2) energy.passed() with raises(ValueError): T(1) energy.passed() with raises(ValueError): T(0) energy.passed()
def energy_update(self): ''' To be elaborated. ''' for HID in self.hh_dict: Energy.energy_step_go(self.hh_dict[HID].energy, self.hh_dict[HID], self.model_parameters_dict)
class Character( Actor ): """ """ #=============================================================================================== def __init__(self,name,imagefile,context,skills=[],factionid=0): """ """ model = [ (0,0), (0,181), (100,181), (100,0) ] bounding_rect = [ (0,0), (0,181), (100,181), (100,0) ] #super( Character, self ).__init__( model, imagefile, offset=(0,50) ) _model = Vertel() _model.set( [ ( 0.0, 0.0, 0.0 ), ( 0.0, 171.0/600.0, 0.0 ), ( 101.0/800.0, 171.0/600.0,0.0 ), ( 101.0/800.0 , 0.0, 0.0 ) ] ) _bound = Vertel() _bound.set( [ ( 0.0, 0.0, 0.0 ), ( 0.0, 100.0/600, 0.0 ), ( 100.0/800.0, 100.0/600, 0.0 ), ( 100.0/800, 0.0, 0.0 ) ] ) super( Character, self ).__init__( imagefile, _model, _bound ) #self.name = kwargs.get('name',"Unnamed") self.name = name self.mind = Mind( ego=self, factionid=factionid ) self._controller = None self._context = context self._target = None #body stats self.strength = 10 #strength of character, in kg*m*s^-2 self.agility = 20 #agility of character, in kg*m*s^-2 self.endurance = 10 #endurance: MAX Energy Reserves, in #endurance #endurance: MAX energy output in watts in kg*m^2*s^-3 self._reach = 1.0 #arm length self._mass = 50 #mass of character, in kg self.health = 100 # self.energy = Energy() self._alive = True #alive bit, used to drop a character object references #skills self.skillbook = SkillBook(skills=skills) self.deck = Deck(maxsize=4, slots=['default']*6 ) #equipment self._equipment = Equipment() #equipment is currently held by the character self.inventory = Inventory(40.0) #items in storage self.weapon = None #modifiers self.buff = Buffable(self) #allows the character to be buffed (stat and status effects) self.status_effects = [] self._wounds = [] #=============================================================================================== # Helper functions which link related members of a Character object, such as the skll book and # skill deck #=============================================================================================== def setslot(self,**kwargs): """ helper function, sets deck slot type """ self.deck.setslot(**kwargs) def setskill(self,**kwargs): """ helper function, sets deck slot with skill from skillbook """ self.deck.setskill(slot=kwargs['slot'],skill=self.skillbook[kwargs['skill']]) def queueskill(self,**kwargs): """ helper function, queues a skill as the next action from the deck """ print "Character queue skill" try: skill = self.deck[kwargs['slot']] if skill: self.mind.appendaction( Action( actor = self, atype = skill.type, target = self.mind._target, skill = skill, stage = self._context, energy = 3 ) ) else: print "No Skill set for deck slot:", kwargs['slot'] except KeyError: print "KeyError in Character:",self.name," queueskill" print " Either 'slot':'val' not present in arguments, or 'slot' not in deck" print " Keys in deck", self.deck.keys() print " kwargs:", kwargs #=============================================================================================== def reach(self): """ return the characters effective reach, taking into account - base reach - weapon reach """ return ( self._reach + self._equipment["rhand"]._reach ) #=============================================================================================== def __str__(self): """ """ return 'Character: %(name)s' %{'name':self.name} #=============================================================================================== def recharge(self,step=1): """ recharge is the turn update function, called recharge to avoid ambiguity with the animated actor's update function. Recharge is called at the beginning of a character's turn. """ self.energy.rechargehand() #draw a new hand of energy from the pool #todo decrement cooldown on abilities by 1 #=============================================================================================== def use(self, energy, attempt=False): """ remove the specified amount of energy from this characters' hand """ return self.energy.subhand(energy,attempt) #=============================================================================================== def hand(self): """return the current energy left in this characters' hand""" return self.energy._hand #=============================================================================================== def pool(self): """return the current energy left in this characters' pool""" return self._energy_pool #=============================================================================================== def iscapable(self, action): """ return True if this character is capable of performing the action, False otherwise whether a character is capable of performing a given action or not is dependent on the energy cost of the action, and any relevant status effects on the character """ if self.energy._hand >= action.getenergy(): return True #=============================================================================================== def update(self, step=1): """ """ #call super class update self.recharge(step) self.health -= len(self._wounds)*25 #mind.plan return self.health #=============================================================================================== def settarget(self, item ): """ """ self._target = item self.mind._target = item def gettarget(self): """ """ return self._target #=============================================================================================== def listen(self): """ TODO: Make character an event listener TODO: this should be an event handler currently just updates wound and energy """ #call super class update self.recharge(1) self.health -= len(self._wounds)*25 #mind.plan if not self.mind.targetalive(): self.mind._target = None return self.health