def neighbors(self): """Return neighbor agents within the communication range.""" cache = self.scheduler.zone_cache if not cache: die("update_zone() must have been called for zone caching.") p = self.mobility.current i, j = self.zone() neighbors = [] # check nine zones including/surrounding the current one for dj in [-1, 0, 1]: if j + dj < 0: continue for di in [-1, 0, 1]: if i + di < 0: continue if not cache.get(j + dj, None): continue if not cache[j + dj].get(i + di, None): continue for agent in self.scheduler.zone_cache[j + dj][i + di]: if agent == self: continue q = agent.mobility.current if abs(p[0] - q[0]) > self.range_: continue if abs(p[1] - q[1]) > self.range_: continue if math.sqrt((p[0] - q[0])**2 + (p[1] - q[1])**2) > self.range_: continue neighbors.append(agent) return neighbors
def animate(self, name, x, y): """Set the goal of cell object NAME to the geometry (X, Y).""" obj = self.object(name) if not obj: die("animate: object '{}' not found".format(name)) obj.goal_x, obj.goal_y = x, y obj.velocity = max(obj.dist_to_goal() / self.frame_rate, 1.)
def usage(): die("""\ usage: {} [-a] [-s] [-w word] -a Show all of the article -s Show the sections of the article with org format -w chose word """.format(sys.argv[0]))
def move(self, x, y): """Change the geometry of the object to (X, Y). If this object has children, their geometries are updated.""" if self.parent: die("move: cannot move attached object '{}'".format(self.name)) else: self.x, self.y = x, y for child in self.children: child.reposition()
def __init__(self, scheduler=None): if scheduler is None: die("Scheduler class must be specified.") self.scheduler = scheduler self.tx_total = 0 self.rx_total = 0 self.dup_total = 0 self.uniq_total = 0 self.delivered_total = 0 self.uniq_delivered_total = 0
def __init__(self, path=None, *kargs, **kwargs): super().__init__(*kargs, **kwargs) if not path: die("Underlying path class must be specified.") if not path.graph: die("Path class doesn't return a valid graph via path.graph.") self.path = path self.current_edge = None self.current_offset = None self.wait = True # choose a random point on a graph self.move_to_point(*self.random_point())
def vertices(self): """Return the list of geometries of all vertices of the polygon object.""" if self.type_ != 'polygon': die("vertices: object type muyst be 'polygon'") vertices = [] theta = cellx.deg2rad(self.rotation) - math.pi / 2 r = self.width / 2 for _ in range(self.n): vertices.append( [self.x + math.cos(theta) * r, self.y + math.sin(theta) * r]) theta += 2 * math.pi / self.n return vertices
def __init__(self, id_=None, scheduler=None, mobility=None, monitor=None, range_=50): if id_ is None: id_ = len(scheduler.agents) + 1 if not scheduler: die("Scheduler class must be specified.") if not mobility: die("Mobility class must be specified.") if not monitor: die("Monitor class must be specified.") if range_ > MAX_RANGE: die(f"range cannot exceed MAX_RANGE ({MAX_RANGE})") self.id_ = id_ self.scheduler = scheduler self.mobility = mobility self.monitor = monitor self.range_ = range_ self.last_neighbors = [] self.received = defaultdict(int) self.receive_queue = defaultdict(int) self.delivered = defaultdict(int) self.tx_count = 0 self.rx_count = 0 self.dup_count = 0 self.scheduler.add_agent(self)
def load_rcfile(): """Load and execute the custom RC script in the home directory (~/.x11util) if it exists. The RC script is any (valid) Python script, which is loaded after defining all global vaiables. So, you can freely overrwite those definitions.""" rc_file = '{}/.x11utilrc'.format(os.getenv('HOME')) try: with open(rc_file) as f: code = f.read() except FileNotFoundError: return None try: exec(code) except: die("executing '%s' failed. aborting...".format(rc_file))
def rgb_in_scheme(scheme, p=1): """Return the RGBA color (R, G, B, A) in color scheme SCHEME with brightness P.""" if scheme == 0: # HSV return hsv2rgb(240 * (1 - p), .9, 1.) elif scheme == 1: # cyan-red return hsv2rgb(0 + 180 * (1 - p), abs(p - .5) * 2, 1.) elif scheme == 2: # blue-orange return hsv2rgb(30 + 180 * (1 - p), abs(p - .5) * 2, 1.) elif scheme == 3: # blue-yellow return hsv2rgb(60 + 180 * (1 - p), abs(p - .5) * 2, 1.) elif scheme == 4: # purple-green return hsv2rgb(90 + 180 * (1 - p), abs(p - .5) * 2, 1.) elif scheme == 5: # green-magenta return hsv2rgb(120 + 180 * p, abs(p - .5) * 2, 1.) elif scheme == 6: # green-red return hsv2rgb(150 + 180 * p, abs(p - .5) * 2, 1.) else: die("rbg_in_scheme: invalid color scheme '{}'".format(scheme))
def _parse_palette(self, args): """Parse arguments ARGS for palette command. ARGS can be: NAME RED GREEN BLUE NAME RED GREEN BLUE ALPHA NAME SRC_NAME NAME SRC_NAME ALPHA""" palette = self.cell.monitor.palette if len(args) == 2: name, src_name = args palette.define_color(name, *palette.rgba(src_name)) elif len(args) == 3: name, src_name, alpha = self.expand_palette(args) palette.define_color(name, *palette.rgb(src_name), a=alpha) elif len(args) == 4: name, r, g, b = self.expand_palette(args) palette.define_color(name, r, g, b) elif len(args) == 5: name, r, g, b, a = self.expand_palette(args) palette.define_color(name, r, g, b, a) else: die("invalid palette arguments: {}".format(args))
def abort(self, msg, *args): """Display error message MSG with the line number and the content, and abort the program execution.""" die("{}: {}\n{}\n".format(self.lineno, self.line, msg, *args))
def delete(self, name): """Unregister cell object having name NAME.""" try: del self.objects[name] except KeyError: die("delete: cannot delete non-existing object '{}'".format(name))
def parse_line(self, line): self.line = line if line == '': return line = re.sub(r'^define +(\S+) +bitmap (\S+)', r'define \1 bitmap "\2"', line) line = re.sub(r'^define +(\S+) +text (\S+)', r'define \1 text "\2"', line) ast = self.parser.parse(line + '\n') print(ast) cmd = ast.head if cmd == 'color_cmd': pattern, color = [str(x) for x in ast.select('*:is-leaf')] self.validate_color(color) for n in self.expand_name(pattern): self.cell.object(n).color = color elif cmd == 'define_cmd': tree = ast.tail[0] atype = tree.head # insert dash before option char for x in tree.select('option > name'): print(type(x.tail[0])) x.tail[0] = plyplus.common.TokValue('-' + x.tail[0]) name, *args = [str(x) for x in tree.select('*:is-leaf')] print('>', name, args) if atype == 'bitmap_cmd': opts = self.parse_options('bi', args) args[0] = args[0].replace('\"', '') self.define_bitmap(name, args, opts) elif atype == 'box_cmd': opts = self.parse_options('f:', args) self.define_box(name, args, opts) elif atype == 'ellipse_cmd': opts = self.parse_options('f:', args) self.define_ellipse(name, args, opts) elif atype == 'line_cmd': opts = self.parse_options('ht', args) self.define_line(name, args, opts) elif atype == 'link_cmd': self.define_link(name, args) elif atype == 'text_cmd': opts = self.parse_options('lcr', args) self.define_text(name, args, opts) else: die("unknown define command '{}'".format(atype)) elif cmd == 'display_cmd': self.cell.display() elif cmd == 'palette_cmd': args = [str(x) for x in ast.select('*:is-leaf')] self._parse_palette(args) elif cmd == 'resize_cmd': args = [str(x) for x in ast.select('*:is-leaf')] name = args.pop(0) w, h = self.expand_position(*args) for n in self.expand_name(name): self.cell.object(n).resize(w, h) elif cmd == 'wait_cmd': self.cell.wait() else: die("unknown command '{}'".format(cmd))