def loadRooms(self): import copy rooms = self.db.rooms.find() for i in range(0, rooms.count()): # default is zero newRoom = Room(self, rooms[i]) print newRoom print rooms[i] newRoom.id = rooms[i]['id'] if 'items' in rooms[i]: for item in rooms[i]['items']:# newRoom.items.append(copy.deepcopy(self.items[item])) if 'npcs' in rooms[i]: for mobile in rooms[i]['npcs']: m = Mobile(self.mobile_list[mobile]['name'], self, self.mobile_list[mobile]) m.room = newRoom self.mobiles.append(m) self.rooms.append(newRoom) # have to load all the rooms BEFORE loading the exits for i in range(0, rooms.count()): exits = rooms[i]['exits'] for e in exits: exit = exits[e] target_room = next(room for room in self.rooms if room.id == exit['target']) direction = exit['direction'] self.rooms[i].exits.append(Exit(direction.lower(), target_room))
def __init__(self, config): self.config = config gps = GPS(config) measure = Measure() self.mobile = Mobile(gps, measure, config) self.step = config['step']
def step(self,step): for mobile in self.mobiles: mobile.applyStep(step) grav = self.gravity.copy() grav.mulScalar(mobile.getMass()) #grav.rotate(mobile.getAngle()) mobile.applyForce(step,grav) for mobile2 in self.mobiles: if mobile != mobile2: if mobile.isBound(mobile2.getPosition(),mobile2.getRadius()) == 1: n = Vector2d.normal(mobile2.getPosition(),mobile.getPosition()) vn = Vector2d.dotProduct(mobile.getVelocity(),n) if vn < 0: #mobile.getVelocity().display() #n.display() Mobile.solveCollide(mobile,mobile2) mobile.applyStep(step) mobile2.applyStep(step) for plane in self.planes: #d = plane.distancePoint(mobile.getPosition()) #vn = Vector2d.dotProduct(mobile.getVelocity(),plane.getNormal()) #if d < 0 and vn < 0: # plane.reflective(mobile) for submobile in mobile.getMobiles(): d = plane.distancePoint(submobile.getPhysicalPosition()) vn = Vector2d.dotProduct(submobile.getVelocity(),plane.getNormal()) if d < submobile.getRadius() and vn < 0: #ADDED CONDITION OVER PHYSICAL POINTS if submobile.getUpdatedPhysicalPoints().count > 0: ppcollide = 0 for point in submobile.getUpdatedPhysicalPoints(): if plane.distancePoint(point) < 0: self.groundcollider.collideEvent(point) n = plane.getNormal().copy() n.normalize() n.mulScalar(-plane.distancePoint(point)) #n.display() mobile.getPosition().add(n) mobile.updateMobiles() ppcollide = 1 if ppcollide == 1: plane.reflective(submobile) for submobile2 in mobile.getMobiles(): v = submobile2.getVelocity() v.set(0.0,v.getY()) mobile.angularVelocity = mobile.angularVelocity * 0.8
def registerPlayer(self, client, playerData): playerId = playerData['_id'] # See if playerId is in game. candidatePlayer = self.getPlayerById(playerId) if candidatePlayer: # If candidate is linkdead, reconnect if candidatePlayer.isLinkdead(): print '{name} has reconnected.'.format(name=candidatePlayer.name) candidatePlayer.client = client candidatePlayer.sendToClient('Reconnecting.') candidatePlayer.linkdead = 0 for mobile in [mobile for mobile in self.mobiles if mobile is not candidatePlayer]: mobile.sendToClient('@g{name} has reconnected.@x'.format(name=candidatePlayer.getName(mobile))) # And return candidatePlayer to attach to the browser return candidatePlayer else: return False else: # Make a new mobile name = playerData['name'].capitalize() stats = playerData['stats'] if 'stats' in playerData else {} newMobile = Mobile(name, self, {'stats': stats}) newMobile.client = client newMobile.is_player = True self.mobiles.append(newMobile) newMobile.id = playerId if 'room' in playerData: newMobile.room = self.rooms[playerData['room']] else: newMobile.room = self.rooms[0] if 'stats' in playerData: for stat in playerData['stats']: newMobile.stats[stat] = playerData['stats'][stat] newMobile.sendToClient('@uWelcome to Redemption, {name}@x.'.format(name=newMobile.name)) for mobile in [mobile for mobile in self.mobiles if mobile is not newMobile]: mobile.sendToClient('@g{name} has connected.@x'.format(name=newMobile.getName(mobile))) return newMobile
def loadRooms(self): rooms = self.db.rooms.find() for i in range(0, rooms.count()): # default is zero exists = [r for r in self.rooms if r.id == rooms[i]['id']] if len(exists) > 0: newRoom = exists[0] newRoom.bg = rooms[i]['bg'] if 'bg' in rooms[i] else newRoom.bg newRoom.desc = rooms[i]['description'] if 'description' in rooms[i] else newRoom.desc else: newRoom = Room(self, rooms[i]) newRoom.id = rooms[i]['id'] if newRoom.bg: print "Has a background!", newRoom.bg newRoom.items = [] newRoom.exits = [] if 'items' in rooms[i]: for item in rooms[i]['items']:# newRoom.items.append(Item(self.items[item])) if 'npcs' in rooms[i]: # only respawn if there is NO combat going on in the room to avoid insane duplications! FIX ME currentMobiles = [mobile for mobile in self.mobiles if mobile.room == newRoom and mobile.combat and not mobile.is_player] if not len(currentMobiles) > 0: for mobile in rooms[i]['npcs']: m = Mobile(self.mobile_list[mobile]['name'], self, self.mobile_list[mobile]) m.room = newRoom self.mobiles.append(m) if len(exists) <= 0: self.rooms.append(newRoom) # have to load all the rooms BEFORE loading the exits for i in range(0, rooms.count()): exits = rooms[i]['exits'] for e in exits: exit = exits[e] target_room = next(room for room in self.rooms if room.id == exit['target']) direction = exit['direction'] self.rooms[i].exits.append(Exit(direction.lower(), target_room))
def __init__(self): # System parameters self.nb_MB = 3 self.state_size = 2 * self.nb_MB self.nb_actions = (Mobile.MAX_DATA + 1) ** self.nb_MB * (Mobile.MAX_ENERGY + 1) ** self.nb_MB self.action_space = ActionSpace((Discrete(Mobile.MAX_DATA + 1), Discrete(Mobile.MAX_ENERGY + 1), Discrete(Mobile.MAX_DATA + 1), Discrete(Mobile.MAX_ENERGY + 1), Discrete(Mobile.MAX_DATA + 1), Discrete(Mobile.MAX_ENERGY + 1) )) self.observation_space = StateSpace((Discrete(Mobile.MAX_CPU), Discrete(Mobile.MAX_ENERGY), Discrete(Mobile.MAX_CPU), Discrete(Mobile.MAX_ENERGY), Discrete(Mobile.MAX_CPU), Discrete(Mobile.MAX_ENERGY))) # initialize Second Transmitters self.MB1 = Mobile() self.MB2 = Mobile() self.MB3 = Mobile() self.max_data = self.nb_MB * Mobile.MAX_DATA self.max_energy = self.nb_MB * Mobile.MAX_ENERGY self.max_latency = Mobile.MAX_LATENCY self.training_time = 0 self.training_data = 0 self.viewer = None self.state = None self.steps_beyond_done = None
def modify(): mod_no = input("Enter the model number:") mobile = get("MX" + mod_no) if mobile: data = {} data['name'] = input("Enter the model name :") data['price'] = int(input("Enter the price:")) data['year'] = input("Enter the Year:") data['sold'] = int(input("Enter the number of items sold:")) data['rating'] = float(input("Enter the rating:")) mob = Mobile(number=mod_no, **data) prev = [] with open(FILE_NAME, "rb") as fp: prev = pickle.load(fp) for i in range(len(prev)): if prev[i].getNumber() == mob.getNumber(): prev[i] = mob with open(FILE_NAME, "wb") as fp: pickle.dump(prev, fp) print("Successfully modified details of " + mob.getNumber()) else: print("No mobile exists with the model number " + mod_no)
def addMobile(): data = {} data['name'] = input("Enter the model name :") data['number'] = input("Enter the model number :") data['price'] = int(input("Enter the price:")) data['year'] = input("Enter the Year") data['sold'] = int(input("Enter the number of items sold:")) data['rating'] = float(input("Enter the rating")) mob = None try: mob = Mobile(**data) except (NameException, NumberException, NegativeException, YearException) as e: print(e.msg) else: try: mob.save() except MobileExists: print("Already an mobile exists with the model number " + mob.getNumber()) else: print("Mobile successfully created")
def registerPlayer(self, client, playerData): playerId = playerData['_id'] # See if playerId is in game. candidatePlayer = self.getPlayerById(playerId) if candidatePlayer: # If candidate is linkdead, reconnect if candidatePlayer.isLinkdead(): print 'Reconnecting to player {name}'.format(name=candidatePlayer.name) candidatePlayer.client = client candidatePlayer.sendToClient('Reconnecting.') candidatePlayer.processCommand('look') candidatePlayer.linkdead = 0 # And return candidatePlayer to attach to the browser return candidatePlayer else: return False else: # Make a new mobile name = playerData['name'] newMobile = Mobile(name, self, {'charClass': 'warrior'}) newMobile.client = client self.mobiles.append(newMobile) newMobile.id = playerId if 'room' in playerData: newMobile.room = self.rooms[playerData['room']] else: newMobile.room = self.rooms[0] if 'stats' in playerData: for stat in playerData['stats']: newMobile.stats[stat] = playerData['stats'][stat] newMobile.sendToClient('@uWelcome to Redemption, {name}@x.'.format(name=newMobile.name)) return newMobile
# Continue receiving for 10 seconds rx.startListening() startTime = received = 0 while time.monotonic() - startTime < endTime or startTime == 0: hasPayload, pipeNo = rx.available_pipe() if hasPayload: print("Receiving packages...") if startTime == 0: startTime = time.monotonic() received += 1 buffer = rx.read(rx.payloadSize) mobile.payload[1] = struct.unpack("<f", buffer[:4])[0] endTime = time.monotonic() finalTime = endTime - startTime avg = (received * rx.payloadSize * 8) / finalTime print("Transmission time: {}\n" "Packages Received: {}\n" "Average bits per second (BPS): {}\n".format(finalTime, received, avg)) rx.stopListening() if __name__ == '__main__': mobile = Mobile([RF24(17, 0), RF24(27, 10)]) rx = mobile.radios[1] measure(mobile, rx) mobile.shutDown() sys.exit()
# importing entire module named person import person p1 = person.Person('person1', 45) print(p1) import car c1 = car.Car('i20') print(c1) c2 = car.MyCar() print(c2) # from mobile module only Mobile class will get imported # from mobile import Mobile # from mobile import MyMobile from mobile import Mobile, MyMobile m1 = Mobile('Galaxy S10 plus') print(m1) m2 = MyMobile() print(m2)
def setupShip(self,filename): domLevel = parse(filename) shipNodes = domLevel.getElementsByTagName("ship") shipNode = shipNodes[0] self.mainbody = Body() for node in shipNode.childNodes: if node.localName == "position": position = node.getAttribute('value') values = position.split(',') self.mainbody.setPosition(float(values[0]),float(values[1])) if node.localName == "mobile": m = Mobile() for childnode in node.childNodes: if childnode.localName == "position": values = childnode.getAttribute('value').split(',') m.setPosition(float(values[0]),float(values[1])) if childnode.localName == "velocity": values = childnode.getAttribute('value').split(',') m.setVelocity(float(values[0]),float(values[1])) if childnode.localName == "thrust": values = childnode.getAttribute('value').split(',') m.setThrustVector(float(values[0]),float(values[1])) m.setInitialThrustVector(float(values[0]),float(values[1])) if childnode.localName == "mass": value = childnode.getAttribute('value') m.setMass(float(value)) if childnode.localName == "radius": value = childnode.getAttribute('value') m.setRadius(float(value)) if childnode.localName == "texture": value = childnode.getAttribute('value') m.setTexture(TextureHelper.loadTextureFromFile(value)) #if childnode.localName == "physicalPoints": # for ppointnode in childnode.childNodes: # if ppointnode.localName == "point": # values = ppointnode.getAttribute('value').split(',') # m.addPhysicalPoint(Vector2d(float(values[0]),float(values[1]))) m.setupPhysicalPoint() self.mainbody.addMobile(m) self.mainbody.init() focus_position = self.mainbody.getPosition() self.world.addMobile(self.mainbody)
class Climber: def __init__(self, config): self.config = config gps = GPS(config) measure = Measure() self.mobile = Mobile(gps, measure, config) self.step = config['step'] def toward_summit(self): while self.mobile.goal is False: direction = self.mobile.guide() new_alpha, new_beta, new_maxlike, new_score = self._walk(direction) self.mobile.assess_results(new_alpha, new_beta, new_maxlike, new_score) def _walk(self, direction): if direction == 'alpha': new_alpha, new_beta, new_maxlike, new_score = self._set_alpha() return new_alpha, new_beta, new_maxlike, new_score elif direction == 'beta': new_alpha, new_beta, new_maxlike, new_score = self._set_beta() return new_alpha, new_beta, new_maxlike, new_score def _set_alpha(self): alpha_up = self.mobile.gps.alpha + self.step alpha_down = self.mobile.gps.alpha - self.step new_beta = None maxlike_up, score_up = self.__run_machine(alpha_up, self.mobile.gps.beta) maxlike_down, score_down = self.__run_machine(alpha_down, self.mobile.gps.beta) if score_up > score_down: new_alpha = alpha_up new_maxlike = maxlike_up new_score = score_up else: new_alpha = alpha_up new_maxlike = maxlike_down new_score = score_down return new_alpha, new_beta, new_maxlike, new_score def _set_beta(self): beta_up = self.mobile.gps.beta + self.step beta_down = self.mobile.gps.beta - self.step new_alpha = None maxlike_up, score_up = self.__run_machine(self.mobile.gps.alpha, beta_up) maxlike_down, score_down = self.__run_machine(self.mobile.gps.alpha, beta_down) if maxlike_up > maxlike_down: new_beta = beta_up new_maxlike = maxlike_up new_score = score_up else: new_beta = beta_down new_maxlike = maxlike_down new_score = score_down return new_alpha, new_beta, new_maxlike, new_score def __run_machine(self, alpha, beta): if str((alpha, beta)) not in self.mobile.memory.keys(): machine = Machine(self.config) machine.run(alpha, beta) score = machine.score maxlike = machine.maxlike self.mobile.memory[str((alpha, beta))] = (maxlike, score) return maxlike, score else: print('machine already been here') maxlike = self.mobile.memory[str((alpha, beta))][0] score = self.mobile.memory[str((alpha, beta))][1] return maxlike, score
import sys from mobile import Mobile from RF24 import RF24 # rx = RF24(27, 10) # TODO # tx = RF24(17, 0) if __name__ == "__main__": # radio = RF24(17, 0) mobile = Mobile([RF24(17, 0), RF24(27, 10)], "R") try: mobile.operate() except KeyboardInterrupt: print(" Keyboard Interrupt detected. Exiting...") mobile.shutDown() sys.exit()
class FederatedLearningEnv(gym.Env): TIME_LIMIT = 10000 DATA_LIMIT = 1500 def __init__(self): # System parameters self.nb_MB = 3 self.state_size = 2 * self.nb_MB self.nb_actions = (Mobile.MAX_DATA + 1) ** self.nb_MB * (Mobile.MAX_ENERGY + 1) ** self.nb_MB self.action_space = ActionSpace((Discrete(Mobile.MAX_DATA + 1), Discrete(Mobile.MAX_ENERGY + 1), Discrete(Mobile.MAX_DATA + 1), Discrete(Mobile.MAX_ENERGY + 1), Discrete(Mobile.MAX_DATA + 1), Discrete(Mobile.MAX_ENERGY + 1) )) self.observation_space = StateSpace((Discrete(Mobile.MAX_CPU), Discrete(Mobile.MAX_ENERGY), Discrete(Mobile.MAX_CPU), Discrete(Mobile.MAX_ENERGY), Discrete(Mobile.MAX_CPU), Discrete(Mobile.MAX_ENERGY))) # initialize Second Transmitters self.MB1 = Mobile() self.MB2 = Mobile() self.MB3 = Mobile() self.max_data = self.nb_MB * Mobile.MAX_DATA self.max_energy = self.nb_MB * Mobile.MAX_ENERGY self.max_latency = Mobile.MAX_LATENCY self.training_time = 0 self.training_data = 0 self.viewer = None self.state = None self.steps_beyond_done = None def seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] def step(self, action): assert self.action_space.contains(action), "%r (%s) invalid"%(action, type(action)) data_required1 = action[0] energy_required1 = action[1] data_required2 = action[2] energy_required2 = action[3] data_required3 = action[4] energy_required3 = action[5] data1, latency1, energy_consumption1, fault1 = self.MB1.update(data_required1, energy_required1) data2, latency2, energy_consumption2, fault2 = self.MB2.update(data_required2, energy_required2) data3, latency3, energy_consumption3, fault3 = self.MB3.update(data_required3, energy_required3) data = data1 + data2 + data3 latency = max(latency1, latency2, latency3) energy_consumption = energy_consumption1 + energy_consumption2 + energy_consumption3 fault = fault1 + fault2 + fault3 state = [self.MB1.CPU_shared, self.MB1.energy, self.MB2.CPU_shared, self.MB2.energy, self.MB3.CPU_shared, self.MB3.energy] # print (state) self.state = tuple(state) self.training_data += data self.training_time += latency reward = 10 * (5 * data/self.max_data - latency/self.max_latency - energy_consumption/self.max_energy) + fault if (self.training_data > FederatedLearningEnv.DATA_LIMIT): done = True else: done = False # if (fault < 0): # print (fault) # print(np.array(self.state), action, [reward, data, latency, energy_consumption, fault], done) reward /= 10 return np.array(self.state), [reward, data, latency, energy_consumption, data1, data2, data3], done, {} def reset(self): self.state = [] self.MB1.reset() self.MB2.reset() self.MB3.reset() state = [self.MB1.CPU_shared, self.MB1.energy, self.MB2.CPU_shared, self.MB2.energy, self.MB3.CPU_shared, self.MB3.energy] self.state = tuple(state) self.training_time = 0 self.training_data = 0 print(self.state) self.steps_beyond_done = None return np.array(self.state) def updateObservation(self): return def render(self, mode='human', close=False): return def close(self): """Override in your subclass to perform any necessary cleanup. Environments will automatically close() themselves when garbage collected or when the program exits. """ raise NotImplementedError() def seed(self, seed=None): """Sets the seed for this env's random number generator(s). # Returns Returns the list of seeds used in this env's random number generators """ raise NotImplementedError() def configure(self, *args, **kwargs): """Provides runtime configuration to the environment. This configuration should consist of data that tells your environment how to run (such as an address of a remote server, or path to your ImageNet data). It should not affect the semantics of the environment. """ raise NotImplementedError() # env = FederatedLearningEnv() # env.reset() # for index in range(0, 100): # env.step(env.action_space.sample())