def set_up_test_simulation(self): """ This function hardcodes in certain values to the system to test it. """ self.num_bodies = 2 r1 = np.array([5., 0., 0.]) r2 = np.array([-5., 0., 0.]) v1 = np.array([0., 0.75, 0.]) v2 = np.array([0., -0.75, 0.]) body1 = body.Body("1", 10, 3, r1, v1) body2 = body.Body("2", 10, 3, r2, v2) self.bodies.append(body1) self.bodies.append(body2)
def __init__(self, x, y, width, length): if any(not isinstance(arg, int) for arg in [x, y, width, length]): raise TypeError(f'Expected int arguments') self.x_position = x self.y_position = y self.width = width self.length = length self._way = [(x, y)] self.collision = False self.hurdles_points = [] self._body = body.Body(self.x_position, self.y_position, width, length) self._prev_body = None self._head_bounder = None self.directions = ['right', 'top', 'left', 'bottom'] self.direct_indx = 0 self.move_dict = { KEY_UP: self.up, KEY_DOWN: self.down, KEY_LEFT: self.left, KEY_RIGHT: self.right, KEY_F1: self.rotate_counterclockwise, KEY_F2: self.rotate_clockwise }
def find_bodies(self, names, catalog=None): """Returns all the objects matching the names. Parameters: names: an iterable over strings Return: a (possibly empty) set of body.Body instances """ if len(names) == 0: return set() #first step: search for an exact name match ret = set() if catalog is None: catalogs_to_search = self.db.root.catalogs else: catalogs_to_search = [self.db.getNode("/catalogs", catalog)] where_conditions = " | ".join("(name=='%s')" % s for s in names) for t in catalogs_to_search: ret.update(body.Body(row) for row in t.where(where_conditions)) if len(ret) == len(names): return ret for name in names: ret.update(self.find_body(name)) return ret
def make_move(self, command): """ Метод используется для движения по карте с препятствиями command = KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP, KEY_F1, что соответствует повороту направо, налево, вниз, вверх и вращению """ # сохраним текущее положение и конфигурацию x_prev, y_prev = self.x_position, self.y_position len_prev, width_prev = self.length, self.width direct_indx_prev = self.direct_indx self.move_dict[command]() new_body = body.Body(self.x_position, self.y_position, self.width, self.length) if any(point in self.hurdles_points for point in new_body.get_body_coord()): self.x_position, self.y_position = x_prev, y_prev self.width, self.length = width_prev, len_prev self.direct_indx = direct_indx_prev self.collision = True else: self._prev_body = self._body self._body = new_body self.collision = False if not self.collision: self._way.append(self.get_coodrd())
def __init__(self, x, y, width, length): self.x_position = x self.y_position = y self.width = width self.length = length self._way = [(x, y)] self.collision = False self.hurdles_points = [] # тело робота self._body = body.Body(self.x_position, self.y_position, width, length) self._prev_body = None # граница тела робота по направлению движения (движение вверх - _body._top_bounder) self._head_bounder = None # направление робота self.directions = ['right', 'top', 'left', 'bottom'] # робот смотрит направо self.direct_indx = 0 # соответсвие комманд и методов self.move_dict = { KEY_UP: self.up, KEY_DOWN: self.down, KEY_LEFT: self.left, KEY_RIGHT: self.right, KEY_F1: self.rotate_counterclockwise, KEY_F2: self.rotate_clockwise }
def init(self): ## load some textures # bakground texture stars_t = self.res.load_tex("stars.jpg") # sun texture sun_t = self.res.load_tex("sun.png") ## set up the background self.background = sf.Sprite(stars_t) scale = self.scn.get_window_size().x / stars_t.size.x self.background.scale((scale, scale)) self.background.move((0, 0)) # make it a little fainter self.background.color = sf.Color(255, 255, 255, 150) ## parse the solar system data self.system_data = resource.parse_json("system.json") ## populate a dictionary of bodies for body_data in self.system_data["bodies"]: self.bodies[body_data["name"]] = body.Body() self.bodies[body_data["name"]].populate(body_data) self.sun = sf.Sprite(sun_t) self.sun.origin = (sun_t.size.x / 2., sun_t.size.y / 2.) self.sun.scale((0.001, 0.001)) ## initialize the views self.bgview = self.scn.default_view() self.bodyview = self.scn.default_view() # TODO setup so that initial view shows orbit of earth self.bodyview.move(-self.scn.size().x / 2., -self.scn.size().y / 2.) self.bodyview.zoom(0.005)
def _startElement(self, name, attrs): nodeName = attrs.get('name', None) if (name == 'transform'): t = transform.Transform() t.takeParser(self._parser, self, attrs) elif (name == 'geom'): g = geom.Geom(nodeName, self) g.takeParser(self._parser) elif (name == 'group'): # parse group pass elif (name == 'body'): b = body.Body(nodeName, self, attrs) b.takeParser(self._parser) elif (name == 'jointgroup'): # parse joint group pass elif (name == 'joint'): j = joint.Joint(nodeName, self) j.takeParser(self._parser) elif (name == 'ext'): # parse ext pass else: raise errors.ChildError('space', name)
def __init__(self, bounds, factions): #Create the environment self.field = Env.Environment(bounds[0], 0, bounds[1], 0) self.targets = [] self.agents = [] self.private_links = {} self.broadcast_channel = Comm.PublicLink() #Create factions for faction in factions: #With 6 bodies each faction_bodies = [] while len(faction_bodies) < 6: #Randomly generate a map coordinate, and create a body at that location x_coord = Rnd.randrange(self.field.x_lower, self.field.x_upper) y_coord = Rnd.randrange(self.field.y_lower, self.field.y_upper) body = Bod.Body(self.field, x_coord, y_coord) #If the location is valid, add it to the list; otherwise re-roll if self.field.registerAgent(body): faction_bodies.append(body) #Insert target controllers for i in range(1,len(faction_bodies)): self.targets.append(Con.TargetController(faction, faction_bodies[i], None)) #Insert agent controller agent_stats = {"faction":faction, "controller":self.createAgent(faction, faction_bodies[0], self.broadcast_channel.send), "collected_targets":0, "steps_taken":0, "happiness":[]} self.private_links[faction] = Comm.PrivateLink(agent_stats["controller"].perceiveMessage, faction) self.broadcast_channel.registerChannel(self.private_links[faction]) self.agents.append(agent_stats) return
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.physical = True self.combat_skill = 50 self.known_landmarks = set() self.body = body.Body(self) self.spells_known = set() self.traits.add(trait.person()) self.get_health_report = self.body.get_health_report self.money = 0
def generate(bodyamount, minmass, maxmass, minrad, maxrad, scale, centermass, centerrad): sys = System() sys.add_centre( body.Body(centermass, centerrad, scale, maxrad, r=1.0, g=1.0, b=0)) for _ in range(1, bodyamount): density = random.random() * (maxmass - minmass) + minmass newrad = random.random() * (maxrad - minrad) + minrad volume = 4 / 3 * math.pi * newrad**3 newmass = volume * density newdir = np.array( (random.random() * 2 - 1, random.random() * 2 - 1)) angle = 2 * random.random() * math.pi radius = random.random() x = radius * math.cos(angle) y = radius * math.sin(angle) newpos = np.array( (x * scale, y * scale, (random.random() * 2 - 1) * scale / 10), dtype=np.float64) r = random.random() g = random.random() b = random.random() sys.add_planet( body.Body(newmass, newrad, maxrad, newdir, newpos, r=r, g=g, b=b), newpos) return sys
def __init__(self): self.body = body.Body() self.panel = panel.Panel(self.body) self.status = status.Status(self.body) self.edgepoint = None self.twinklers = [] self.shots = [] self.paused = False self.target = None self.healmode = False self.clearselections() self.clickat = None
def get_hurdlers_points(self, area): """ Метод возвращает препятсвия, которые находятся вне зоны area """ res = [] for item in self.hurdles: for point in item.get_body_coord(): if not (area['x_left'] < point[0] < area['x_right'] and area['y_bottom'] < point[1] < area['y_top']): res.append(point) res += body.Body(0, 0, self.map_width, self.map_length).get_body_coord() self.hurdles_points = res return res
def __find_in_table(self, name, table): assert isinstance(table, tables.Table) #looking for an exact match ret = set(body.Body(row) for row in table.where("name=='%s'" % name)) #only returns a set if it has exactly one match if len(ret) == 1: return ret newname = name.replace(" ", "").lower() for row in table.iterrows(): if ((newname == row["name"].replace(" ", "").lower()) or (newname == row["additional_names"].replace(" ", "").lower())): #found exactly the name return set([body.Body(row)]) elif ((newname in row["name"].replace(" ", "").lower()) or (newname in row["additional_names"].replace(" ", "").lower()) or (newname in row["notes"].replace(" ", "").lower())): ret.add(body.Body(row)) return ret
def generate(bodyamount, minmass, maxmass, minrad, maxrad, scale, centermass, centerrad): sys = system.System() sys.add_centre( body.Body(centermass, 0.1 * maxrad * 20, scale, maxrad, r=0.5, g=0.3, b=0)) for _ in range(1, bodyamount): newmass = random.random() * (maxmass - minmass) + minmass newrad = random.random() * (maxrad - minrad) + minrad newdir = np.array( (random.random() * 2 - 1, random.random() * 2 - 1)) newpos = np.array(((random.random() * 2 - 1) * scale, (random.random() * 2 - 1) * scale, 0), dtype=np.float64) r = random.random() g = random.random() b = random.random() sys.add_planet( body.Body(newmass, newrad, scale, maxrad, newdir, newpos, r=r, g=g, b=b), newpos) return sys
def set_up_random_simulation(self): """ This function sets up a random system. """ self.num_bodies = random.randint(1, 11) for i in range(0, self.num_bodies): name = str(i) mass = float(random.randint(1, 11)) radius = float(random.randint(1, 11)) r = np.zeros(3) v = np.zeros(3) for j in range(0, 3): r[j] += float(random.randint(-5, 6)) v[j] += float(random.randint(-2, 3)) new_body = body.Body(name, mass, radius, r, v) self.bodies.append(new_body)
def filter_catalog(self, catalog, master_filter): """Apply a bank of filters to a catalog, returning only the remaining elements. Parameters: catalog: a string, the name of the catalog (see list_catalogs) master_filter: a callable that filters the elements in the catalog. candidates are in filters.py """ table = self.get_catalog(catalog) assert isinstance(table, tables.Table) assert callable(master_filter) return filter(master_filter, (body.Body(row) for row in table.iterrows()))
def __init__(self): self.name = 'default' self.time_step_size = 1. self.body = body.Body() self.pde = pde.PDE(self.body) self.environment = environment.Environment() self.state = state.State() self.state_dot = state.State() self.old_state = state.State() self.step = 0 self.time = 0. self.max_change = [1., 1., math.pi/8.]
def hurdle_fabric(max_x, max_y, max_size, num_hurdles): """ Функция генерирует препятсвия случайного размера и в случайном положении max_x - крайннее допустимое значение по оси х max_y - крайннее допустимое значение по оси y max_size - максимальный размер препятсивия num_hurdles - количество препятсвий """ hurdles = [] for i in range(num_hurdles): x_pos = randint(1, max_x - max_size * 2) y_pos = randint(1, max_y - max_size * 2) width = randint(2, max_size) length = randint(2, max_size) hurdles.append(body.Body(x_pos, y_pos, width, length)) return hurdles
def hurdle_fabric(max_x, max_y, max_size, num_hurdles): """ Функция генерирует препятсвия случайного размера и в случайном положении max_x - крайннее допустимое значение по оси х max_y - крайннее допустимое значение по оси y max_size - максимальный размер препятсивия num_hurdles - количество препятсвий """ if any(not isinstance(arg, int) for arg in [max_x, max_y, max_size, num_hurdles]): raise TypeError(f'Expected int arguments') hurdles = [] for i in range(num_hurdles): x_pos = randint(1, max_x - max_size * 2) y_pos = randint(1, max_y - max_size * 2) width = randint(2, max_size) length = randint(2, max_size) hurdles.append(body.Body(x_pos, y_pos, width, length)) return hurdles
def __init__(self): self._N = stdio.readInt() # Number of bodies self._radius = stdio.readFloat() # Radius of universe # the set scale for drawing on screen stddraw.setXscale(-self._radius, +self._radius) stddraw.setYscale(-self._radius, +self._radius) # read in the _N bodies self.orbs = [] # Array of bodies for i in range(self._N): rx = stdio.readFloat() ry = stdio.readFloat() vx = stdio.readFloat() vy = stdio.readFloat() mass = stdio.readFloat() position = [rx, ry] velocity = [vx, vy] r = vector.Vector(position) v = vector.Vector(velocity) self.orbs += [body.Body(r, v, mass)]
def _startElement(self, name, attrs): nodeName = attrs.get('name', None) if (name == 'transform'): t = transform.Transform() t.takeParser(self._parser, self, attrs) self._transformed = True elif (name == 'box'): self._parseGeomBox(attrs) elif (name == 'cappedCylinder'): self._parseGeomCCylinder(attrs) elif (name == 'cone'): raise NotImplementedError() elif (name == 'cylinder'): raise NotImplementedError() elif (name == 'plane'): self._parseGeomPlane(attrs) elif (name == 'ray'): self._parseGeomRay(attrs) elif (name == 'sphere'): self._parseGeomSphere(attrs) elif (name == 'trimesh'): self._parseTriMesh(attrs) elif (name == 'geom'): g = Geom(nodeName, self) g.takeParser(self._parser) elif (name == 'body'): b = body.Body(nodeName, self, attrs) b.takeParser(self._parser) elif (name == 'joint'): j = joint.Joint(nodename, self) j.takeParser(self._parser) elif (name == 'jointgroup'): pass elif (name == 'ext'): pass else: raise errors.ChildError('geom', name)
def read_data(bodies): """ This function reads data from the file "data.txt" line by line and initializes bodies. Each line contains information about one body. Lines, staring with '#' and empty lines are skipped. Format of the line: mass x y vx vy radius color(optional) """ # Creates file if it didn't exist. inp = open("data.txt", 'a') inp.close() inp = open("data.txt", 'r') for line in inp: if len(line.strip()) == 0 or line[0] == '#': continue data = line.split() if len(data) > 6: color = data[6] else: color = 0 data = [ float(data[0]), [float(data[1]), float(data[2])], [float(data[3]), float(data[4])], int(data[5]) ] if color: data.append(color) body.Body(bodies, *data) inp.close()
def set_up_given_simulation(self, given_filename): """ This function reads in a data file and creates the simulation based off of that. """ f = open(given_filename) for line_num, line in enumerate(f): if (line_num != 0): line_arr = line.split() name = line_arr[0] mass = float(line_arr[1]) radius = float(line_arr[2]) r = np.array([ float(line_arr[3]), float(line_arr[4]), float(line_arr[5]) ]) v = np.array([ float(line_arr[6]), float(line_arr[7]), float(line_arr[8]) ]) new_body = body.Body(name, mass, radius, r, v) self.bodies.append(new_body) self.num_bodies = len(self.bodies)
figure_name = "two_masses_ellipse.png" position_files_prefix = "positions_four_planets_com_" ####################################################### for dirName in [figure_folder, position_files_folder]: if not os.path.exists(dirName): os.mkdir(dirName) print("Directory ", dirName, " Created ") else: print("Directory ", dirName, " already exists") def distance_function(x1, y1, x2, y2): return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) # Initialize planets of type body planets = [bod.Body(planet_initial_conditions[i]) for i in range(len(planet_initial_conditions))] # Format list with initial positions and velocities U0 = [] for i in planets: U0.append(i.positions) for i in planets: U0.append(i.velocities) U0 = sum(U0, []) def timestep(t, U): # Set up array with first derivatives to return return_array = list(U[int(len(U)/2) : len(U)]) # Loop over planets for planet in planets:
def test_body_init_values(x, y, width, length): with pytest.raises(TypeError): body.Body(x, y, width, length)
def test_get_body_center(x, y, width, length): body_obj = body.Body(x, y, width, length) assert len(body_obj.get_body_coord()) == 2 * width + 2 * (length - 1)
def test_calculate_body_coord(x, y, width, length): body_obj = body.Body(x, y, width, length) assert len(body_obj._top_bounder) == width assert len(body_obj._left_bounder) == length - 1
def __iter__(self): for table in self.db.root.catalogs: for row in table.iterrows(): yield body.Body(row)
import csv import model import controller import body classes = [] name = raw_input("Ingrese el nombre del CSV: ") with open('./classes/' + name + '.csv') as File: reader = csv.reader(File) for row in reader: classes.append(row) classname = classes.pop(0) classes.pop(0) mod = model.Model(classname, classes) con = controller.Controller(classname, classes) body = body.Body(classname, classes) mod.getFormat() con.getFormat() body.getFormat()
def test_body_parametrs(x, y, width, length): body_obj = body.Body(x, y, width, length) assert body_obj.length == length assert body_obj.length == length assert body_obj.x_left_top == x assert body_obj.y_left_top == y