CombinedText
stringlengths
4
3.42M
#!/usr/bin/env python3 # vim: set syntax=python ts=4 : # # Copyright (c) 2018 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import contextlib import string import mmap import sys import re import subprocess import select import shutil import shlex import signal import threading import concurrent.futures from collections import OrderedDict import queue import time import csv import glob import concurrent import xml.etree.ElementTree as ET import logging import pty from pathlib import Path from distutils.spawn import find_executable from colorama import Fore import pickle import platform import yaml import json from multiprocessing import Lock, Process, Value try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import SafeLoader, Dumper try: import serial except ImportError: print("Install pyserial python module with pip to use --device-testing option.") try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") try: import psutil except ImportError: print("Install psutil python module with pip to run in Qemu.") ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") # This is needed to load edt.pickle files. sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts", "python-devicetree", "src")) from devicetree import edtlib # pylint: disable=unused-import # Use this for internal comparisons; that's what canonicalization is # for. Don't use it when invoking other components of the build system # to avoid confusing and hard to trace inconsistencies in error messages # and logs, generated Makefiles, etc. compared to when users invoke these # components directly. # Note "normalization" is different from canonicalization, see os.path. canonical_zephyr_base = os.path.realpath(ZEPHYR_BASE) sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import scl import expr_parser logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ExecutionCounter(object): def __init__(self, total=0): self._done = Value('i', 0) self._passed = Value('i', 0) self._skipped_configs = Value('i', 0) self._skipped_runtime = Value('i', 0) self._skipped_cases = Value('i', 0) self._error = Value('i', 0) self._failed = Value('i', 0) self._total = Value('i', total) self._cases = Value('i', 0) self.lock = Lock() @property def cases(self): with self._cases.get_lock(): return self._cases.value @cases.setter def cases(self, value): with self._cases.get_lock(): self._cases.value = value @property def skipped_cases(self): with self._skipped_cases.get_lock(): return self._skipped_cases.value @skipped_cases.setter def skipped_cases(self, value): with self._skipped_cases.get_lock(): self._skipped_cases.value = value @property def error(self): with self._error.get_lock(): return self._error.value @error.setter def error(self, value): with self._error.get_lock(): self._error.value = value @property def done(self): with self._done.get_lock(): return self._done.value @done.setter def done(self, value): with self._done.get_lock(): self._done.value = value @property def passed(self): with self._passed.get_lock(): return self._passed.value @passed.setter def passed(self, value): with self._passed.get_lock(): self._passed.value = value @property def skipped_configs(self): with self._skipped_configs.get_lock(): return self._skipped_configs.value @skipped_configs.setter def skipped_configs(self, value): with self._skipped_configs.get_lock(): self._skipped_configs.value = value @property def skipped_runtime(self): with self._skipped_runtime.get_lock(): return self._skipped_runtime.value @skipped_runtime.setter def skipped_runtime(self, value): with self._skipped_runtime.get_lock(): self._skipped_runtime.value = value @property def failed(self): with self._failed.get_lock(): return self._failed.value @failed.setter def failed(self, value): with self._failed.get_lock(): self._failed.value = value @property def total(self): with self._total.get_lock(): return self._total.value class CMakeCacheEntry: '''Represents a CMake cache entry. This class understands the type system in a CMakeCache.txt, and converts the following cache types to Python types: Cache Type Python type ---------- ------------------------------------------- FILEPATH str PATH str STRING str OR list of str (if ';' is in the value) BOOL bool INTERNAL str OR list of str (if ';' is in the value) ---------- ------------------------------------------- ''' # Regular expression for a cache entry. # # CMake variable names can include escape characters, allowing a # wider set of names than is easy to match with a regular # expression. To be permissive here, use a non-greedy match up to # the first colon (':'). This breaks if the variable name has a # colon inside, but it's good enough. CACHE_ENTRY = re.compile( r'''(?P<name>.*?) # name :(?P<type>FILEPATH|PATH|STRING|BOOL|INTERNAL) # type =(?P<value>.*) # value ''', re.X) @classmethod def _to_bool(cls, val): # Convert a CMake BOOL string into a Python bool. # # "True if the constant is 1, ON, YES, TRUE, Y, or a # non-zero number. False if the constant is 0, OFF, NO, # FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in # the suffix -NOTFOUND. Named boolean constants are # case-insensitive. If the argument is not one of these # constants, it is treated as a variable." # # https://cmake.org/cmake/help/v3.0/command/if.html val = val.upper() if val in ('ON', 'YES', 'TRUE', 'Y'): return 1 elif val in ('OFF', 'NO', 'FALSE', 'N', 'IGNORE', 'NOTFOUND', ''): return 0 elif val.endswith('-NOTFOUND'): return 0 else: try: v = int(val) return v != 0 except ValueError as exc: raise ValueError('invalid bool {}'.format(val)) from exc @classmethod def from_line(cls, line, line_no): # Comments can only occur at the beginning of a line. # (The value of an entry could contain a comment character). if line.startswith('//') or line.startswith('#'): return None # Whitespace-only lines do not contain cache entries. if not line.strip(): return None m = cls.CACHE_ENTRY.match(line) if not m: return None name, type_, value = (m.group(g) for g in ('name', 'type', 'value')) if type_ == 'BOOL': try: value = cls._to_bool(value) except ValueError as exc: args = exc.args + ('on line {}: {}'.format(line_no, line),) raise ValueError(args) from exc elif type_ in ['STRING', 'INTERNAL']: # If the value is a CMake list (i.e. is a string which # contains a ';'), convert to a Python list. if ';' in value: value = value.split(';') return CMakeCacheEntry(name, value) def __init__(self, name, value): self.name = name self.value = value def __str__(self): fmt = 'CMakeCacheEntry(name={}, value={})' return fmt.format(self.name, self.value) class CMakeCache: '''Parses and represents a CMake cache file.''' @staticmethod def from_file(cache_file): return CMakeCache(cache_file) def __init__(self, cache_file): self.cache_file = cache_file self.load(cache_file) def load(self, cache_file): entries = [] with open(cache_file, 'r') as cache: for line_no, line in enumerate(cache): entry = CMakeCacheEntry.from_line(line, line_no) if entry: entries.append(entry) self._entries = OrderedDict((e.name, e) for e in entries) def get(self, name, default=None): entry = self._entries.get(name) if entry is not None: return entry.value else: return default def get_list(self, name, default=None): if default is None: default = [] entry = self._entries.get(name) if entry is not None: value = entry.value if isinstance(value, list): return value elif isinstance(value, str): return [value] if value else [] else: msg = 'invalid value {} type {}' raise RuntimeError(msg.format(value, type(value))) else: return default def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name].value def __setitem__(self, name, entry): if not isinstance(entry, CMakeCacheEntry): msg = 'improper type {} for value {}, expecting CMakeCacheEntry' raise TypeError(msg.format(type(entry), entry)) self._entries[name] = entry def __delitem__(self, name): del self._entries[name] def __iter__(self): return iter(self._entries.values()) class TwisterException(Exception): pass class TwisterRuntimeError(TwisterException): pass class ConfigurationError(TwisterException): def __init__(self, cfile, message): TwisterException.__init__(self, cfile + ": " + message) class BuildError(TwisterException): pass class ExecutionError(TwisterException): pass class HarnessImporter: def __init__(self, name): sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister")) module = __import__("harness") if name: my_class = getattr(module, name) else: my_class = getattr(module, "Test") self.instance = my_class() class Handler: def __init__(self, instance, type_str="build"): """Constructor """ self.state = "waiting" self.run = False self.duration = 0 self.type_str = type_str self.binary = None self.pid_fn = None self.call_make_run = False self.name = instance.name self.instance = instance self.timeout = instance.testcase.timeout self.sourcedir = instance.testcase.source_dir self.build_dir = instance.build_dir self.log = os.path.join(self.build_dir, "handler.log") self.returncode = 0 self.set_state("running", self.duration) self.generator = None self.generator_cmd = None self.args = [] def set_state(self, state, duration): self.state = state self.duration = duration def get_state(self): ret = (self.state, self.duration) return ret def record(self, harness): if harness.recording: filename = os.path.join(self.build_dir, "recording.csv") with open(filename, "at") as csvfile: cw = csv.writer(csvfile, harness.fieldnames, lineterminator=os.linesep) cw.writerow(harness.fieldnames) for instance in harness.recording: cw.writerow(instance) class BinaryHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.terminated = False self.call_west_flash = False # Tool options self.valgrind = False self.lsan = False self.asan = False self.ubsan = False self.coverage = False def try_kill_process_by_pid(self): if self.pid_fn: pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) self.pid_fn = None # clear so we don't try to kill the binary twice try: os.kill(pid, signal.SIGTERM) except ProcessLookupError: pass def terminate(self, proc): # encapsulate terminate functionality so we do it consistently where ever # we might want to terminate the proc. We need try_kill_process_by_pid # because of both how newer ninja (1.6.0 or greater) and .NET / renode # work. Newer ninja's don't seem to pass SIGTERM down to the children # so we need to use try_kill_process_by_pid. for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except ProcessLookupError: pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() self.terminated = True def _output_reader(self, proc): self.line = proc.stdout.readline() def _output_handler(self, proc, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") timeout_extended = False timeout_time = time.time() + self.timeout while True: this_timeout = timeout_time - time.time() if this_timeout < 0: break reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(this_timeout) if not reader_t.is_alive(): line = self.line logger.debug("OUTPUT: {0}".format(line.decode('utf-8').rstrip())) log_out_fp.write(line.decode('utf-8')) log_out_fp.flush() harness.handle(line.decode('utf-8').rstrip()) if harness.state: if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 else: reader_t.join(0) break try: # POSIX arch based ztests end on their own, # so let's give it up to 100ms to do so proc.wait(0.1) except subprocess.TimeoutExpired: self.terminate(proc) log_out_fp.close() def handle(self): harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) if self.call_make_run: command = [self.generator_cmd, "run"] elif self.call_west_flash: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] else: command = [self.binary] run_valgrind = False if self.valgrind and shutil.which("valgrind"): command = ["valgrind", "--error-exitcode=2", "--leak-check=full", "--suppressions=" + ZEPHYR_BASE + "/scripts/valgrind.supp", "--log-file=" + self.build_dir + "/valgrind.log" ] + command run_valgrind = True logger.debug("Spawning process: " + " ".join(shlex.quote(word) for word in command) + os.linesep + "in directory: " + self.build_dir) start_time = time.time() env = os.environ.copy() if self.asan: env["ASAN_OPTIONS"] = "log_path=stdout:" + \ env.get("ASAN_OPTIONS", "") if not self.lsan: env["ASAN_OPTIONS"] += "detect_leaks=0" if self.ubsan: env["UBSAN_OPTIONS"] = "log_path=stdout:halt_on_error=1:" + \ env.get("UBSAN_OPTIONS", "") with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir, env=env) as proc: logger.debug("Spawning BinaryHandler Thread for %s" % self.name) t = threading.Thread(target=self._output_handler, args=(proc, harness,), daemon=True) t.start() t.join() if t.is_alive(): self.terminate(proc) t.join() proc.wait() self.returncode = proc.returncode self.try_kill_process_by_pid() handler_time = time.time() - start_time if self.coverage: subprocess.call(["GCOV_PREFIX=" + self.build_dir, "gcov", self.sourcedir, "-b", "-s", self.build_dir], shell=True) # FIXME: This is needed when killing the simulator, the console is # garbled and needs to be reset. Did not find a better way to do that. if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests if not self.terminated and self.returncode != 0: # When a process is killed, the default handler returns 128 + SIGTERM # so in that case the return code itself is not meaningful self.set_state("failed", handler_time) self.instance.reason = "Failed" elif run_valgrind and self.returncode == 2: self.set_state("failed", handler_time) self.instance.reason = "Valgrind error" elif harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state("timeout", handler_time) self.instance.reason = "Timeout" self.record(harness) class DeviceHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.suite = None def monitor_serial(self, ser, halt_fileno, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") ser_fileno = ser.fileno() readlist = [halt_fileno, ser_fileno] if self.coverage: # Set capture_coverage to True to indicate that right after # test results we should get coverage data, otherwise we exit # from the test. harness.capture_coverage = True ser.flush() while ser.isOpen(): readable, _, _ = select.select(readlist, [], [], self.timeout) if halt_fileno in readable: logger.debug('halted') ser.close() break if ser_fileno not in readable: continue # Timeout. serial_line = None try: serial_line = ser.readline() except TypeError: pass except serial.SerialException: ser.close() break # Just because ser_fileno has data doesn't mean an entire line # is available yet. if serial_line: sl = serial_line.decode('utf-8', 'ignore').lstrip() logger.debug("DEVICE: {0}".format(sl.rstrip())) log_out_fp.write(sl) log_out_fp.flush() harness.handle(sl.rstrip()) if harness.state: if not harness.capture_coverage: ser.close() break log_out_fp.close() def device_is_available(self, instance): device = instance.platform.name fixture = instance.testcase.harness_config.get("fixture") for d in self.suite.duts: if fixture and fixture not in d.fixtures: continue if d.platform != device or not (d.serial or d.serial_pty): continue d.lock.acquire() avail = False if d.available: d.available = 0 d.counter += 1 avail = True d.lock.release() if avail: return d return None def make_device_available(self, serial): for d in self.suite.duts: if d.serial == serial or d.serial_pty: d.available = 1 @staticmethod def run_custom_script(script, timeout): with subprocess.Popen(script, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, _ = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) except subprocess.TimeoutExpired: proc.kill() proc.communicate() logger.error("{} timed out".format(script)) def handle(self): out_state = "failed" runner = None hardware = self.device_is_available(self.instance) while not hardware: logger.debug("Waiting for device {} to become available".format(self.instance.platform.name)) time.sleep(1) hardware = self.device_is_available(self.instance) runner = hardware.runner or self.suite.west_runner serial_pty = hardware.serial_pty ser_pty_process = None if serial_pty: master, slave = pty.openpty() try: ser_pty_process = subprocess.Popen(re.split(',| ', serial_pty), stdout=master, stdin=master, stderr=master) except subprocess.CalledProcessError as error: logger.error("Failed to run subprocess {}, error {}".format(serial_pty, error.output)) return serial_device = os.ttyname(slave) else: serial_device = hardware.serial logger.debug("Using serial device {}".format(serial_device)) if (self.suite.west_flash is not None) or runner: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] command_extra_args = [] # There are three ways this option is used. # 1) bare: --west-flash # This results in options.west_flash == [] # 2) with a value: --west-flash="--board-id=42" # This results in options.west_flash == "--board-id=42" # 3) Multiple values: --west-flash="--board-id=42,--erase" # This results in options.west_flash == "--board-id=42 --erase" if self.suite.west_flash and self.suite.west_flash != []: command_extra_args.extend(self.suite.west_flash.split(',')) if runner: command.append("--runner") command.append(runner) board_id = hardware.probe_id or hardware.id product = hardware.product if board_id is not None: if runner == "pyocd": command_extra_args.append("--board-id") command_extra_args.append(board_id) elif runner == "nrfjprog": command_extra_args.append("--snr") command_extra_args.append(board_id) elif runner == "openocd" and product == "STM32 STLink": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "STLINK-V3": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "EDBG CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("cmsis_dap_serial %s" % (board_id)) elif runner == "jlink": command.append("--tool-opt=-SelectEmuBySN %s" % (board_id)) if command_extra_args != []: command.append('--') command.extend(command_extra_args) else: command = [self.generator_cmd, "-C", self.build_dir, "flash"] pre_script = hardware.pre_script post_flash_script = hardware.post_flash_script post_script = hardware.post_script if pre_script: self.run_custom_script(pre_script, 30) try: ser = serial.Serial( serial_device, baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=self.timeout ) except serial.SerialException as e: self.set_state("failed", 0) self.instance.reason = "Failed" logger.error("Serial device error: %s" % (str(e))) if serial_pty and ser_pty_process: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) self.make_device_available(serial_device) return ser.flush() harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) read_pipe, write_pipe = os.pipe() start_time = time.time() t = threading.Thread(target=self.monitor_serial, daemon=True, args=(ser, read_pipe, harness)) t.start() d_log = "{}/device.log".format(self.instance.build_dir) logger.debug('Flash command: %s', command) try: stdout = stderr = None with subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: (stdout, stderr) = proc.communicate(timeout=30) logger.debug(stdout.decode()) if proc.returncode != 0: self.instance.reason = "Device issue (Flash?)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) os.write(write_pipe, b'x') # halt the thread out_state = "flash_error" except subprocess.TimeoutExpired: proc.kill() (stdout, stderr) = proc.communicate() self.instance.reason = "Device issue (Timeout)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.CalledProcessError: os.write(write_pipe, b'x') # halt the thread if post_flash_script: self.run_custom_script(post_flash_script, 30) t.join(self.timeout) if t.is_alive(): logger.debug("Timed out while monitoring serial output on {}".format(self.instance.platform.name)) out_state = "timeout" if ser.isOpen(): ser.close() if serial_pty: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) os.close(write_pipe) os.close(read_pipe) handler_time = time.time() - start_time if out_state in ["timeout", "flash_error"]: for c in self.instance.testcase.cases: if c not in harness.tests: harness.tests[c] = "BLOCK" if out_state == "timeout": self.instance.reason = "Timeout" elif out_state == "flash_error": self.instance.reason = "Flash error" if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests # sometimes a test instance hasn't been executed successfully with an # empty dictionary results, in order to include it into final report, # so fill the results as BLOCK if self.instance.results == {}: for k in self.instance.testcase.cases: self.instance.results[k] = 'BLOCK' if harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state(out_state, handler_time) if post_script: self.run_custom_script(post_script, 30) self.make_device_available(serial_device) self.record(harness) class QEMUHandler(Handler): """Spawns a thread to monitor QEMU output from pipes We pass QEMU_PIPE to 'make run' and monitor the pipes for output. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") if "ignore_qemu_crash" in instance.testcase.tags: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process exection time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results, harness, ignore_unexpected_eof=False): fifo_in = fifo_fn + ".in" fifo_out = fifo_fn + ".out" # These in/out nodes are named from QEMU's perspective, not ours if os.path.exists(fifo_in): os.unlink(fifo_in) os.mkfifo(fifo_in) if os.path.exists(fifo_out): os.unlink(fifo_out) os.mkfifo(fifo_out) # We don't do anything with out_fp but we need to open it for # writing so that QEMU doesn't block, due to the way pipes work out_fp = open(fifo_in, "wb") # Disable internal buffering, we don't # want read() or poll() to ever block if there is data in there in_fp = open(fifo_out, "rb", buffering=0) log_out_fp = open(logfile, "wt") start_time = time.time() timeout_time = start_time + timeout p = select.poll() p.register(in_fp, select.POLLIN) out_state = None line = "" timeout_extended = False pid = 0 if os.path.exists(pid_fn): pid = int(open(pid_fn).read()) while True: this_timeout = int((timeout_time - time.time()) * 1000) if this_timeout < 0 or not p.poll(this_timeout): try: if pid and this_timeout > 0: #there's possibility we polled nothing because #of not enough CPU time scheduled by host for #QEMU process during p.poll(this_timeout) cpu_time = QEMUHandler._get_cpu_time(pid) if cpu_time < timeout and not out_state: timeout_time = time.time() + (timeout - cpu_time) continue except ProcessLookupError: out_state = "failed" break if not out_state: out_state = "timeout" break if pid == 0 and os.path.exists(pid_fn): pid = int(open(pid_fn).read()) if harness.is_pytest: harness.handle(None) out_state = harness.state break try: c = in_fp.read(1).decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail out_state = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: out_state = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(line) log_out_fp.flush() line = line.strip() logger.debug(f"QEMU ({pid}): {line}") harness.handle(line) if harness.state: # if we have registered a fail make sure the state is not # overridden by a false success message coming from the # testsuite if out_state not in ['failed', 'unexpected eof', 'unexpected byte']: out_state = harness.state # if we get some state, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" if harness.is_pytest: harness.pytest_run(logfile) out_state = harness.state handler.record(harness) handler_time = time.time() - start_time logger.debug(f"QEMU ({pid}) complete ({out_state}) after {handler_time} seconds") if out_state == "timeout": handler.instance.reason = "Timeout" handler.set_state("failed", handler_time) elif out_state == "failed": handler.instance.reason = "Failed" handler.set_state("failed", handler_time) elif out_state in ['unexpected eof', 'unexpected byte']: handler.instance.reason = out_state handler.set_state("failed", handler_time) else: handler.set_state(out_state, handler_time) log_out_fp.close() out_fp.close() in_fp.close() if pid: try: if pid: os.kill(pid, signal.SIGTERM) except ProcessLookupError: # Oh well, as long as it's dead! User probably sent Ctrl-C pass os.unlink(fifo_in) os.unlink(fifo_out) def handle(self): self.results = {} self.run = True # We pass this to QEMU which looks for fifos with .in and .out # suffixes. self.fifo_fn = os.path.join(self.instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(self.instance.build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log harness_import = HarnessImporter(self.instance.testcase.harness.capitalize()) harness = harness_import.instance harness.configure(self.instance) self.thread = threading.Thread(name=self.name, target=QEMUHandler._thread, args=(self, self.timeout, self.build_dir, self.log_fn, self.fifo_fn, self.pid_fn, self.results, harness, self.ignore_unexpected_eof)) self.instance.results = harness.tests self.thread.daemon = True logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread.start() if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) logger.debug("Running %s (%s)" % (self.name, self.type_str)) command = [self.generator_cmd] command += ["-C", self.build_dir, "run"] is_timeout = False qemu_pid = None with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) try: proc.wait(self.timeout) except subprocess.TimeoutExpired: # sometimes QEMU can't handle SIGTERM signal correctly # in that case kill -9 QEMU process directly and leave # twister to judge testing result by console output is_timeout = True if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) try: os.kill(qemu_pid, signal.SIGKILL) except ProcessLookupError: pass proc.wait() if harness.state == "passed": self.returncode = 0 else: self.returncode = proc.returncode else: proc.terminate() proc.kill() self.returncode = proc.returncode else: if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) logger.debug(f"No timeout, return code from QEMU ({qemu_pid}): {proc.returncode}") self.returncode = proc.returncode # Need to wait for harness to finish processing # output from QEMU. Otherwise it might miss some # error messages. self.thread.join() if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({qemu_pid}): {self.returncode}") if (self.returncode != 0 and not self.ignore_qemu_crash) or not harness.state: self.set_state("failed", 0) if is_timeout: self.instance.reason = "Timeout" else: self.instance.reason = "Exited with {}".format(self.returncode) def get_fifo(self): return self.fifo_fn class SizeCalculator: alloc_sections = [ "bss", "noinit", "app_bss", "app_noinit", "ccm_bss", "ccm_noinit" ] rw_sections = [ "datas", "initlevel", "exceptions", "initshell", "_static_thread_data_area", "k_timer_area", "k_mem_slab_area", "k_mem_pool_area", "sw_isr_table", "k_sem_area", "k_mutex_area", "app_shmem_regions", "_k_fifo_area", "_k_lifo_area", "k_stack_area", "k_msgq_area", "k_mbox_area", "k_pipe_area", "net_if_area", "net_if_dev_area", "net_l2_area", "net_l2_data", "k_queue_area", "_net_buf_pool_area", "app_datas", "kobject_data", "mmu_tables", "app_pad", "priv_stacks", "ccm_data", "usb_descriptor", "usb_data", "usb_bos_desc", "uart_mux", 'log_backends_sections', 'log_dynamic_sections', 'log_const_sections', "app_smem", 'shell_root_cmds_sections', 'log_const_sections', "font_entry_sections", "priv_stacks_noinit", "_GCOV_BSS_SECTION_NAME", "gcov", "nocache", "devices", "k_heap_area", ] # These get copied into RAM only on non-XIP ro_sections = [ "rom_start", "text", "ctors", "init_array", "reset", "z_object_assignment_area", "rodata", "net_l2", "vector", "sw_isr_table", "settings_handler_static_area", "bt_l2cap_fixed_chan_area", "bt_l2cap_br_fixed_chan_area", "bt_gatt_service_static_area", "vectors", "net_socket_register_area", "net_ppp_proto", "shell_area", "tracing_backend_area", "ppp_protocol_handler_area", ] def __init__(self, filename, extra_sections): """Constructor @param filename Path to the output binary The <filename> is parsed by objdump to determine section sizes """ # Make sure this is an ELF binary with open(filename, "rb") as f: magic = f.read(4) try: if magic != b'\x7fELF': raise TwisterRuntimeError("%s is not an ELF binary" % filename) except Exception as e: print(str(e)) sys.exit(2) # Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK. # GREP can not be used as it returns an error if the symbol is not # found. is_xip_command = "nm " + filename + \ " | awk '/CONFIG_XIP/ { print $3 }'" is_xip_output = subprocess.check_output( is_xip_command, shell=True, stderr=subprocess.STDOUT).decode( "utf-8").strip() try: if is_xip_output.endswith("no symbols"): raise TwisterRuntimeError("%s has no symbol information" % filename) except Exception as e: print(str(e)) sys.exit(2) self.is_xip = (len(is_xip_output) != 0) self.filename = filename self.sections = [] self.rom_size = 0 self.ram_size = 0 self.extra_sections = extra_sections self._calculate_sizes() def get_ram_size(self): """Get the amount of RAM the application will use up on the device @return amount of RAM, in bytes """ return self.ram_size def get_rom_size(self): """Get the size of the data that this application uses on device's flash @return amount of ROM, in bytes """ return self.rom_size def unrecognized_sections(self): """Get a list of sections inside the binary that weren't recognized @return list of unrecognized section names """ slist = [] for v in self.sections: if not v["recognized"]: slist.append(v["name"]) return slist def _calculate_sizes(self): """ Calculate RAM and ROM usage by section """ objdump_command = "objdump -h " + self.filename objdump_output = subprocess.check_output( objdump_command, shell=True).decode("utf-8").splitlines() for line in objdump_output: words = line.split() if not words: # Skip lines that are too short continue index = words[0] if not index[0].isdigit(): # Skip lines that do not start continue # with a digit name = words[1] # Skip lines with section names if name[0] == '.': # starting with '.' continue # TODO this doesn't actually reflect the size in flash or RAM as # it doesn't include linker-imposed padding between sections. # It is close though. size = int(words[2], 16) if size == 0: continue load_addr = int(words[4], 16) virt_addr = int(words[3], 16) # Add section to memory use totals (for both non-XIP and XIP scenarios) # Unrecognized section names are not included in the calculations. recognized = True if name in SizeCalculator.alloc_sections: self.ram_size += size stype = "alloc" elif name in SizeCalculator.rw_sections: self.ram_size += size self.rom_size += size stype = "rw" elif name in SizeCalculator.ro_sections: self.rom_size += size if not self.is_xip: self.ram_size += size stype = "ro" else: stype = "unknown" if name not in self.extra_sections: recognized = False self.sections.append({"name": name, "load_addr": load_addr, "size": size, "virt_addr": virt_addr, "type": stype, "recognized": recognized}) class TwisterConfigParser: """Class to read test case files with semantic checking """ def __init__(self, filename, schema): """Instantiate a new TwisterConfigParser object @param filename Source .yaml file to read """ self.data = {} self.schema = schema self.filename = filename self.tests = {} self.common = {} def load(self): self.data = scl.yaml_load_verify(self.filename, self.schema) if 'tests' in self.data: self.tests = self.data['tests'] if 'common' in self.data: self.common = self.data['common'] def _cast_value(self, value, typestr): if isinstance(value, str): v = value.strip() if typestr == "str": return v elif typestr == "float": return float(value) elif typestr == "int": return int(value) elif typestr == "bool": return value elif typestr.startswith("list") and isinstance(value, list): return value elif typestr.startswith("list") and isinstance(value, str): vs = v.split() if len(typestr) > 4 and typestr[4] == ":": return [self._cast_value(vsi, typestr[5:]) for vsi in vs] else: return vs elif typestr.startswith("set"): vs = v.split() if len(typestr) > 3 and typestr[3] == ":": return {self._cast_value(vsi, typestr[4:]) for vsi in vs} else: return set(vs) elif typestr.startswith("map"): return value else: raise ConfigurationError( self.filename, "unknown type '%s'" % value) def get_test(self, name, valid_keys): """Get a dictionary representing the keys/values within a test @param name The test in the .yaml file to retrieve data from @param valid_keys A dictionary representing the intended semantics for this test. Each key in this dictionary is a key that could be specified, if a key is given in the .yaml file which isn't in here, it will generate an error. Each value in this dictionary is another dictionary containing metadata: "default" - Default value if not given "type" - Data type to convert the text value to. Simple types supported are "str", "float", "int", "bool" which will get converted to respective Python data types. "set" and "list" may also be specified which will split the value by whitespace (but keep the elements as strings). finally, "list:<type>" and "set:<type>" may be given which will perform a type conversion after splitting the value up. "required" - If true, raise an error if not defined. If false and "default" isn't specified, a type conversion will be done on an empty string @return A dictionary containing the test key-value pairs with type conversion and default values filled in per valid_keys """ d = {} for k, v in self.common.items(): d[k] = v for k, v in self.tests[name].items(): if k in d: if isinstance(d[k], str): # By default, we just concatenate string values of keys # which appear both in "common" and per-test sections, # but some keys are handled in adhoc way based on their # semantics. if k == "filter": d[k] = "(%s) and (%s)" % (d[k], v) else: d[k] += " " + v else: d[k] = v for k, kinfo in valid_keys.items(): if k not in d: if "required" in kinfo: required = kinfo["required"] else: required = False if required: raise ConfigurationError( self.filename, "missing required value for '%s' in test '%s'" % (k, name)) else: if "default" in kinfo: default = kinfo["default"] else: default = self._cast_value("", kinfo["type"]) d[k] = default else: try: d[k] = self._cast_value(d[k], kinfo["type"]) except ValueError: raise ConfigurationError( self.filename, "bad %s value '%s' for key '%s' in name '%s'" % (kinfo["type"], d[k], k, name)) return d class Platform: """Class representing metadata for a particular platform Maps directly to BOARD when building""" platform_schema = scl.yaml_load(os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "platform-schema.yaml")) def __init__(self): """Constructor. """ self.name = "" self.twister = True # if no RAM size is specified by the board, take a default of 128K self.ram = 128 self.ignore_tags = [] self.only_tags = [] self.default = False # if no flash size is specified by the board, take a default of 512K self.flash = 512 self.supported = set() self.arch = "" self.type = "na" self.simulation = "na" self.supported_toolchains = [] self.env = [] self.env_satisfied = True self.filter_data = dict() def load(self, platform_file): scp = TwisterConfigParser(platform_file, self.platform_schema) scp.load() data = scp.data self.name = data['identifier'] self.twister = data.get("twister", True) # if no RAM size is specified by the board, take a default of 128K self.ram = data.get("ram", 128) testing = data.get("testing", {}) self.ignore_tags = testing.get("ignore_tags", []) self.only_tags = testing.get("only_tags", []) self.default = testing.get("default", False) # if no flash size is specified by the board, take a default of 512K self.flash = data.get("flash", 512) self.supported = set() for supp_feature in data.get("supported", []): for item in supp_feature.split(":"): self.supported.add(item) self.arch = data['arch'] self.type = data.get('type', "na") self.simulation = data.get('simulation', "na") self.supported_toolchains = data.get("toolchain", []) self.env = data.get("env", []) self.env_satisfied = True for env in self.env: if not os.environ.get(env, None): self.env_satisfied = False def __repr__(self): return "<%s on %s>" % (self.name, self.arch) class DisablePyTestCollectionMixin(object): __test__ = False class TestCase(DisablePyTestCollectionMixin): """Class representing a test application """ def __init__(self, testcase_root, workdir, name): """TestCase constructor. This gets called by TestSuite as it finds and reads test yaml files. Multiple TestCase instances may be generated from a single testcase.yaml, each one corresponds to an entry within that file. We need to have a unique name for every single test case. Since a testcase.yaml can define multiple tests, the canonical name for the test case is <workdir>/<name>. @param testcase_root os.path.abspath() of one of the --testcase-root @param workdir Sub-directory of testcase_root where the .yaml test configuration file was found @param name Name of this test case, corresponding to the entry name in the test case configuration file. For many test cases that just define one test, can be anything and is usually "test". This is really only used to distinguish between different cases when the testcase.yaml defines multiple tests """ self.source_dir = "" self.yamlfile = "" self.cases = [] self.name = self.get_unique(testcase_root, workdir, name) self.id = name self.type = None self.tags = set() self.extra_args = None self.extra_configs = None self.arch_allow = None self.arch_exclude = None self.skip = False self.platform_exclude = None self.platform_allow = None self.toolchain_exclude = None self.toolchain_allow = None self.tc_filter = None self.timeout = 60 self.harness = "" self.harness_config = {} self.build_only = True self.build_on_all = False self.slow = False self.min_ram = -1 self.depends_on = None self.min_flash = -1 self.extra_sections = None self.integration_platforms = [] @staticmethod def get_unique(testcase_root, workdir, name): canonical_testcase_root = os.path.realpath(testcase_root) if Path(canonical_zephyr_base) in Path(canonical_testcase_root).parents: # This is in ZEPHYR_BASE, so include path in name for uniqueness # FIXME: We should not depend on path of test for unique names. relative_tc_root = os.path.relpath(canonical_testcase_root, start=canonical_zephyr_base) else: relative_tc_root = "" # workdir can be "." unique = os.path.normpath(os.path.join(relative_tc_root, workdir, name)) check = name.split(".") if len(check) < 2: raise TwisterException(f"""bad test name '{name}' in {testcase_root}/{workdir}. \ Tests should reference the category and subsystem with a dot as a separator. """ ) return unique @staticmethod def scan_file(inf_name): suite_regex = re.compile( # do not match until end-of-line, otherwise we won't allow # stc_regex below to catch the ones that are declared in the same # line--as we only search starting the end of this match br"^\s*ztest_test_suite\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) stc_regex = re.compile( br"^\s*" # empy space at the beginning is ok # catch the case where it is declared in the same sentence, e.g: # # ztest_test_suite(mutex_complex, ztest_user_unit_test(TESTNAME)); br"(?:ztest_test_suite\([a-zA-Z0-9_]+,\s*)?" # Catch ztest[_user]_unit_test-[_setup_teardown](TESTNAME) br"ztest_(?:1cpu_)?(?:user_)?unit_test(?:_setup_teardown)?" # Consume the argument that becomes the extra testcse br"\(\s*" br"(?P<stc_name>[a-zA-Z0-9_]+)" # _setup_teardown() variant has two extra arguments that we ignore br"(?:\s*,\s*[a-zA-Z0-9_]+\s*,\s*[a-zA-Z0-9_]+)?" br"\s*\)", # We don't check how it finishes; we don't care re.MULTILINE) suite_run_regex = re.compile( br"^\s*ztest_run_test_suite\((?P<suite_name>[a-zA-Z0-9_]+)\)", re.MULTILINE) achtung_regex = re.compile( br"(#ifdef|#endif)", re.MULTILINE) warnings = None with open(inf_name) as inf: if os.name == 'nt': mmap_args = {'fileno': inf.fileno(), 'length': 0, 'access': mmap.ACCESS_READ} else: mmap_args = {'fileno': inf.fileno(), 'length': 0, 'flags': mmap.MAP_PRIVATE, 'prot': mmap.PROT_READ, 'offset': 0} with contextlib.closing(mmap.mmap(**mmap_args)) as main_c: suite_regex_match = suite_regex.search(main_c) if not suite_regex_match: # can't find ztest_test_suite, maybe a client, because # it includes ztest.h return None, None suite_run_match = suite_run_regex.search(main_c) if not suite_run_match: raise ValueError("can't find ztest_run_test_suite") achtung_matches = re.findall( achtung_regex, main_c[suite_regex_match.end():suite_run_match.start()]) if achtung_matches: warnings = "found invalid %s in ztest_test_suite()" \ % ", ".join(sorted({match.decode() for match in achtung_matches},reverse = True)) _matches = re.findall( stc_regex, main_c[suite_regex_match.end():suite_run_match.start()]) for match in _matches: if not match.decode().startswith("test_"): warnings = "Found a test that does not start with test_" matches = [match.decode().replace("test_", "", 1) for match in _matches] return matches, warnings def scan_path(self, path): subcases = [] for filename in glob.glob(os.path.join(path, "src", "*.c*")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) raise TwisterRuntimeError("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) for filename in glob.glob(os.path.join(path, "*.c")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) return subcases def parse_subcases(self, test_path): results = self.scan_path(test_path) for sub in results: name = "{}.{}".format(self.id, sub) self.cases.append(name) if not results: self.cases.append(self.id) def __str__(self): return self.name class TestInstance(DisablePyTestCollectionMixin): """Class representing the execution of a particular TestCase on a platform @param test The TestCase object we want to build/execute @param platform Platform object that we want to build and run against @param base_outdir Base directory for all test results. The actual out directory used is <outdir>/<platform>/<test case name> """ def __init__(self, testcase, platform, outdir): self.testcase = testcase self.platform = platform self.status = None self.reason = "Unknown" self.metrics = dict() self.handler = None self.outdir = outdir self.name = os.path.join(platform.name, testcase.name) self.build_dir = os.path.join(outdir, platform.name, testcase.name) self.run = False self.results = {} def __getstate__(self): d = self.__dict__.copy() return d def __setstate__(self, d): self.__dict__.update(d) def __lt__(self, other): return self.name < other.name @staticmethod def testcase_runnable(testcase, fixtures): can_run = False # console harness allows us to run the test and capture data. if testcase.harness in [ 'console', 'ztest', 'pytest']: can_run = True # if we have a fixture that is also being supplied on the # command-line, then we need to run the test, not just build it. fixture = testcase.harness_config.get('fixture') if fixture: can_run = (fixture in fixtures) elif testcase.harness: can_run = False else: can_run = True return can_run # Global testsuite parameters def check_runnable(self, enable_slow=False, filter='buildable', fixtures=[]): # right now we only support building on windows. running is still work # in progress. if os.name == 'nt': return False # we asked for build-only on the command line if self.testcase.build_only: return False # Do not run slow tests: skip_slow = self.testcase.slow and not enable_slow if skip_slow: return False target_ready = bool(self.testcase.type == "unit" or \ self.platform.type == "native" or \ self.platform.simulation in ["mdb-nsim", "nsim", "renode", "qemu", "tsim", "armfvp"] or \ filter == 'runnable') if self.platform.simulation == "nsim": if not find_executable("nsimdrv"): target_ready = False if self.platform.simulation == "mdb-nsim": if not find_executable("mdb"): target_ready = False if self.platform.simulation == "renode": if not find_executable("renode"): target_ready = False if self.platform.simulation == "tsim": if not find_executable("tsim-leon3"): target_ready = False testcase_runnable = self.testcase_runnable(self.testcase, fixtures) return testcase_runnable and target_ready def create_overlay(self, platform, enable_asan=False, enable_ubsan=False, enable_coverage=False, coverage_platform=[]): # Create this in a "twister/" subdirectory otherwise this # will pass this overlay to kconfig.py *twice* and kconfig.cmake # will silently give that second time precedence over any # --extra-args=CONFIG_* subdir = os.path.join(self.build_dir, "twister") content = "" if self.testcase.extra_configs: content = "\n".join(self.testcase.extra_configs) if enable_coverage: if platform.name in coverage_platform: content = content + "\nCONFIG_COVERAGE=y" content = content + "\nCONFIG_COVERAGE_DUMP=y" if enable_asan: if platform.type == "native": content = content + "\nCONFIG_ASAN=y" if enable_ubsan: if platform.type == "native": content = content + "\nCONFIG_UBSAN=y" if content: os.makedirs(subdir, exist_ok=True) file = os.path.join(subdir, "testcase_extra.conf") with open(file, "w") as f: f.write(content) return content def calculate_sizes(self): """Get the RAM/ROM sizes of a test case. This can only be run after the instance has been executed by MakeGenerator, otherwise there won't be any binaries to measure. @return A SizeCalculator object """ fns = glob.glob(os.path.join(self.build_dir, "zephyr", "*.elf")) fns.extend(glob.glob(os.path.join(self.build_dir, "zephyr", "*.exe"))) fns = [x for x in fns if not x.endswith('_prebuilt.elf')] if len(fns) != 1: raise BuildError("Missing/multiple output ELF binary") return SizeCalculator(fns[0], self.testcase.extra_sections) def fill_results_by_status(self): """Fills results according to self.status The method is used to propagate the instance level status to the test cases inside. Useful when the whole instance is skipped and the info is required also at the test cases level for reporting. Should be used with caution, e.g. should not be used to fill all results with passes """ status_to_verdict = { 'skipped': 'SKIP', 'error': 'BLOCK', 'failure': 'FAILED' } for k in self.results: self.results[k] = status_to_verdict[self.status] def __repr__(self): return "<TestCase %s on %s>" % (self.testcase.name, self.platform.name) class CMake(): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') def __init__(self, testcase, platform, source_dir, build_dir): self.cwd = None self.capture_output = True self.defconfig = {} self.cmake_cache = {} self.instance = None self.testcase = testcase self.platform = platform self.source_dir = source_dir self.build_dir = build_dir self.log = "build.log" self.generator = None self.generator_cmd = None def parse_generated(self): self.defconfig = {} return {} def run_build(self, args=[]): logger.debug("Building %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [] cmake_args.extend(args) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() results = {} if p.returncode == 0: msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) self.instance.status = "passed" results = {'msg': msg, "returncode": p.returncode, "instance": self.instance} if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) else: return None else: # A real error occurred, raise an exception log_msg = "" if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) if log_msg: res = re.findall("region `(FLASH|RAM|SRAM)' overflowed by", log_msg) if res and not self.overflow_as_errors: logger.debug("Test skipped due to {} Overflow".format(res[0])) self.instance.status = "skipped" self.instance.reason = "{} overflow".format(res[0]) else: self.instance.status = "error" self.instance.reason = "Build failure" results = { "returncode": p.returncode, "instance": self.instance, } return results def run_cmake(self, args=[]): if self.warnings_as_errors: ldflags = "-Wl,--fatal-warnings" cflags = "-Werror" aflags = "-Wa,--fatal-warnings" gen_defines_args = "--err-on-deprecated-properties" else: ldflags = cflags = aflags = "" gen_defines_args = "" logger.debug("Running cmake on %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [ f'-B{self.build_dir}', f'-S{self.source_dir}', f'-DEXTRA_CFLAGS="{cflags}"', f'-DEXTRA_AFLAGS="{aflags}', f'-DEXTRA_LDFLAGS="{ldflags}"', f'-DEXTRA_GEN_DEFINES_ARGS={gen_defines_args}', f'-G{self.generator}' ] if self.cmake_only: cmake_args.append("-DCMAKE_EXPORT_COMPILE_COMMANDS=1") args = ["-D{}".format(a.replace('"', '')) for a in args] cmake_args.extend(args) cmake_opts = ['-DBOARD={}'.format(self.platform.name)] cmake_args.extend(cmake_opts) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: filter_results = self.parse_generated() msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) logger.debug(msg) results = {'msg': msg, 'filter': filter_results} else: self.instance.status = "error" self.instance.reason = "Cmake build failure" logger.error("Cmake build failure: %s for %s" % (self.source_dir, self.platform.name)) results = {"returncode": p.returncode} if out: with open(os.path.join(self.build_dir, self.log), "a") as log: log_msg = out.decode(sys.getdefaultencoding()) log.write(log_msg) return results @staticmethod def run_cmake_script(args=[]): logger.debug("Running cmake script %s" % (args[0])) cmake_args = ["-D{}".format(a.replace('"', '')) for a in args[1:]] cmake_args.extend(['-P', args[0]]) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') if not cmake: msg = "Unable to find `cmake` in path" logger.error(msg) raise Exception(msg) cmd = [cmake] + cmake_args kwargs = dict() kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: msg = "Finished running %s" % (args[0]) logger.debug(msg) results = {"returncode": p.returncode, "msg": msg, "stdout": out} else: logger.error("Cmake script failure: %s" % (args[0])) results = {"returncode": p.returncode} return results class FilterBuilder(CMake): def __init__(self, testcase, platform, source_dir, build_dir): super().__init__(testcase, platform, source_dir, build_dir) self.log = "config-twister.log" def parse_generated(self): if self.platform.name == "unit_testing": return {} cmake_cache_path = os.path.join(self.build_dir, "CMakeCache.txt") defconfig_path = os.path.join(self.build_dir, "zephyr", ".config") with open(defconfig_path, "r") as fp: defconfig = {} for line in fp.readlines(): m = self.config_re.match(line) if not m: if line.strip() and not line.startswith("#"): sys.stderr.write("Unrecognized line %s\n" % line) continue defconfig[m.group(1)] = m.group(2).strip() self.defconfig = defconfig cmake_conf = {} try: cache = CMakeCache.from_file(cmake_cache_path) except FileNotFoundError: cache = {} for k in iter(cache): cmake_conf[k.name] = k.value self.cmake_cache = cmake_conf filter_data = { "ARCH": self.platform.arch, "PLATFORM": self.platform.name } filter_data.update(os.environ) filter_data.update(self.defconfig) filter_data.update(self.cmake_cache) edt_pickle = os.path.join(self.build_dir, "zephyr", "edt.pickle") if self.testcase and self.testcase.tc_filter: try: if os.path.exists(edt_pickle): with open(edt_pickle, 'rb') as f: edt = pickle.load(f) else: edt = None res = expr_parser.parse(self.testcase.tc_filter, filter_data, edt) except (ValueError, SyntaxError) as se: sys.stderr.write( "Failed processing %s\n" % self.testcase.yamlfile) raise se if not res: return {os.path.join(self.platform.name, self.testcase.name): True} else: return {os.path.join(self.platform.name, self.testcase.name): False} else: self.platform.filter_data = filter_data return filter_data class ProjectBuilder(FilterBuilder): def __init__(self, suite, instance, **kwargs): super().__init__(instance.testcase, instance.platform, instance.testcase.source_dir, instance.build_dir) self.log = "build.log" self.instance = instance self.suite = suite self.filtered_tests = 0 self.lsan = kwargs.get('lsan', False) self.asan = kwargs.get('asan', False) self.ubsan = kwargs.get('ubsan', False) self.valgrind = kwargs.get('valgrind', False) self.extra_args = kwargs.get('extra_args', []) self.device_testing = kwargs.get('device_testing', False) self.cmake_only = kwargs.get('cmake_only', False) self.cleanup = kwargs.get('cleanup', False) self.coverage = kwargs.get('coverage', False) self.inline_logs = kwargs.get('inline_logs', False) self.generator = kwargs.get('generator', None) self.generator_cmd = kwargs.get('generator_cmd', None) self.verbose = kwargs.get('verbose', None) self.warnings_as_errors = kwargs.get('warnings_as_errors', True) self.overflow_as_errors = kwargs.get('overflow_as_errors', False) @staticmethod def log_info(filename, inline_logs): filename = os.path.abspath(os.path.realpath(filename)) if inline_logs: logger.info("{:-^100}".format(filename)) try: with open(filename) as fp: data = fp.read() except Exception as e: data = "Unable to read log data (%s)\n" % (str(e)) logger.error(data) logger.info("{:-^100}".format(filename)) else: logger.error("see: " + Fore.YELLOW + filename + Fore.RESET) def log_info_file(self, inline_logs): build_dir = self.instance.build_dir h_log = "{}/handler.log".format(build_dir) b_log = "{}/build.log".format(build_dir) v_log = "{}/valgrind.log".format(build_dir) d_log = "{}/device.log".format(build_dir) if os.path.exists(v_log) and "Valgrind" in self.instance.reason: self.log_info("{}".format(v_log), inline_logs) elif os.path.exists(h_log) and os.path.getsize(h_log) > 0: self.log_info("{}".format(h_log), inline_logs) elif os.path.exists(d_log) and os.path.getsize(d_log) > 0: self.log_info("{}".format(d_log), inline_logs) else: self.log_info("{}".format(b_log), inline_logs) def setup_handler(self): instance = self.instance args = [] # FIXME: Needs simplification if instance.platform.simulation == "qemu": instance.handler = QEMUHandler(instance, "qemu") args.append("QEMU_PIPE=%s" % instance.handler.get_fifo()) instance.handler.call_make_run = True elif instance.testcase.type == "unit": instance.handler = BinaryHandler(instance, "unit") instance.handler.binary = os.path.join(instance.build_dir, "testbinary") if self.coverage: args.append("COVERAGE=1") elif instance.platform.type == "native": handler = BinaryHandler(instance, "native") handler.asan = self.asan handler.valgrind = self.valgrind handler.lsan = self.lsan handler.ubsan = self.ubsan handler.coverage = self.coverage handler.binary = os.path.join(instance.build_dir, "zephyr", "zephyr.exe") instance.handler = handler elif instance.platform.simulation == "renode": if find_executable("renode"): instance.handler = BinaryHandler(instance, "renode") instance.handler.pid_fn = os.path.join(instance.build_dir, "renode.pid") instance.handler.call_make_run = True elif instance.platform.simulation == "tsim": instance.handler = BinaryHandler(instance, "tsim") instance.handler.call_make_run = True elif self.device_testing: instance.handler = DeviceHandler(instance, "device") instance.handler.coverage = self.coverage elif instance.platform.simulation == "nsim": if find_executable("nsimdrv"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "mdb-nsim": if find_executable("mdb"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.pid_fn = os.path.join(instance.build_dir, "mdb.pid") instance.handler.call_west_flash = True elif instance.platform.simulation == "armfvp": instance.handler = BinaryHandler(instance, "armfvp") instance.handler.call_make_run = True if instance.handler: instance.handler.args = args instance.handler.generator_cmd = self.generator_cmd instance.handler.generator = self.generator def process(self, pipeline, done, message, lock, results): op = message.get('op') if not self.instance.handler: self.setup_handler() # The build process, call cmake and build with configured generator if op == "cmake": res = self.cmake() if self.instance.status in ["failed", "error"]: pipeline.put({"op": "report", "test": self.instance}) elif self.cmake_only: if self.instance.status is None: self.instance.status = "passed" pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.name in res['filter'] and res['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = "skipped" self.instance.reason = "filter" results.skipped_runtime += 1 for case in self.instance.testcase.cases: self.instance.results.update({case: 'SKIP'}) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "build", "test": self.instance}) elif op == "build": logger.debug("build test: %s" % self.instance.name) res = self.build() if not res: self.instance.status = "error" self.instance.reason = "Build Failure" pipeline.put({"op": "report", "test": self.instance}) else: # Count skipped cases during build, for example # due to ram/rom overflow. inst = res.get("instance", None) if inst and inst.status == "skipped": results.skipped_runtime += 1 if res.get('returncode', 1) > 0: pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.run and self.instance.handler: pipeline.put({"op": "run", "test": self.instance}) else: pipeline.put({"op": "report", "test": self.instance}) # Run the generated binary using one of the supported handlers elif op == "run": logger.debug("run test: %s" % self.instance.name) self.run() self.instance.status, _ = self.instance.handler.get_state() logger.debug(f"run status: {self.instance.name} {self.instance.status}") # to make it work with pickle self.instance.handler.thread = None self.instance.handler.suite = None pipeline.put({ "op": "report", "test": self.instance, "status": self.instance.status, "reason": self.instance.reason } ) # Report results and output progress to screen elif op == "report": with lock: done.put(self.instance) self.report_out(results) if self.cleanup and not self.coverage and self.instance.status == "passed": pipeline.put({ "op": "cleanup", "test": self.instance }) elif op == "cleanup": if self.device_testing: self.cleanup_device_testing_artifacts() else: self.cleanup_artifacts() def cleanup_artifacts(self, additional_keep=[]): logger.debug("Cleaning up {}".format(self.instance.build_dir)) allow = [ 'zephyr/.config', 'handler.log', 'build.log', 'device.log', 'recording.csv', ] allow += additional_keep allow = [os.path.join(self.instance.build_dir, file) for file in allow] for dirpath, dirnames, filenames in os.walk(self.instance.build_dir, topdown=False): for name in filenames: path = os.path.join(dirpath, name) if path not in allow: os.remove(path) # Remove empty directories and symbolic links to directories for dir in dirnames: path = os.path.join(dirpath, dir) if os.path.islink(path): os.remove(path) elif not os.listdir(path): os.rmdir(path) def cleanup_device_testing_artifacts(self): logger.debug("Cleaning up for Device Testing {}".format(self.instance.build_dir)) sanitizelist = [ 'CMakeCache.txt', 'zephyr/runners.yaml', ] keep = [ 'zephyr/zephyr.hex', 'zephyr/zephyr.bin', 'zephyr/zephyr.elf', ] keep += sanitizelist self.cleanup_artifacts(keep) # sanitize paths so files are relocatable for file in sanitizelist: file = os.path.join(self.instance.build_dir, file) with open(file, "rt") as fin: data = fin.read() data = data.replace(canonical_zephyr_base+"/", "") with open(file, "wt") as fin: fin.write(data) def report_out(self, results): total_to_do = results.total - results.skipped_configs total_tests_width = len(str(total_to_do)) results.done += 1 instance = self.instance if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.status == "error": results.error += 1 results.failed += 1 if self.verbose: status = Fore.RED + "FAILED " + Fore.RESET + instance.reason else: print("") logger.error( "{:<25} {:<50} {}FAILED{}: {}".format( instance.platform.name, instance.testcase.name, Fore.RED, Fore.RESET, instance.reason)) if not self.verbose: self.log_info_file(self.inline_logs) elif instance.status == "skipped": status = Fore.YELLOW + "SKIPPED" + Fore.RESET elif instance.status == "passed": status = Fore.GREEN + "PASSED" + Fore.RESET else: logger.debug(f"Unknown status = {instance.status}") status = Fore.YELLOW + "UNKNOWN" + Fore.RESET if self.verbose: if self.cmake_only: more_info = "cmake" elif instance.status == "skipped": more_info = instance.reason else: if instance.handler and instance.run: more_info = instance.handler.type_str htime = instance.handler.duration if htime: more_info += " {:.3f}s".format(htime) else: more_info = "build" logger.info("{:>{}}/{} {:<25} {:<50} {} ({})".format( results.done, total_tests_width, total_to_do, instance.platform.name, instance.testcase.name, status, more_info)) if instance.status in ["error", "failed", "timeout"]: self.log_info_file(self.inline_logs) else: completed_perc = 0 if total_to_do > 0: completed_perc = int((float(results.done) / total_to_do) * 100) skipped = results.skipped_configs + results.skipped_runtime sys.stdout.write("\rINFO - Total complete: %s%4d/%4d%s %2d%% skipped: %s%4d%s, failed: %s%4d%s" % ( Fore.GREEN, results.done, total_to_do, Fore.RESET, completed_perc, Fore.YELLOW if skipped > 0 else Fore.RESET, skipped, Fore.RESET, Fore.RED if results.failed > 0 else Fore.RESET, results.failed, Fore.RESET ) ) sys.stdout.flush() def cmake(self): instance = self.instance args = self.testcase.extra_args[:] args += self.extra_args if instance.handler: args += instance.handler.args # merge overlay files into one variable def extract_overlays(args): re_overlay = re.compile('OVERLAY_CONFIG=(.*)') other_args = [] overlays = [] for arg in args: match = re_overlay.search(arg) if match: overlays.append(match.group(1).strip('\'"')) else: other_args.append(arg) args[:] = other_args return overlays overlays = extract_overlays(args) if os.path.exists(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")): overlays.append(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")) if overlays: args.append("OVERLAY_CONFIG=\"%s\"" % (" ".join(overlays))) res = self.run_cmake(args) return res def build(self): res = self.run_build(['--build', self.build_dir]) return res def run(self): instance = self.instance if instance.handler: if instance.handler.type_str == "device": instance.handler.suite = self.suite instance.handler.handle() sys.stdout.flush() class TestSuite(DisablePyTestCollectionMixin): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') tc_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "testcase-schema.yaml")) quarantine_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "quarantine-schema.yaml")) testcase_valid_keys = {"tags": {"type": "set", "required": False}, "type": {"type": "str", "default": "integration"}, "extra_args": {"type": "list"}, "extra_configs": {"type": "list"}, "build_only": {"type": "bool", "default": False}, "build_on_all": {"type": "bool", "default": False}, "skip": {"type": "bool", "default": False}, "slow": {"type": "bool", "default": False}, "timeout": {"type": "int", "default": 60}, "min_ram": {"type": "int", "default": 8}, "depends_on": {"type": "set"}, "min_flash": {"type": "int", "default": 32}, "arch_allow": {"type": "set"}, "arch_exclude": {"type": "set"}, "extra_sections": {"type": "list", "default": []}, "integration_platforms": {"type": "list", "default": []}, "platform_exclude": {"type": "set"}, "platform_allow": {"type": "set"}, "toolchain_exclude": {"type": "set"}, "toolchain_allow": {"type": "set"}, "filter": {"type": "str"}, "harness": {"type": "str"}, "harness_config": {"type": "map", "default": {}} } RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "release", "twister_last_release.csv") SAMPLE_FILENAME = 'sample.yaml' TESTCASE_FILENAME = 'testcase.yaml' def __init__(self, board_root_list=[], testcase_roots=[], outdir=None): self.roots = testcase_roots if not isinstance(board_root_list, list): self.board_roots = [board_root_list] else: self.board_roots = board_root_list # Testsuite Options self.coverage_platform = [] self.build_only = False self.cmake_only = False self.cleanup = False self.enable_slow = False self.device_testing = False self.fixtures = [] self.enable_coverage = False self.enable_ubsan = False self.enable_lsan = False self.enable_asan = False self.enable_valgrind = False self.extra_args = [] self.inline_logs = False self.enable_sizes_report = False self.west_flash = None self.west_runner = None self.generator = None self.generator_cmd = None self.warnings_as_errors = True self.overflow_as_errors = False self.quarantine_verify = False # Keep track of which test cases we've filtered out and why self.testcases = {} self.quarantine = {} self.platforms = [] self.selected_platforms = [] self.filtered_platforms = [] self.default_platforms = [] self.outdir = os.path.abspath(outdir) self.discards = {} self.load_errors = 0 self.instances = dict() self.total_platforms = 0 self.start_time = 0 self.duration = 0 self.warnings = 0 # hardcoded for now self.duts = [] # run integration tests only self.integration = False self.pipeline = None self.version = "NA" def check_zephyr_version(self): try: subproc = subprocess.run(["git", "describe", "--abbrev=12"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: self.version = subproc.stdout.strip() logger.info(f"Zephyr version: {self.version}") except OSError: logger.info("Cannot read zephyr version.") def get_platform_instances(self, platform): filtered_dict = {k:v for k,v in self.instances.items() if k.startswith(platform + "/")} return filtered_dict def config(self): logger.info("coverage platform: {}".format(self.coverage_platform)) # Debug Functions @staticmethod def info(what): sys.stdout.write(what + "\n") sys.stdout.flush() def update_counting(self, results=None, initial=False): results.skipped_configs = 0 results.skipped_cases = 0 for instance in self.instances.values(): if initial: results.cases += len(instance.testcase.cases) if instance.status == 'skipped': results.skipped_configs += 1 results.skipped_cases += len(instance.testcase.cases) elif instance.status == "passed": results.passed += 1 for res in instance.results.values(): if res == 'SKIP': results.skipped_cases += 1 def compare_metrics(self, filename): # name, datatype, lower results better interesting_metrics = [("ram_size", int, True), ("rom_size", int, True)] if not os.path.exists(filename): logger.error("Cannot compare metrics, %s not found" % filename) return [] results = [] saved_metrics = {} with open(filename) as fp: cr = csv.DictReader(fp) for row in cr: d = {} for m, _, _ in interesting_metrics: d[m] = row[m] saved_metrics[(row["test"], row["platform"])] = d for instance in self.instances.values(): mkey = (instance.testcase.name, instance.platform.name) if mkey not in saved_metrics: continue sm = saved_metrics[mkey] for metric, mtype, lower_better in interesting_metrics: if metric not in instance.metrics: continue if sm[metric] == "": continue delta = instance.metrics.get(metric, 0) - mtype(sm[metric]) if delta == 0: continue results.append((instance, metric, instance.metrics.get(metric, 0), delta, lower_better)) return results def footprint_reports(self, report, show_footprint, all_deltas, footprint_threshold, last_metrics): if not report: return logger.debug("running footprint_reports") deltas = self.compare_metrics(report) warnings = 0 if deltas and show_footprint: for i, metric, value, delta, lower_better in deltas: if not all_deltas and ((delta < 0 and lower_better) or (delta > 0 and not lower_better)): continue percentage = 0 if value > delta: percentage = (float(delta) / float(value - delta)) if not all_deltas and (percentage < (footprint_threshold / 100.0)): continue logger.info("{:<25} {:<60} {}{}{}: {} {:<+4}, is now {:6} {:+.2%}".format( i.platform.name, i.testcase.name, Fore.YELLOW, "INFO" if all_deltas else "WARNING", Fore.RESET, metric, delta, value, percentage)) warnings += 1 if warnings: logger.warning("Deltas based on metrics from last %s" % ("release" if not last_metrics else "run")) def summary(self, results, unrecognized_sections): failed = 0 run = 0 for instance in self.instances.values(): if instance.status == "failed": failed += 1 elif instance.metrics.get("unrecognized") and not unrecognized_sections: logger.error("%sFAILED%s: %s has unrecognized binary sections: %s" % (Fore.RED, Fore.RESET, instance.name, str(instance.metrics.get("unrecognized", [])))) failed += 1 if instance.metrics.get('handler_time', None): run += 1 if results.total and results.total != results.skipped_configs: pass_rate = (float(results.passed) / float(results.total - results.skipped_configs)) else: pass_rate = 0 logger.info( "{}{} of {}{} test configurations passed ({:.2%}), {}{}{} failed, {} skipped with {}{}{} warnings in {:.2f} seconds".format( Fore.RED if failed else Fore.GREEN, results.passed, results.total - results.skipped_configs, Fore.RESET, pass_rate, Fore.RED if results.failed else Fore.RESET, results.failed, Fore.RESET, results.skipped_configs, Fore.YELLOW if self.warnings else Fore.RESET, self.warnings, Fore.RESET, self.duration)) self.total_platforms = len(self.platforms) # if we are only building, do not report about tests being executed. if self.platforms and not self.build_only: logger.info("In total {} test cases were executed, {} skipped on {} out of total {} platforms ({:02.2f}%)".format( results.cases - results.skipped_cases, results.skipped_cases, len(self.filtered_platforms), self.total_platforms, (100 * len(self.filtered_platforms) / len(self.platforms)) )) logger.info(f"{Fore.GREEN}{run}{Fore.RESET} test configurations executed on platforms, \ {Fore.RED}{results.total - run - results.skipped_configs}{Fore.RESET} test configurations were only built.") def save_reports(self, name, suffix, report_dir, no_update, release, only_failed, platform_reports, json_report): if not self.instances: return logger.info("Saving reports...") if name: report_name = name else: report_name = "twister" if report_dir: os.makedirs(report_dir, exist_ok=True) filename = os.path.join(report_dir, report_name) outdir = report_dir else: filename = os.path.join(self.outdir, report_name) outdir = self.outdir if suffix: filename = "{}_{}".format(filename, suffix) if not no_update: self.xunit_report(filename + ".xml", full_report=False, append=only_failed, version=self.version) self.xunit_report(filename + "_report.xml", full_report=True, append=only_failed, version=self.version) self.csv_report(filename + ".csv") if json_report: self.json_report(filename + ".json", append=only_failed, version=self.version) if platform_reports: self.target_report(outdir, suffix, append=only_failed) if self.discards: self.discard_report(filename + "_discard.csv") if release: self.csv_report(self.RELEASE_DATA) def add_configurations(self): for board_root in self.board_roots: board_root = os.path.abspath(board_root) logger.debug("Reading platform configuration files under %s..." % board_root) for file in glob.glob(os.path.join(board_root, "*", "*", "*.yaml")): try: platform = Platform() platform.load(file) if platform.name in [p.name for p in self.platforms]: logger.error(f"Duplicate platform {platform.name} in {file}") raise Exception(f"Duplicate platform identifier {platform.name} found") if platform.twister: self.platforms.append(platform) if platform.default: self.default_platforms.append(platform.name) except RuntimeError as e: logger.error("E: %s: can't load: %s" % (file, e)) self.load_errors += 1 def get_all_tests(self): tests = [] for _, tc in self.testcases.items(): for case in tc.cases: tests.append(case) return tests @staticmethod def get_toolchain(): toolchain_script = Path(ZEPHYR_BASE) / Path('cmake/verify-toolchain.cmake') result = CMake.run_cmake_script([toolchain_script, "FORMAT=json"]) try: if result['returncode']: raise TwisterRuntimeError("E: Variable ZEPHYR_TOOLCHAIN_VARIANT is not defined") except Exception as e: print(str(e)) sys.exit(2) toolchain = json.loads(result['stdout'])['ZEPHYR_TOOLCHAIN_VARIANT'] logger.info(f"Using '{toolchain}' toolchain.") return toolchain def add_testcases(self, testcase_filter=[]): for root in self.roots: root = os.path.abspath(root) logger.debug("Reading test case configuration files under %s..." % root) for dirpath, _, filenames in os.walk(root, topdown=True): if self.SAMPLE_FILENAME in filenames: filename = self.SAMPLE_FILENAME elif self.TESTCASE_FILENAME in filenames: filename = self.TESTCASE_FILENAME else: continue logger.debug("Found possible test case in " + dirpath) tc_path = os.path.join(dirpath, filename) try: parsed_data = TwisterConfigParser(tc_path, self.tc_schema) parsed_data.load() tc_path = os.path.dirname(tc_path) workdir = os.path.relpath(tc_path, root) for name in parsed_data.tests.keys(): tc = TestCase(root, workdir, name) tc_dict = parsed_data.get_test(name, self.testcase_valid_keys) tc.source_dir = tc_path tc.yamlfile = tc_path tc.type = tc_dict["type"] tc.tags = tc_dict["tags"] tc.extra_args = tc_dict["extra_args"] tc.extra_configs = tc_dict["extra_configs"] tc.arch_allow = tc_dict["arch_allow"] tc.arch_exclude = tc_dict["arch_exclude"] tc.skip = tc_dict["skip"] tc.platform_exclude = tc_dict["platform_exclude"] tc.platform_allow = tc_dict["platform_allow"] tc.toolchain_exclude = tc_dict["toolchain_exclude"] tc.toolchain_allow = tc_dict["toolchain_allow"] tc.tc_filter = tc_dict["filter"] tc.timeout = tc_dict["timeout"] tc.harness = tc_dict["harness"] tc.harness_config = tc_dict["harness_config"] if tc.harness == 'console' and not tc.harness_config: raise Exception('Harness config error: console harness defined without a configuration.') tc.build_only = tc_dict["build_only"] tc.build_on_all = tc_dict["build_on_all"] tc.slow = tc_dict["slow"] tc.min_ram = tc_dict["min_ram"] tc.depends_on = tc_dict["depends_on"] tc.min_flash = tc_dict["min_flash"] tc.extra_sections = tc_dict["extra_sections"] tc.integration_platforms = tc_dict["integration_platforms"] tc.parse_subcases(tc_path) if testcase_filter: if tc.name and tc.name in testcase_filter: self.testcases[tc.name] = tc else: self.testcases[tc.name] = tc except Exception as e: logger.error("%s: can't load (skipping): %s" % (tc_path, e)) self.load_errors += 1 return len(self.testcases) def get_platform(self, name): selected_platform = None for platform in self.platforms: if platform.name == name: selected_platform = platform break return selected_platform def load_quarantine(self, file): """ Loads quarantine list from the given yaml file. Creates a dictionary of all tests configurations (platform + scenario: comment) that shall be skipped due to quarantine """ # Load yaml into quarantine_yaml quarantine_yaml = scl.yaml_load_verify(file, self.quarantine_schema) # Create quarantine_list with a product of the listed # platforms and scenarios for each entry in quarantine yaml quarantine_list = [] for quar_dict in quarantine_yaml: if quar_dict['platforms'][0] == "all": plat = [p.name for p in self.platforms] else: plat = quar_dict['platforms'] comment = quar_dict.get('comment', "NA") quarantine_list.append([{".".join([p, s]): comment} for p in plat for s in quar_dict['scenarios']]) # Flatten the quarantine_list quarantine_list = [it for sublist in quarantine_list for it in sublist] # Change quarantine_list into a dictionary for d in quarantine_list: self.quarantine.update(d) def load_from_file(self, file, filter_status=[], filter_platform=[]): try: with open(file, "r") as fp: cr = csv.DictReader(fp) instance_list = [] for row in cr: if row["status"] in filter_status: continue test = row["test"] platform = self.get_platform(row["platform"]) if filter_platform and platform.name not in filter_platform: continue instance = TestInstance(self.testcases[test], platform, self.outdir) if self.device_testing: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) instance.create_overlay(platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) instance_list.append(instance) self.add_instances(instance_list) except KeyError as e: logger.error("Key error while parsing tests file.({})".format(str(e))) sys.exit(2) except FileNotFoundError as e: logger.error("Couldn't find input file with list of tests. ({})".format(e)) sys.exit(2) def apply_filters(self, **kwargs): toolchain = self.get_toolchain() discards = {} platform_filter = kwargs.get('platform') exclude_platform = kwargs.get('exclude_platform', []) testcase_filter = kwargs.get('run_individual_tests', []) arch_filter = kwargs.get('arch') tag_filter = kwargs.get('tag') exclude_tag = kwargs.get('exclude_tag') all_filter = kwargs.get('all') runnable = kwargs.get('runnable') force_toolchain = kwargs.get('force_toolchain') force_platform = kwargs.get('force_platform') emu_filter = kwargs.get('emulation_only') logger.debug("platform filter: " + str(platform_filter)) logger.debug(" arch_filter: " + str(arch_filter)) logger.debug(" tag_filter: " + str(tag_filter)) logger.debug(" exclude_tag: " + str(exclude_tag)) default_platforms = False emulation_platforms = False if all_filter: logger.info("Selecting all possible platforms per test case") # When --all used, any --platform arguments ignored platform_filter = [] elif not platform_filter and not emu_filter: logger.info("Selecting default platforms per test case") default_platforms = True elif emu_filter: logger.info("Selecting emulation platforms per test case") emulation_platforms = True if platform_filter: platforms = list(filter(lambda p: p.name in platform_filter, self.platforms)) elif emu_filter: platforms = list(filter(lambda p: p.simulation != 'na', self.platforms)) elif arch_filter: platforms = list(filter(lambda p: p.arch in arch_filter, self.platforms)) elif default_platforms: platforms = list(filter(lambda p: p.default, self.platforms)) else: platforms = self.platforms logger.info("Building initial testcase list...") for tc_name, tc in self.testcases.items(): if tc.build_on_all and not platform_filter: platform_scope = self.platforms elif tc.integration_platforms and self.integration: platform_scope = list(filter(lambda item: item.name in tc.integration_platforms, \ self.platforms)) else: platform_scope = platforms integration = self.integration and tc.integration_platforms # If there isn't any overlap between the platform_allow list and the platform_scope # we set the scope to the platform_allow list if tc.platform_allow and not platform_filter and not integration: a = set(platform_scope) b = set(filter(lambda item: item.name in tc.platform_allow, self.platforms)) c = a.intersection(b) if not c: platform_scope = list(filter(lambda item: item.name in tc.platform_allow, \ self.platforms)) # list of instances per testcase, aka configurations. instance_list = [] for plat in platform_scope: instance = TestInstance(tc, plat, self.outdir) if runnable: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) for t in tc.cases: instance.results[t] = None if runnable and self.duts: for h in self.duts: if h.platform == plat.name: if tc.harness_config.get('fixture') in h.fixtures: instance.run = True if not force_platform and plat.name in exclude_platform: discards[instance] = discards.get(instance, "Platform is excluded on command line.") if (plat.arch == "unit") != (tc.type == "unit"): # Discard silently continue if runnable and not instance.run: discards[instance] = discards.get(instance, "Not runnable on device") if self.integration and tc.integration_platforms and plat.name not in tc.integration_platforms: discards[instance] = discards.get(instance, "Not part of integration platforms") if tc.skip: discards[instance] = discards.get(instance, "Skip filter") if tag_filter and not tc.tags.intersection(tag_filter): discards[instance] = discards.get(instance, "Command line testcase tag filter") if exclude_tag and tc.tags.intersection(exclude_tag): discards[instance] = discards.get(instance, "Command line testcase exclude filter") if testcase_filter and tc_name not in testcase_filter: discards[instance] = discards.get(instance, "Testcase name filter") if arch_filter and plat.arch not in arch_filter: discards[instance] = discards.get(instance, "Command line testcase arch filter") if not force_platform: if tc.arch_allow and plat.arch not in tc.arch_allow: discards[instance] = discards.get(instance, "Not in test case arch allow list") if tc.arch_exclude and plat.arch in tc.arch_exclude: discards[instance] = discards.get(instance, "In test case arch exclude") if tc.platform_exclude and plat.name in tc.platform_exclude: discards[instance] = discards.get(instance, "In test case platform exclude") if tc.toolchain_exclude and toolchain in tc.toolchain_exclude: discards[instance] = discards.get(instance, "In test case toolchain exclude") if platform_filter and plat.name not in platform_filter: discards[instance] = discards.get(instance, "Command line platform filter") if tc.platform_allow and plat.name not in tc.platform_allow: discards[instance] = discards.get(instance, "Not in testcase platform allow list") if tc.toolchain_allow and toolchain not in tc.toolchain_allow: discards[instance] = discards.get(instance, "Not in testcase toolchain allow list") if not plat.env_satisfied: discards[instance] = discards.get(instance, "Environment ({}) not satisfied".format(", ".join(plat.env))) if not force_toolchain \ and toolchain and (toolchain not in plat.supported_toolchains) \ and tc.type != 'unit': discards[instance] = discards.get(instance, "Not supported by the toolchain") if plat.ram < tc.min_ram: discards[instance] = discards.get(instance, "Not enough RAM") if tc.depends_on: dep_intersection = tc.depends_on.intersection(set(plat.supported)) if dep_intersection != set(tc.depends_on): discards[instance] = discards.get(instance, "No hardware support") if plat.flash < tc.min_flash: discards[instance] = discards.get(instance, "Not enough FLASH") if set(plat.ignore_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (exclude_tags)") if plat.only_tags and not set(plat.only_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (only_tags)") test_configuration = ".".join([instance.platform.name, instance.testcase.id]) # skip quarantined tests if test_configuration in self.quarantine and not self.quarantine_verify: discards[instance] = discards.get(instance, f"Quarantine: {self.quarantine[test_configuration]}") # run only quarantined test to verify their statuses (skip everything else) if self.quarantine_verify and test_configuration not in self.quarantine: discards[instance] = discards.get(instance, "Not under quarantine") # if nothing stopped us until now, it means this configuration # needs to be added. instance_list.append(instance) # no configurations, so jump to next testcase if not instance_list: continue # if twister was launched with no platform options at all, we # take all default platforms if default_platforms and not tc.build_on_all and not integration: if tc.platform_allow: a = set(self.default_platforms) b = set(tc.platform_allow) c = a.intersection(b) if c: aa = list(filter(lambda tc: tc.platform.name in c, instance_list)) self.add_instances(aa) else: self.add_instances(instance_list) else: instances = list(filter(lambda tc: tc.platform.default, instance_list)) self.add_instances(instances) elif integration: instances = list(filter(lambda item: item.platform.name in tc.integration_platforms, instance_list)) self.add_instances(instances) elif emulation_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.simulation != 'na', instance_list)): discards[instance] = discards.get(instance, "Not an emulated platform") else: self.add_instances(instance_list) for _, case in self.instances.items(): case.create_overlay(case.platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) self.discards = discards self.selected_platforms = set(p.platform.name for p in self.instances.values()) for instance in self.discards: instance.reason = self.discards[instance] # If integration mode is on all skips on integration_platforms are treated as errors. # TODO: add quarantine relief here when PR with quarantine feature gets merged if self.integration and instance.platform.name in instance.testcase.integration_platforms: instance.status = "error" instance.reason += " but is one of the integration platforms" instance.fill_results_by_status() self.instances[instance.name] = instance else: instance.status = "skipped" instance.fill_results_by_status() self.filtered_platforms = set(p.platform.name for p in self.instances.values() if p.status != "skipped" ) return discards def add_instances(self, instance_list): for instance in instance_list: self.instances[instance.name] = instance @staticmethod def calc_one_elf_size(instance): if instance.status not in ["error", "failed", "skipped"]: if instance.platform.type != "native": size_calc = instance.calculate_sizes() instance.metrics["ram_size"] = size_calc.get_ram_size() instance.metrics["rom_size"] = size_calc.get_rom_size() instance.metrics["unrecognized"] = size_calc.unrecognized_sections() else: instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["unrecognized"] = [] instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 def add_tasks_to_queue(self, pipeline, build_only=False, test_only=False): for instance in self.instances.values(): if build_only: instance.run = False if test_only and instance.run: pipeline.put({"op": "run", "test": instance}) else: if instance.status not in ['passed', 'skipped', 'error']: logger.debug(f"adding {instance.name}") instance.status = None pipeline.put({"op": "cmake", "test": instance}) # If the instance got 'error' status before, proceed to the report stage if instance.status == "error": pipeline.put({"op": "report", "test": instance}) def pipeline_mgr(self, pipeline, done_queue, lock, results): while True: try: task = pipeline.get_nowait() except queue.Empty: break else: test = task['test'] pb = ProjectBuilder(self, test, lsan=self.enable_lsan, asan=self.enable_asan, ubsan=self.enable_ubsan, coverage=self.enable_coverage, extra_args=self.extra_args, device_testing=self.device_testing, cmake_only=self.cmake_only, cleanup=self.cleanup, valgrind=self.enable_valgrind, inline_logs=self.inline_logs, generator=self.generator, generator_cmd=self.generator_cmd, verbose=self.verbose, warnings_as_errors=self.warnings_as_errors, overflow_as_errors=self.overflow_as_errors ) pb.process(pipeline, done_queue, task, lock, results) return True def execute(self, pipeline, done, results): lock = Lock() logger.info("Adding tasks to the queue...") self.add_tasks_to_queue(pipeline, self.build_only, self.test_only) logger.info("Added initial list of jobs to queue") processes = [] for job in range(self.jobs): logger.debug(f"Launch process {job}") p = Process(target=self.pipeline_mgr, args=(pipeline, done, lock, results, )) processes.append(p) p.start() try: for p in processes: p.join() except KeyboardInterrupt: logger.info("Execution interrupted") for p in processes: p.terminate() # FIXME: This needs to move out. if self.enable_size_report and not self.cmake_only: # Parallelize size calculation executor = concurrent.futures.ThreadPoolExecutor(self.jobs) futures = [executor.submit(self.calc_one_elf_size, instance) for instance in self.instances.values()] concurrent.futures.wait(futures) else: for instance in self.instances.values(): instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 instance.metrics["unrecognized"] = [] return results def discard_report(self, filename): try: if not self.discards: raise TwisterRuntimeError("apply_filters() hasn't been run!") except Exception as e: logger.error(str(e)) sys.exit(2) with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "reason"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance, reason in sorted(self.discards.items()): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "reason": reason} cw.writerow(rowdict) def target_report(self, outdir, suffix, append=False): platforms = {inst.platform.name for _, inst in self.instances.items()} for platform in platforms: if suffix: filename = os.path.join(outdir,"{}_{}.xml".format(platform, suffix)) else: filename = os.path.join(outdir,"{}.xml".format(platform)) self.xunit_report(filename, platform, full_report=True, append=append, version=self.version) @staticmethod def process_log(log_file): filtered_string = "" if os.path.exists(log_file): with open(log_file, "rb") as f: log = f.read().decode("utf-8") filtered_string = ''.join(filter(lambda x: x in string.printable, log)) return filtered_string def xunit_report(self, filename, platform=None, full_report=False, append=False, version="NA"): total = 0 fails = passes = errors = skips = 0 if platform: selected = [platform] logger.info(f"Writing target report for {platform}...") else: logger.info(f"Writing xunit report {filename}...") selected = self.selected_platforms if os.path.exists(filename) and append: tree = ET.parse(filename) eleTestsuites = tree.getroot() else: eleTestsuites = ET.Element('testsuites') for p in selected: inst = self.get_platform_instances(p) fails = 0 passes = 0 errors = 0 skips = 0 duration = 0 for _, instance in inst.items(): handler_time = instance.metrics.get('handler_time', 0) duration += handler_time if full_report and instance.run: for k in instance.results.keys(): if instance.results[k] == 'PASS': passes += 1 elif instance.results[k] == 'BLOCK': errors += 1 elif instance.results[k] == 'SKIP' or instance.status in ['skipped']: skips += 1 else: fails += 1 else: if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.reason in ['build_error', 'handler_crash']: errors += 1 else: fails += 1 elif instance.status == 'skipped': skips += 1 elif instance.status == 'passed': passes += 1 else: if instance.status: logger.error(f"{instance.name}: Unknown status {instance.status}") else: logger.error(f"{instance.name}: No status") total = (errors + passes + fails + skips) # do not produce a report if no tests were actually run (only built) if total == 0: continue run = p eleTestsuite = None # When we re-run the tests, we re-use the results and update only with # the newly run tests. if os.path.exists(filename) and append: ts = eleTestsuites.findall(f'testsuite/[@name="{p}"]') if ts: eleTestsuite = ts[0] eleTestsuite.attrib['failures'] = "%d" % fails eleTestsuite.attrib['errors'] = "%d" % errors eleTestsuite.attrib['skipped'] = "%d" % skips else: logger.info(f"Did not find any existing results for {p}") eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) else: eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) for _, instance in inst.items(): if full_report: tname = os.path.basename(instance.testcase.name) else: tname = instance.testcase.id handler_time = instance.metrics.get('handler_time', 0) if full_report: for k in instance.results.keys(): # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@name="{k}"]'): eleTestsuite.remove(tc) classname = ".".join(tname.split(".")[:2]) eleTestcase = ET.SubElement( eleTestsuite, 'testcase', classname=classname, name="%s" % (k), time="%f" % handler_time) if instance.results[k] in ['FAIL', 'BLOCK'] or \ (not instance.run and instance.status in ["error", "failed", "timeout"]): if instance.results[k] == 'FAIL': el = ET.SubElement( eleTestcase, 'failure', type="failure", message="failed") else: el = ET.SubElement( eleTestcase, 'error', type="failure", message=instance.reason) log_root = os.path.join(self.outdir, instance.platform.name, instance.testcase.name) log_file = os.path.join(log_root, "handler.log") el.text = self.process_log(log_file) elif instance.results[k] == 'PASS' \ or (not instance.run and instance.status in ["passed"]): pass elif instance.results[k] == 'SKIP' or (instance.status in ["skipped"]): el = ET.SubElement(eleTestcase, 'skipped', type="skipped", message=instance.reason) else: el = ET.SubElement( eleTestcase, 'error', type="error", message=f"{instance.reason}") else: if platform: classname = ".".join(instance.testcase.name.split(".")[:2]) else: classname = p + ":" + ".".join(instance.testcase.name.split(".")[:2]) # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@classname="{classname}"][@name="{instance.testcase.name}"]'): eleTestsuite.remove(tc) eleTestcase = ET.SubElement(eleTestsuite, 'testcase', classname=classname, name="%s" % (instance.testcase.name), time="%f" % handler_time) if instance.status in ["error", "failed", "timeout", "flash_error"]: failure = ET.SubElement( eleTestcase, 'failure', type="failure", message=instance.reason) log_root = ("%s/%s/%s" % (self.outdir, instance.platform.name, instance.testcase.name)) bl = os.path.join(log_root, "build.log") hl = os.path.join(log_root, "handler.log") log_file = bl if instance.reason != 'Build error': if os.path.exists(hl): log_file = hl else: log_file = bl failure.text = self.process_log(log_file) elif instance.status == "skipped": ET.SubElement(eleTestcase, 'skipped', type="skipped", message="Skipped") result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) return fails, passes, errors, skips def csv_report(self, filename): with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "status", "extra_args", "handler", "handler_time", "ram_size", "rom_size"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance in self.instances.values(): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "extra_args": " ".join(instance.testcase.extra_args), "handler": instance.platform.simulation} rowdict["status"] = instance.status if instance.status not in ["error", "failed", "timeout"]: if instance.handler: rowdict["handler_time"] = instance.metrics.get("handler_time", 0) ram_size = instance.metrics.get("ram_size", 0) rom_size = instance.metrics.get("rom_size", 0) rowdict["ram_size"] = ram_size rowdict["rom_size"] = rom_size cw.writerow(rowdict) def json_report(self, filename, append=False, version="NA"): logger.info(f"Writing JSON report {filename}") report = {} selected = self.selected_platforms report["environment"] = {"os": os.name, "zephyr_version": version, "toolchain": self.get_toolchain() } json_data = {} if os.path.exists(filename) and append: with open(filename, 'r') as json_file: json_data = json.load(json_file) suites = json_data.get("testsuites", []) if suites: suite = suites[0] testcases = suite.get("testcases", []) else: suite = {} testcases = [] for p in selected: inst = self.get_platform_instances(p) for _, instance in inst.items(): testcase = {} handler_log = os.path.join(instance.build_dir, "handler.log") build_log = os.path.join(instance.build_dir, "build.log") device_log = os.path.join(instance.build_dir, "device.log") handler_time = instance.metrics.get('handler_time', 0) ram_size = instance.metrics.get ("ram_size", 0) rom_size = instance.metrics.get("rom_size",0) for k in instance.results.keys(): testcases = list(filter(lambda d: not (d.get('testcase') == k and d.get('platform') == p), testcases )) testcase = {"testcase": k, "arch": instance.platform.arch, "platform": p, } if ram_size: testcase["ram_size"] = ram_size if rom_size: testcase["rom_size"] = rom_size if instance.results[k] in ["PASS"]: testcase["status"] = "passed" if instance.handler: testcase["execution_time"] = handler_time elif instance.results[k] in ['FAIL', 'BLOCK'] or instance.status in ["error", "failed", "timeout"]: testcase["status"] = "failed" testcase["reason"] = instance.reason testcase["execution_time"] = handler_time if os.path.exists(handler_log): testcase["test_output"] = self.process_log(handler_log) elif os.path.exists(device_log): testcase["device_log"] = self.process_log(device_log) else: testcase["build_log"] = self.process_log(build_log) else: testcase["status"] = "skipped" testcase["reason"] = instance.reason testcases.append(testcase) suites = [ {"testcases": testcases} ] report["testsuites"] = suites with open(filename, "wt") as json_file: json.dump(report, json_file, indent=4, separators=(',',':')) def get_testcase(self, identifier): results = [] for _, tc in self.testcases.items(): for case in tc.cases: if case == identifier: results.append(tc) return results class CoverageTool: """ Base class for every supported coverage tool """ def __init__(self): self.gcov_tool = None self.base_dir = None @staticmethod def factory(tool): if tool == 'lcov': t = Lcov() elif tool == 'gcovr': t = Gcovr() else: logger.error("Unsupported coverage tool specified: {}".format(tool)) return None logger.debug(f"Select {tool} as the coverage tool...") return t @staticmethod def retrieve_gcov_data(intput_file): logger.debug("Working on %s" % intput_file) extracted_coverage_info = {} capture_data = False capture_complete = False with open(intput_file, 'r') as fp: for line in fp.readlines(): if re.search("GCOV_COVERAGE_DUMP_START", line): capture_data = True continue if re.search("GCOV_COVERAGE_DUMP_END", line): capture_complete = True break # Loop until the coverage data is found. if not capture_data: continue if line.startswith("*"): sp = line.split("<") if len(sp) > 1: # Remove the leading delimiter "*" file_name = sp[0][1:] # Remove the trailing new line char hex_dump = sp[1][:-1] else: continue else: continue extracted_coverage_info.update({file_name: hex_dump}) if not capture_data: capture_complete = True return {'complete': capture_complete, 'data': extracted_coverage_info} @staticmethod def create_gcda_files(extracted_coverage_info): logger.debug("Generating gcda files") for filename, hexdump_val in extracted_coverage_info.items(): # if kobject_hash is given for coverage gcovr fails # hence skipping it problem only in gcovr v4.1 if "kobject_hash" in filename: filename = (filename[:-4]) + "gcno" try: os.remove(filename) except Exception: pass continue with open(filename, 'wb') as fp: fp.write(bytes.fromhex(hexdump_val)) def generate(self, outdir): for filename in glob.glob("%s/**/handler.log" % outdir, recursive=True): gcov_data = self.__class__.retrieve_gcov_data(filename) capture_complete = gcov_data['complete'] extracted_coverage_info = gcov_data['data'] if capture_complete: self.__class__.create_gcda_files(extracted_coverage_info) logger.debug("Gcov data captured: {}".format(filename)) else: logger.error("Gcov data capture incomplete: {}".format(filename)) with open(os.path.join(outdir, "coverage.log"), "a") as coveragelog: ret = self._generate(outdir, coveragelog) if ret == 0: logger.info("HTML report generated: {}".format( os.path.join(outdir, "coverage", "index.html"))) class Lcov(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('*' + pattern + '*') def add_ignore_directory(self, pattern): self.ignores.append('*/' + pattern + '/*') def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.info") ztestfile = os.path.join(outdir, "ztest.info") cmd = ["lcov", "--gcov-tool", self.gcov_tool, "--capture", "--directory", outdir, "--rc", "lcov_branch_coverage=1", "--output-file", coveragefile] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--extract", coveragefile, os.path.join(self.base_dir, "tests", "ztest", "*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--remove", ztestfile, os.path.join(self.base_dir, "tests/ztest/test/*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) files = [coveragefile, ztestfile] else: files = [coveragefile] for i in self.ignores: subprocess.call( ["lcov", "--gcov-tool", self.gcov_tool, "--remove", coveragefile, i, "--output-file", coveragefile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) # The --ignore-errors source option is added to avoid it exiting due to # samples/application_development/external_lib/ return subprocess.call(["genhtml", "--legend", "--branch-coverage", "--ignore-errors", "source", "-output-directory", os.path.join(outdir, "coverage")] + files, stdout=coveragelog) class Gcovr(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('.*' + pattern + '.*') def add_ignore_directory(self, pattern): self.ignores.append(".*/" + pattern + '/.*') @staticmethod def _interleave_list(prefix, list): tuple_list = [(prefix, item) for item in list] return [item for sublist in tuple_list for item in sublist] def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.json") ztestfile = os.path.join(outdir, "ztest.json") excludes = Gcovr._interleave_list("-e", self.ignores) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-e", "tests/*"] + excludes + ["--json", "-o", coveragefile, outdir] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) subprocess.call(["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-f", "tests/ztest", "-e", "tests/ztest/test/*", "--json", "-o", ztestfile, outdir], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: files = [coveragefile, ztestfile] else: files = [coveragefile] subdir = os.path.join(outdir, "coverage") os.makedirs(subdir, exist_ok=True) tracefiles = self._interleave_list("--add-tracefile", files) return subprocess.call(["gcovr", "-r", self.base_dir, "--html", "--html-details"] + tracefiles + ["-o", os.path.join(subdir, "index.html")], stdout=coveragelog) class DUT(object): def __init__(self, id=None, serial=None, platform=None, product=None, serial_pty=None, connected=False, pre_script=None, post_script=None, post_flash_script=None, runner=None): self.serial = serial self.platform = platform self.serial_pty = serial_pty self._counter = Value("i", 0) self._available = Value("i", 1) self.connected = connected self.pre_script = pre_script self.id = id self.product = product self.runner = runner self.fixtures = [] self.post_flash_script = post_flash_script self.post_script = post_script self.pre_script = pre_script self.probe_id = None self.notes = None self.lock = Lock() self.match = False @property def available(self): with self._available.get_lock(): return self._available.value @available.setter def available(self, value): with self._available.get_lock(): self._available.value = value @property def counter(self): with self._counter.get_lock(): return self._counter.value @counter.setter def counter(self, value): with self._counter.get_lock(): self._counter.value = value def to_dict(self): d = {} exclude = ['_available', '_counter', 'match'] v = vars(self) for k in v.keys(): if k not in exclude and v[k]: d[k] = v[k] return d def __repr__(self): return f"<{self.platform} ({self.product}) on {self.serial}>" class HardwareMap: schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "hwmap-schema.yaml") manufacturer = [ 'ARM', 'SEGGER', 'MBED', 'STMicroelectronics', 'Atmel Corp.', 'Texas Instruments', 'Silicon Labs', 'NXP Semiconductors', 'Microchip Technology Inc.', 'FTDI', 'Digilent' ] runner_mapping = { 'pyocd': [ 'DAPLink CMSIS-DAP', 'MBED CMSIS-DAP' ], 'jlink': [ 'J-Link', 'J-Link OB' ], 'openocd': [ 'STM32 STLink', '^XDS110.*', 'STLINK-V3' ], 'dediprog': [ 'TTL232R-3V3', 'MCP2200 USB Serial Port Emulator' ] } def __init__(self): self.detected = [] self.duts = [] def add_device(self, serial, platform, pre_script, is_pty): device = DUT(platform=platform, connected=True, pre_script=pre_script) if is_pty: device.serial_pty = serial else: device.serial = serial self.duts.append(device) def load(self, map_file): hwm_schema = scl.yaml_load(self.schema_path) duts = scl.yaml_load_verify(map_file, hwm_schema) for dut in duts: pre_script = dut.get('pre_script') post_script = dut.get('post_script') post_flash_script = dut.get('post_flash_script') platform = dut.get('platform') id = dut.get('id') runner = dut.get('runner') serial = dut.get('serial') product = dut.get('product') fixtures = dut.get('fixtures', []) new_dut = DUT(platform=platform, product=product, runner=runner, id=id, serial=serial, connected=serial is not None, pre_script=pre_script, post_script=post_script, post_flash_script=post_flash_script) new_dut.fixtures = fixtures new_dut.counter = 0 self.duts.append(new_dut) def scan(self, persistent=False): from serial.tools import list_ports if persistent and platform.system() == 'Linux': # On Linux, /dev/serial/by-id provides symlinks to # '/dev/ttyACMx' nodes using names which are unique as # long as manufacturers fill out USB metadata nicely. # # This creates a map from '/dev/ttyACMx' device nodes # to '/dev/serial/by-id/usb-...' symlinks. The symlinks # go into the hardware map because they stay the same # even when the user unplugs / replugs the device. # # Some inexpensive USB/serial adapters don't result # in unique names here, though, so use of this feature # requires explicitly setting persistent=True. by_id = Path('/dev/serial/by-id') def readlink(link): return str((by_id / link).resolve()) persistent_map = {readlink(link): str(link) for link in by_id.iterdir()} else: persistent_map = {} serial_devices = list_ports.comports() logger.info("Scanning connected hardware...") for d in serial_devices: if d.manufacturer in self.manufacturer: # TI XDS110 can have multiple serial devices for a single board # assume endpoint 0 is the serial, skip all others if d.manufacturer == 'Texas Instruments' and not d.location.endswith('0'): continue s_dev = DUT(platform="unknown", id=d.serial_number, serial=persistent_map.get(d.device, d.device), product=d.product, runner='unknown') for runner, _ in self.runner_mapping.items(): products = self.runner_mapping.get(runner) if d.product in products: s_dev.runner = runner continue # Try regex matching for p in products: if re.match(p, d.product): s_dev.runner = runner s_dev.connected = True self.detected.append(s_dev) else: logger.warning("Unsupported device (%s): %s" % (d.manufacturer, d)) def save(self, hwm_file): # use existing map self.detected.sort(key=lambda x: x.serial or '') if os.path.exists(hwm_file): with open(hwm_file, 'r') as yaml_file: hwm = yaml.load(yaml_file, Loader=SafeLoader) if hwm: hwm.sort(key=lambda x: x['serial'] or '') # disconnect everything for h in hwm: h['connected'] = False h['serial'] = None for _detected in self.detected: for h in hwm: if _detected.id == h['id'] and _detected.product == h['product'] and not _detected.match: h['connected'] = True h['serial'] = _detected.serial _detected.match = True new_duts = list(filter(lambda d: not d.match, self.detected)) new = [] for d in new_duts: new.append(d.to_dict()) if hwm: hwm = hwm + new else: hwm = new with open(hwm_file, 'w') as yaml_file: yaml.dump(hwm, yaml_file, Dumper=Dumper, default_flow_style=False) self.load(hwm_file) logger.info("Registered devices:") self.dump() else: # create new file dl = [] for _connected in self.detected: platform = _connected.platform id = _connected.id runner = _connected.runner serial = _connected.serial product = _connected.product d = { 'platform': platform, 'id': id, 'runner': runner, 'serial': serial, 'product': product } dl.append(d) with open(hwm_file, 'w') as yaml_file: yaml.dump(dl, yaml_file, Dumper=Dumper, default_flow_style=False) logger.info("Detected devices:") self.dump(detected=True) def dump(self, filtered=[], header=[], connected_only=False, detected=False): print("") table = [] if detected: to_show = self.detected else: to_show = self.duts if not header: header = ["Platform", "ID", "Serial device"] for p in to_show: platform = p.platform connected = p.connected if filtered and platform not in filtered: continue if not connected_only or connected: table.append([platform, p.id, p.serial]) print(tabulate(table, headers=header, tablefmt="github")) twister: Add ICCM/DCCM to list of overflow regions On ARC some platforms utilize ICCM/DCCM for their "flash" and "ram" storage. So we might get errors about overflowing one of these regions. So treat them similar to how we treat FLASH and SRAM. Signed-off-by: Kumar Gala <a5e5248af4cd4f0ed8c515f61d40a6e2db46a66e@linaro.org> #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # # Copyright (c) 2018 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import contextlib import string import mmap import sys import re import subprocess import select import shutil import shlex import signal import threading import concurrent.futures from collections import OrderedDict import queue import time import csv import glob import concurrent import xml.etree.ElementTree as ET import logging import pty from pathlib import Path from distutils.spawn import find_executable from colorama import Fore import pickle import platform import yaml import json from multiprocessing import Lock, Process, Value try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import SafeLoader, Dumper try: import serial except ImportError: print("Install pyserial python module with pip to use --device-testing option.") try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") try: import psutil except ImportError: print("Install psutil python module with pip to run in Qemu.") ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") # This is needed to load edt.pickle files. sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts", "python-devicetree", "src")) from devicetree import edtlib # pylint: disable=unused-import # Use this for internal comparisons; that's what canonicalization is # for. Don't use it when invoking other components of the build system # to avoid confusing and hard to trace inconsistencies in error messages # and logs, generated Makefiles, etc. compared to when users invoke these # components directly. # Note "normalization" is different from canonicalization, see os.path. canonical_zephyr_base = os.path.realpath(ZEPHYR_BASE) sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import scl import expr_parser logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ExecutionCounter(object): def __init__(self, total=0): self._done = Value('i', 0) self._passed = Value('i', 0) self._skipped_configs = Value('i', 0) self._skipped_runtime = Value('i', 0) self._skipped_cases = Value('i', 0) self._error = Value('i', 0) self._failed = Value('i', 0) self._total = Value('i', total) self._cases = Value('i', 0) self.lock = Lock() @property def cases(self): with self._cases.get_lock(): return self._cases.value @cases.setter def cases(self, value): with self._cases.get_lock(): self._cases.value = value @property def skipped_cases(self): with self._skipped_cases.get_lock(): return self._skipped_cases.value @skipped_cases.setter def skipped_cases(self, value): with self._skipped_cases.get_lock(): self._skipped_cases.value = value @property def error(self): with self._error.get_lock(): return self._error.value @error.setter def error(self, value): with self._error.get_lock(): self._error.value = value @property def done(self): with self._done.get_lock(): return self._done.value @done.setter def done(self, value): with self._done.get_lock(): self._done.value = value @property def passed(self): with self._passed.get_lock(): return self._passed.value @passed.setter def passed(self, value): with self._passed.get_lock(): self._passed.value = value @property def skipped_configs(self): with self._skipped_configs.get_lock(): return self._skipped_configs.value @skipped_configs.setter def skipped_configs(self, value): with self._skipped_configs.get_lock(): self._skipped_configs.value = value @property def skipped_runtime(self): with self._skipped_runtime.get_lock(): return self._skipped_runtime.value @skipped_runtime.setter def skipped_runtime(self, value): with self._skipped_runtime.get_lock(): self._skipped_runtime.value = value @property def failed(self): with self._failed.get_lock(): return self._failed.value @failed.setter def failed(self, value): with self._failed.get_lock(): self._failed.value = value @property def total(self): with self._total.get_lock(): return self._total.value class CMakeCacheEntry: '''Represents a CMake cache entry. This class understands the type system in a CMakeCache.txt, and converts the following cache types to Python types: Cache Type Python type ---------- ------------------------------------------- FILEPATH str PATH str STRING str OR list of str (if ';' is in the value) BOOL bool INTERNAL str OR list of str (if ';' is in the value) ---------- ------------------------------------------- ''' # Regular expression for a cache entry. # # CMake variable names can include escape characters, allowing a # wider set of names than is easy to match with a regular # expression. To be permissive here, use a non-greedy match up to # the first colon (':'). This breaks if the variable name has a # colon inside, but it's good enough. CACHE_ENTRY = re.compile( r'''(?P<name>.*?) # name :(?P<type>FILEPATH|PATH|STRING|BOOL|INTERNAL) # type =(?P<value>.*) # value ''', re.X) @classmethod def _to_bool(cls, val): # Convert a CMake BOOL string into a Python bool. # # "True if the constant is 1, ON, YES, TRUE, Y, or a # non-zero number. False if the constant is 0, OFF, NO, # FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in # the suffix -NOTFOUND. Named boolean constants are # case-insensitive. If the argument is not one of these # constants, it is treated as a variable." # # https://cmake.org/cmake/help/v3.0/command/if.html val = val.upper() if val in ('ON', 'YES', 'TRUE', 'Y'): return 1 elif val in ('OFF', 'NO', 'FALSE', 'N', 'IGNORE', 'NOTFOUND', ''): return 0 elif val.endswith('-NOTFOUND'): return 0 else: try: v = int(val) return v != 0 except ValueError as exc: raise ValueError('invalid bool {}'.format(val)) from exc @classmethod def from_line(cls, line, line_no): # Comments can only occur at the beginning of a line. # (The value of an entry could contain a comment character). if line.startswith('//') or line.startswith('#'): return None # Whitespace-only lines do not contain cache entries. if not line.strip(): return None m = cls.CACHE_ENTRY.match(line) if not m: return None name, type_, value = (m.group(g) for g in ('name', 'type', 'value')) if type_ == 'BOOL': try: value = cls._to_bool(value) except ValueError as exc: args = exc.args + ('on line {}: {}'.format(line_no, line),) raise ValueError(args) from exc elif type_ in ['STRING', 'INTERNAL']: # If the value is a CMake list (i.e. is a string which # contains a ';'), convert to a Python list. if ';' in value: value = value.split(';') return CMakeCacheEntry(name, value) def __init__(self, name, value): self.name = name self.value = value def __str__(self): fmt = 'CMakeCacheEntry(name={}, value={})' return fmt.format(self.name, self.value) class CMakeCache: '''Parses and represents a CMake cache file.''' @staticmethod def from_file(cache_file): return CMakeCache(cache_file) def __init__(self, cache_file): self.cache_file = cache_file self.load(cache_file) def load(self, cache_file): entries = [] with open(cache_file, 'r') as cache: for line_no, line in enumerate(cache): entry = CMakeCacheEntry.from_line(line, line_no) if entry: entries.append(entry) self._entries = OrderedDict((e.name, e) for e in entries) def get(self, name, default=None): entry = self._entries.get(name) if entry is not None: return entry.value else: return default def get_list(self, name, default=None): if default is None: default = [] entry = self._entries.get(name) if entry is not None: value = entry.value if isinstance(value, list): return value elif isinstance(value, str): return [value] if value else [] else: msg = 'invalid value {} type {}' raise RuntimeError(msg.format(value, type(value))) else: return default def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name].value def __setitem__(self, name, entry): if not isinstance(entry, CMakeCacheEntry): msg = 'improper type {} for value {}, expecting CMakeCacheEntry' raise TypeError(msg.format(type(entry), entry)) self._entries[name] = entry def __delitem__(self, name): del self._entries[name] def __iter__(self): return iter(self._entries.values()) class TwisterException(Exception): pass class TwisterRuntimeError(TwisterException): pass class ConfigurationError(TwisterException): def __init__(self, cfile, message): TwisterException.__init__(self, cfile + ": " + message) class BuildError(TwisterException): pass class ExecutionError(TwisterException): pass class HarnessImporter: def __init__(self, name): sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister")) module = __import__("harness") if name: my_class = getattr(module, name) else: my_class = getattr(module, "Test") self.instance = my_class() class Handler: def __init__(self, instance, type_str="build"): """Constructor """ self.state = "waiting" self.run = False self.duration = 0 self.type_str = type_str self.binary = None self.pid_fn = None self.call_make_run = False self.name = instance.name self.instance = instance self.timeout = instance.testcase.timeout self.sourcedir = instance.testcase.source_dir self.build_dir = instance.build_dir self.log = os.path.join(self.build_dir, "handler.log") self.returncode = 0 self.set_state("running", self.duration) self.generator = None self.generator_cmd = None self.args = [] def set_state(self, state, duration): self.state = state self.duration = duration def get_state(self): ret = (self.state, self.duration) return ret def record(self, harness): if harness.recording: filename = os.path.join(self.build_dir, "recording.csv") with open(filename, "at") as csvfile: cw = csv.writer(csvfile, harness.fieldnames, lineterminator=os.linesep) cw.writerow(harness.fieldnames) for instance in harness.recording: cw.writerow(instance) class BinaryHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.terminated = False self.call_west_flash = False # Tool options self.valgrind = False self.lsan = False self.asan = False self.ubsan = False self.coverage = False def try_kill_process_by_pid(self): if self.pid_fn: pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) self.pid_fn = None # clear so we don't try to kill the binary twice try: os.kill(pid, signal.SIGTERM) except ProcessLookupError: pass def terminate(self, proc): # encapsulate terminate functionality so we do it consistently where ever # we might want to terminate the proc. We need try_kill_process_by_pid # because of both how newer ninja (1.6.0 or greater) and .NET / renode # work. Newer ninja's don't seem to pass SIGTERM down to the children # so we need to use try_kill_process_by_pid. for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except ProcessLookupError: pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() self.terminated = True def _output_reader(self, proc): self.line = proc.stdout.readline() def _output_handler(self, proc, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") timeout_extended = False timeout_time = time.time() + self.timeout while True: this_timeout = timeout_time - time.time() if this_timeout < 0: break reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(this_timeout) if not reader_t.is_alive(): line = self.line logger.debug("OUTPUT: {0}".format(line.decode('utf-8').rstrip())) log_out_fp.write(line.decode('utf-8')) log_out_fp.flush() harness.handle(line.decode('utf-8').rstrip()) if harness.state: if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 else: reader_t.join(0) break try: # POSIX arch based ztests end on their own, # so let's give it up to 100ms to do so proc.wait(0.1) except subprocess.TimeoutExpired: self.terminate(proc) log_out_fp.close() def handle(self): harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) if self.call_make_run: command = [self.generator_cmd, "run"] elif self.call_west_flash: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] else: command = [self.binary] run_valgrind = False if self.valgrind and shutil.which("valgrind"): command = ["valgrind", "--error-exitcode=2", "--leak-check=full", "--suppressions=" + ZEPHYR_BASE + "/scripts/valgrind.supp", "--log-file=" + self.build_dir + "/valgrind.log" ] + command run_valgrind = True logger.debug("Spawning process: " + " ".join(shlex.quote(word) for word in command) + os.linesep + "in directory: " + self.build_dir) start_time = time.time() env = os.environ.copy() if self.asan: env["ASAN_OPTIONS"] = "log_path=stdout:" + \ env.get("ASAN_OPTIONS", "") if not self.lsan: env["ASAN_OPTIONS"] += "detect_leaks=0" if self.ubsan: env["UBSAN_OPTIONS"] = "log_path=stdout:halt_on_error=1:" + \ env.get("UBSAN_OPTIONS", "") with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir, env=env) as proc: logger.debug("Spawning BinaryHandler Thread for %s" % self.name) t = threading.Thread(target=self._output_handler, args=(proc, harness,), daemon=True) t.start() t.join() if t.is_alive(): self.terminate(proc) t.join() proc.wait() self.returncode = proc.returncode self.try_kill_process_by_pid() handler_time = time.time() - start_time if self.coverage: subprocess.call(["GCOV_PREFIX=" + self.build_dir, "gcov", self.sourcedir, "-b", "-s", self.build_dir], shell=True) # FIXME: This is needed when killing the simulator, the console is # garbled and needs to be reset. Did not find a better way to do that. if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests if not self.terminated and self.returncode != 0: # When a process is killed, the default handler returns 128 + SIGTERM # so in that case the return code itself is not meaningful self.set_state("failed", handler_time) self.instance.reason = "Failed" elif run_valgrind and self.returncode == 2: self.set_state("failed", handler_time) self.instance.reason = "Valgrind error" elif harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state("timeout", handler_time) self.instance.reason = "Timeout" self.record(harness) class DeviceHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.suite = None def monitor_serial(self, ser, halt_fileno, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") ser_fileno = ser.fileno() readlist = [halt_fileno, ser_fileno] if self.coverage: # Set capture_coverage to True to indicate that right after # test results we should get coverage data, otherwise we exit # from the test. harness.capture_coverage = True ser.flush() while ser.isOpen(): readable, _, _ = select.select(readlist, [], [], self.timeout) if halt_fileno in readable: logger.debug('halted') ser.close() break if ser_fileno not in readable: continue # Timeout. serial_line = None try: serial_line = ser.readline() except TypeError: pass except serial.SerialException: ser.close() break # Just because ser_fileno has data doesn't mean an entire line # is available yet. if serial_line: sl = serial_line.decode('utf-8', 'ignore').lstrip() logger.debug("DEVICE: {0}".format(sl.rstrip())) log_out_fp.write(sl) log_out_fp.flush() harness.handle(sl.rstrip()) if harness.state: if not harness.capture_coverage: ser.close() break log_out_fp.close() def device_is_available(self, instance): device = instance.platform.name fixture = instance.testcase.harness_config.get("fixture") for d in self.suite.duts: if fixture and fixture not in d.fixtures: continue if d.platform != device or not (d.serial or d.serial_pty): continue d.lock.acquire() avail = False if d.available: d.available = 0 d.counter += 1 avail = True d.lock.release() if avail: return d return None def make_device_available(self, serial): for d in self.suite.duts: if d.serial == serial or d.serial_pty: d.available = 1 @staticmethod def run_custom_script(script, timeout): with subprocess.Popen(script, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, _ = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) except subprocess.TimeoutExpired: proc.kill() proc.communicate() logger.error("{} timed out".format(script)) def handle(self): out_state = "failed" runner = None hardware = self.device_is_available(self.instance) while not hardware: logger.debug("Waiting for device {} to become available".format(self.instance.platform.name)) time.sleep(1) hardware = self.device_is_available(self.instance) runner = hardware.runner or self.suite.west_runner serial_pty = hardware.serial_pty ser_pty_process = None if serial_pty: master, slave = pty.openpty() try: ser_pty_process = subprocess.Popen(re.split(',| ', serial_pty), stdout=master, stdin=master, stderr=master) except subprocess.CalledProcessError as error: logger.error("Failed to run subprocess {}, error {}".format(serial_pty, error.output)) return serial_device = os.ttyname(slave) else: serial_device = hardware.serial logger.debug("Using serial device {}".format(serial_device)) if (self.suite.west_flash is not None) or runner: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] command_extra_args = [] # There are three ways this option is used. # 1) bare: --west-flash # This results in options.west_flash == [] # 2) with a value: --west-flash="--board-id=42" # This results in options.west_flash == "--board-id=42" # 3) Multiple values: --west-flash="--board-id=42,--erase" # This results in options.west_flash == "--board-id=42 --erase" if self.suite.west_flash and self.suite.west_flash != []: command_extra_args.extend(self.suite.west_flash.split(',')) if runner: command.append("--runner") command.append(runner) board_id = hardware.probe_id or hardware.id product = hardware.product if board_id is not None: if runner == "pyocd": command_extra_args.append("--board-id") command_extra_args.append(board_id) elif runner == "nrfjprog": command_extra_args.append("--snr") command_extra_args.append(board_id) elif runner == "openocd" and product == "STM32 STLink": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "STLINK-V3": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "EDBG CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("cmsis_dap_serial %s" % (board_id)) elif runner == "jlink": command.append("--tool-opt=-SelectEmuBySN %s" % (board_id)) if command_extra_args != []: command.append('--') command.extend(command_extra_args) else: command = [self.generator_cmd, "-C", self.build_dir, "flash"] pre_script = hardware.pre_script post_flash_script = hardware.post_flash_script post_script = hardware.post_script if pre_script: self.run_custom_script(pre_script, 30) try: ser = serial.Serial( serial_device, baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=self.timeout ) except serial.SerialException as e: self.set_state("failed", 0) self.instance.reason = "Failed" logger.error("Serial device error: %s" % (str(e))) if serial_pty and ser_pty_process: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) self.make_device_available(serial_device) return ser.flush() harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) read_pipe, write_pipe = os.pipe() start_time = time.time() t = threading.Thread(target=self.monitor_serial, daemon=True, args=(ser, read_pipe, harness)) t.start() d_log = "{}/device.log".format(self.instance.build_dir) logger.debug('Flash command: %s', command) try: stdout = stderr = None with subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: (stdout, stderr) = proc.communicate(timeout=30) logger.debug(stdout.decode()) if proc.returncode != 0: self.instance.reason = "Device issue (Flash?)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) os.write(write_pipe, b'x') # halt the thread out_state = "flash_error" except subprocess.TimeoutExpired: proc.kill() (stdout, stderr) = proc.communicate() self.instance.reason = "Device issue (Timeout)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.CalledProcessError: os.write(write_pipe, b'x') # halt the thread if post_flash_script: self.run_custom_script(post_flash_script, 30) t.join(self.timeout) if t.is_alive(): logger.debug("Timed out while monitoring serial output on {}".format(self.instance.platform.name)) out_state = "timeout" if ser.isOpen(): ser.close() if serial_pty: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) os.close(write_pipe) os.close(read_pipe) handler_time = time.time() - start_time if out_state in ["timeout", "flash_error"]: for c in self.instance.testcase.cases: if c not in harness.tests: harness.tests[c] = "BLOCK" if out_state == "timeout": self.instance.reason = "Timeout" elif out_state == "flash_error": self.instance.reason = "Flash error" if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests # sometimes a test instance hasn't been executed successfully with an # empty dictionary results, in order to include it into final report, # so fill the results as BLOCK if self.instance.results == {}: for k in self.instance.testcase.cases: self.instance.results[k] = 'BLOCK' if harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state(out_state, handler_time) if post_script: self.run_custom_script(post_script, 30) self.make_device_available(serial_device) self.record(harness) class QEMUHandler(Handler): """Spawns a thread to monitor QEMU output from pipes We pass QEMU_PIPE to 'make run' and monitor the pipes for output. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") if "ignore_qemu_crash" in instance.testcase.tags: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process exection time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results, harness, ignore_unexpected_eof=False): fifo_in = fifo_fn + ".in" fifo_out = fifo_fn + ".out" # These in/out nodes are named from QEMU's perspective, not ours if os.path.exists(fifo_in): os.unlink(fifo_in) os.mkfifo(fifo_in) if os.path.exists(fifo_out): os.unlink(fifo_out) os.mkfifo(fifo_out) # We don't do anything with out_fp but we need to open it for # writing so that QEMU doesn't block, due to the way pipes work out_fp = open(fifo_in, "wb") # Disable internal buffering, we don't # want read() or poll() to ever block if there is data in there in_fp = open(fifo_out, "rb", buffering=0) log_out_fp = open(logfile, "wt") start_time = time.time() timeout_time = start_time + timeout p = select.poll() p.register(in_fp, select.POLLIN) out_state = None line = "" timeout_extended = False pid = 0 if os.path.exists(pid_fn): pid = int(open(pid_fn).read()) while True: this_timeout = int((timeout_time - time.time()) * 1000) if this_timeout < 0 or not p.poll(this_timeout): try: if pid and this_timeout > 0: #there's possibility we polled nothing because #of not enough CPU time scheduled by host for #QEMU process during p.poll(this_timeout) cpu_time = QEMUHandler._get_cpu_time(pid) if cpu_time < timeout and not out_state: timeout_time = time.time() + (timeout - cpu_time) continue except ProcessLookupError: out_state = "failed" break if not out_state: out_state = "timeout" break if pid == 0 and os.path.exists(pid_fn): pid = int(open(pid_fn).read()) if harness.is_pytest: harness.handle(None) out_state = harness.state break try: c = in_fp.read(1).decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail out_state = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: out_state = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(line) log_out_fp.flush() line = line.strip() logger.debug(f"QEMU ({pid}): {line}") harness.handle(line) if harness.state: # if we have registered a fail make sure the state is not # overridden by a false success message coming from the # testsuite if out_state not in ['failed', 'unexpected eof', 'unexpected byte']: out_state = harness.state # if we get some state, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" if harness.is_pytest: harness.pytest_run(logfile) out_state = harness.state handler.record(harness) handler_time = time.time() - start_time logger.debug(f"QEMU ({pid}) complete ({out_state}) after {handler_time} seconds") if out_state == "timeout": handler.instance.reason = "Timeout" handler.set_state("failed", handler_time) elif out_state == "failed": handler.instance.reason = "Failed" handler.set_state("failed", handler_time) elif out_state in ['unexpected eof', 'unexpected byte']: handler.instance.reason = out_state handler.set_state("failed", handler_time) else: handler.set_state(out_state, handler_time) log_out_fp.close() out_fp.close() in_fp.close() if pid: try: if pid: os.kill(pid, signal.SIGTERM) except ProcessLookupError: # Oh well, as long as it's dead! User probably sent Ctrl-C pass os.unlink(fifo_in) os.unlink(fifo_out) def handle(self): self.results = {} self.run = True # We pass this to QEMU which looks for fifos with .in and .out # suffixes. self.fifo_fn = os.path.join(self.instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(self.instance.build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log harness_import = HarnessImporter(self.instance.testcase.harness.capitalize()) harness = harness_import.instance harness.configure(self.instance) self.thread = threading.Thread(name=self.name, target=QEMUHandler._thread, args=(self, self.timeout, self.build_dir, self.log_fn, self.fifo_fn, self.pid_fn, self.results, harness, self.ignore_unexpected_eof)) self.instance.results = harness.tests self.thread.daemon = True logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread.start() if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) logger.debug("Running %s (%s)" % (self.name, self.type_str)) command = [self.generator_cmd] command += ["-C", self.build_dir, "run"] is_timeout = False qemu_pid = None with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) try: proc.wait(self.timeout) except subprocess.TimeoutExpired: # sometimes QEMU can't handle SIGTERM signal correctly # in that case kill -9 QEMU process directly and leave # twister to judge testing result by console output is_timeout = True if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) try: os.kill(qemu_pid, signal.SIGKILL) except ProcessLookupError: pass proc.wait() if harness.state == "passed": self.returncode = 0 else: self.returncode = proc.returncode else: proc.terminate() proc.kill() self.returncode = proc.returncode else: if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) logger.debug(f"No timeout, return code from QEMU ({qemu_pid}): {proc.returncode}") self.returncode = proc.returncode # Need to wait for harness to finish processing # output from QEMU. Otherwise it might miss some # error messages. self.thread.join() if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({qemu_pid}): {self.returncode}") if (self.returncode != 0 and not self.ignore_qemu_crash) or not harness.state: self.set_state("failed", 0) if is_timeout: self.instance.reason = "Timeout" else: self.instance.reason = "Exited with {}".format(self.returncode) def get_fifo(self): return self.fifo_fn class SizeCalculator: alloc_sections = [ "bss", "noinit", "app_bss", "app_noinit", "ccm_bss", "ccm_noinit" ] rw_sections = [ "datas", "initlevel", "exceptions", "initshell", "_static_thread_data_area", "k_timer_area", "k_mem_slab_area", "k_mem_pool_area", "sw_isr_table", "k_sem_area", "k_mutex_area", "app_shmem_regions", "_k_fifo_area", "_k_lifo_area", "k_stack_area", "k_msgq_area", "k_mbox_area", "k_pipe_area", "net_if_area", "net_if_dev_area", "net_l2_area", "net_l2_data", "k_queue_area", "_net_buf_pool_area", "app_datas", "kobject_data", "mmu_tables", "app_pad", "priv_stacks", "ccm_data", "usb_descriptor", "usb_data", "usb_bos_desc", "uart_mux", 'log_backends_sections', 'log_dynamic_sections', 'log_const_sections', "app_smem", 'shell_root_cmds_sections', 'log_const_sections', "font_entry_sections", "priv_stacks_noinit", "_GCOV_BSS_SECTION_NAME", "gcov", "nocache", "devices", "k_heap_area", ] # These get copied into RAM only on non-XIP ro_sections = [ "rom_start", "text", "ctors", "init_array", "reset", "z_object_assignment_area", "rodata", "net_l2", "vector", "sw_isr_table", "settings_handler_static_area", "bt_l2cap_fixed_chan_area", "bt_l2cap_br_fixed_chan_area", "bt_gatt_service_static_area", "vectors", "net_socket_register_area", "net_ppp_proto", "shell_area", "tracing_backend_area", "ppp_protocol_handler_area", ] def __init__(self, filename, extra_sections): """Constructor @param filename Path to the output binary The <filename> is parsed by objdump to determine section sizes """ # Make sure this is an ELF binary with open(filename, "rb") as f: magic = f.read(4) try: if magic != b'\x7fELF': raise TwisterRuntimeError("%s is not an ELF binary" % filename) except Exception as e: print(str(e)) sys.exit(2) # Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK. # GREP can not be used as it returns an error if the symbol is not # found. is_xip_command = "nm " + filename + \ " | awk '/CONFIG_XIP/ { print $3 }'" is_xip_output = subprocess.check_output( is_xip_command, shell=True, stderr=subprocess.STDOUT).decode( "utf-8").strip() try: if is_xip_output.endswith("no symbols"): raise TwisterRuntimeError("%s has no symbol information" % filename) except Exception as e: print(str(e)) sys.exit(2) self.is_xip = (len(is_xip_output) != 0) self.filename = filename self.sections = [] self.rom_size = 0 self.ram_size = 0 self.extra_sections = extra_sections self._calculate_sizes() def get_ram_size(self): """Get the amount of RAM the application will use up on the device @return amount of RAM, in bytes """ return self.ram_size def get_rom_size(self): """Get the size of the data that this application uses on device's flash @return amount of ROM, in bytes """ return self.rom_size def unrecognized_sections(self): """Get a list of sections inside the binary that weren't recognized @return list of unrecognized section names """ slist = [] for v in self.sections: if not v["recognized"]: slist.append(v["name"]) return slist def _calculate_sizes(self): """ Calculate RAM and ROM usage by section """ objdump_command = "objdump -h " + self.filename objdump_output = subprocess.check_output( objdump_command, shell=True).decode("utf-8").splitlines() for line in objdump_output: words = line.split() if not words: # Skip lines that are too short continue index = words[0] if not index[0].isdigit(): # Skip lines that do not start continue # with a digit name = words[1] # Skip lines with section names if name[0] == '.': # starting with '.' continue # TODO this doesn't actually reflect the size in flash or RAM as # it doesn't include linker-imposed padding between sections. # It is close though. size = int(words[2], 16) if size == 0: continue load_addr = int(words[4], 16) virt_addr = int(words[3], 16) # Add section to memory use totals (for both non-XIP and XIP scenarios) # Unrecognized section names are not included in the calculations. recognized = True if name in SizeCalculator.alloc_sections: self.ram_size += size stype = "alloc" elif name in SizeCalculator.rw_sections: self.ram_size += size self.rom_size += size stype = "rw" elif name in SizeCalculator.ro_sections: self.rom_size += size if not self.is_xip: self.ram_size += size stype = "ro" else: stype = "unknown" if name not in self.extra_sections: recognized = False self.sections.append({"name": name, "load_addr": load_addr, "size": size, "virt_addr": virt_addr, "type": stype, "recognized": recognized}) class TwisterConfigParser: """Class to read test case files with semantic checking """ def __init__(self, filename, schema): """Instantiate a new TwisterConfigParser object @param filename Source .yaml file to read """ self.data = {} self.schema = schema self.filename = filename self.tests = {} self.common = {} def load(self): self.data = scl.yaml_load_verify(self.filename, self.schema) if 'tests' in self.data: self.tests = self.data['tests'] if 'common' in self.data: self.common = self.data['common'] def _cast_value(self, value, typestr): if isinstance(value, str): v = value.strip() if typestr == "str": return v elif typestr == "float": return float(value) elif typestr == "int": return int(value) elif typestr == "bool": return value elif typestr.startswith("list") and isinstance(value, list): return value elif typestr.startswith("list") and isinstance(value, str): vs = v.split() if len(typestr) > 4 and typestr[4] == ":": return [self._cast_value(vsi, typestr[5:]) for vsi in vs] else: return vs elif typestr.startswith("set"): vs = v.split() if len(typestr) > 3 and typestr[3] == ":": return {self._cast_value(vsi, typestr[4:]) for vsi in vs} else: return set(vs) elif typestr.startswith("map"): return value else: raise ConfigurationError( self.filename, "unknown type '%s'" % value) def get_test(self, name, valid_keys): """Get a dictionary representing the keys/values within a test @param name The test in the .yaml file to retrieve data from @param valid_keys A dictionary representing the intended semantics for this test. Each key in this dictionary is a key that could be specified, if a key is given in the .yaml file which isn't in here, it will generate an error. Each value in this dictionary is another dictionary containing metadata: "default" - Default value if not given "type" - Data type to convert the text value to. Simple types supported are "str", "float", "int", "bool" which will get converted to respective Python data types. "set" and "list" may also be specified which will split the value by whitespace (but keep the elements as strings). finally, "list:<type>" and "set:<type>" may be given which will perform a type conversion after splitting the value up. "required" - If true, raise an error if not defined. If false and "default" isn't specified, a type conversion will be done on an empty string @return A dictionary containing the test key-value pairs with type conversion and default values filled in per valid_keys """ d = {} for k, v in self.common.items(): d[k] = v for k, v in self.tests[name].items(): if k in d: if isinstance(d[k], str): # By default, we just concatenate string values of keys # which appear both in "common" and per-test sections, # but some keys are handled in adhoc way based on their # semantics. if k == "filter": d[k] = "(%s) and (%s)" % (d[k], v) else: d[k] += " " + v else: d[k] = v for k, kinfo in valid_keys.items(): if k not in d: if "required" in kinfo: required = kinfo["required"] else: required = False if required: raise ConfigurationError( self.filename, "missing required value for '%s' in test '%s'" % (k, name)) else: if "default" in kinfo: default = kinfo["default"] else: default = self._cast_value("", kinfo["type"]) d[k] = default else: try: d[k] = self._cast_value(d[k], kinfo["type"]) except ValueError: raise ConfigurationError( self.filename, "bad %s value '%s' for key '%s' in name '%s'" % (kinfo["type"], d[k], k, name)) return d class Platform: """Class representing metadata for a particular platform Maps directly to BOARD when building""" platform_schema = scl.yaml_load(os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "platform-schema.yaml")) def __init__(self): """Constructor. """ self.name = "" self.twister = True # if no RAM size is specified by the board, take a default of 128K self.ram = 128 self.ignore_tags = [] self.only_tags = [] self.default = False # if no flash size is specified by the board, take a default of 512K self.flash = 512 self.supported = set() self.arch = "" self.type = "na" self.simulation = "na" self.supported_toolchains = [] self.env = [] self.env_satisfied = True self.filter_data = dict() def load(self, platform_file): scp = TwisterConfigParser(platform_file, self.platform_schema) scp.load() data = scp.data self.name = data['identifier'] self.twister = data.get("twister", True) # if no RAM size is specified by the board, take a default of 128K self.ram = data.get("ram", 128) testing = data.get("testing", {}) self.ignore_tags = testing.get("ignore_tags", []) self.only_tags = testing.get("only_tags", []) self.default = testing.get("default", False) # if no flash size is specified by the board, take a default of 512K self.flash = data.get("flash", 512) self.supported = set() for supp_feature in data.get("supported", []): for item in supp_feature.split(":"): self.supported.add(item) self.arch = data['arch'] self.type = data.get('type', "na") self.simulation = data.get('simulation', "na") self.supported_toolchains = data.get("toolchain", []) self.env = data.get("env", []) self.env_satisfied = True for env in self.env: if not os.environ.get(env, None): self.env_satisfied = False def __repr__(self): return "<%s on %s>" % (self.name, self.arch) class DisablePyTestCollectionMixin(object): __test__ = False class TestCase(DisablePyTestCollectionMixin): """Class representing a test application """ def __init__(self, testcase_root, workdir, name): """TestCase constructor. This gets called by TestSuite as it finds and reads test yaml files. Multiple TestCase instances may be generated from a single testcase.yaml, each one corresponds to an entry within that file. We need to have a unique name for every single test case. Since a testcase.yaml can define multiple tests, the canonical name for the test case is <workdir>/<name>. @param testcase_root os.path.abspath() of one of the --testcase-root @param workdir Sub-directory of testcase_root where the .yaml test configuration file was found @param name Name of this test case, corresponding to the entry name in the test case configuration file. For many test cases that just define one test, can be anything and is usually "test". This is really only used to distinguish between different cases when the testcase.yaml defines multiple tests """ self.source_dir = "" self.yamlfile = "" self.cases = [] self.name = self.get_unique(testcase_root, workdir, name) self.id = name self.type = None self.tags = set() self.extra_args = None self.extra_configs = None self.arch_allow = None self.arch_exclude = None self.skip = False self.platform_exclude = None self.platform_allow = None self.toolchain_exclude = None self.toolchain_allow = None self.tc_filter = None self.timeout = 60 self.harness = "" self.harness_config = {} self.build_only = True self.build_on_all = False self.slow = False self.min_ram = -1 self.depends_on = None self.min_flash = -1 self.extra_sections = None self.integration_platforms = [] @staticmethod def get_unique(testcase_root, workdir, name): canonical_testcase_root = os.path.realpath(testcase_root) if Path(canonical_zephyr_base) in Path(canonical_testcase_root).parents: # This is in ZEPHYR_BASE, so include path in name for uniqueness # FIXME: We should not depend on path of test for unique names. relative_tc_root = os.path.relpath(canonical_testcase_root, start=canonical_zephyr_base) else: relative_tc_root = "" # workdir can be "." unique = os.path.normpath(os.path.join(relative_tc_root, workdir, name)) check = name.split(".") if len(check) < 2: raise TwisterException(f"""bad test name '{name}' in {testcase_root}/{workdir}. \ Tests should reference the category and subsystem with a dot as a separator. """ ) return unique @staticmethod def scan_file(inf_name): suite_regex = re.compile( # do not match until end-of-line, otherwise we won't allow # stc_regex below to catch the ones that are declared in the same # line--as we only search starting the end of this match br"^\s*ztest_test_suite\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) stc_regex = re.compile( br"^\s*" # empy space at the beginning is ok # catch the case where it is declared in the same sentence, e.g: # # ztest_test_suite(mutex_complex, ztest_user_unit_test(TESTNAME)); br"(?:ztest_test_suite\([a-zA-Z0-9_]+,\s*)?" # Catch ztest[_user]_unit_test-[_setup_teardown](TESTNAME) br"ztest_(?:1cpu_)?(?:user_)?unit_test(?:_setup_teardown)?" # Consume the argument that becomes the extra testcse br"\(\s*" br"(?P<stc_name>[a-zA-Z0-9_]+)" # _setup_teardown() variant has two extra arguments that we ignore br"(?:\s*,\s*[a-zA-Z0-9_]+\s*,\s*[a-zA-Z0-9_]+)?" br"\s*\)", # We don't check how it finishes; we don't care re.MULTILINE) suite_run_regex = re.compile( br"^\s*ztest_run_test_suite\((?P<suite_name>[a-zA-Z0-9_]+)\)", re.MULTILINE) achtung_regex = re.compile( br"(#ifdef|#endif)", re.MULTILINE) warnings = None with open(inf_name) as inf: if os.name == 'nt': mmap_args = {'fileno': inf.fileno(), 'length': 0, 'access': mmap.ACCESS_READ} else: mmap_args = {'fileno': inf.fileno(), 'length': 0, 'flags': mmap.MAP_PRIVATE, 'prot': mmap.PROT_READ, 'offset': 0} with contextlib.closing(mmap.mmap(**mmap_args)) as main_c: suite_regex_match = suite_regex.search(main_c) if not suite_regex_match: # can't find ztest_test_suite, maybe a client, because # it includes ztest.h return None, None suite_run_match = suite_run_regex.search(main_c) if not suite_run_match: raise ValueError("can't find ztest_run_test_suite") achtung_matches = re.findall( achtung_regex, main_c[suite_regex_match.end():suite_run_match.start()]) if achtung_matches: warnings = "found invalid %s in ztest_test_suite()" \ % ", ".join(sorted({match.decode() for match in achtung_matches},reverse = True)) _matches = re.findall( stc_regex, main_c[suite_regex_match.end():suite_run_match.start()]) for match in _matches: if not match.decode().startswith("test_"): warnings = "Found a test that does not start with test_" matches = [match.decode().replace("test_", "", 1) for match in _matches] return matches, warnings def scan_path(self, path): subcases = [] for filename in glob.glob(os.path.join(path, "src", "*.c*")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) raise TwisterRuntimeError("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) for filename in glob.glob(os.path.join(path, "*.c")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) return subcases def parse_subcases(self, test_path): results = self.scan_path(test_path) for sub in results: name = "{}.{}".format(self.id, sub) self.cases.append(name) if not results: self.cases.append(self.id) def __str__(self): return self.name class TestInstance(DisablePyTestCollectionMixin): """Class representing the execution of a particular TestCase on a platform @param test The TestCase object we want to build/execute @param platform Platform object that we want to build and run against @param base_outdir Base directory for all test results. The actual out directory used is <outdir>/<platform>/<test case name> """ def __init__(self, testcase, platform, outdir): self.testcase = testcase self.platform = platform self.status = None self.reason = "Unknown" self.metrics = dict() self.handler = None self.outdir = outdir self.name = os.path.join(platform.name, testcase.name) self.build_dir = os.path.join(outdir, platform.name, testcase.name) self.run = False self.results = {} def __getstate__(self): d = self.__dict__.copy() return d def __setstate__(self, d): self.__dict__.update(d) def __lt__(self, other): return self.name < other.name @staticmethod def testcase_runnable(testcase, fixtures): can_run = False # console harness allows us to run the test and capture data. if testcase.harness in [ 'console', 'ztest', 'pytest']: can_run = True # if we have a fixture that is also being supplied on the # command-line, then we need to run the test, not just build it. fixture = testcase.harness_config.get('fixture') if fixture: can_run = (fixture in fixtures) elif testcase.harness: can_run = False else: can_run = True return can_run # Global testsuite parameters def check_runnable(self, enable_slow=False, filter='buildable', fixtures=[]): # right now we only support building on windows. running is still work # in progress. if os.name == 'nt': return False # we asked for build-only on the command line if self.testcase.build_only: return False # Do not run slow tests: skip_slow = self.testcase.slow and not enable_slow if skip_slow: return False target_ready = bool(self.testcase.type == "unit" or \ self.platform.type == "native" or \ self.platform.simulation in ["mdb-nsim", "nsim", "renode", "qemu", "tsim", "armfvp"] or \ filter == 'runnable') if self.platform.simulation == "nsim": if not find_executable("nsimdrv"): target_ready = False if self.platform.simulation == "mdb-nsim": if not find_executable("mdb"): target_ready = False if self.platform.simulation == "renode": if not find_executable("renode"): target_ready = False if self.platform.simulation == "tsim": if not find_executable("tsim-leon3"): target_ready = False testcase_runnable = self.testcase_runnable(self.testcase, fixtures) return testcase_runnable and target_ready def create_overlay(self, platform, enable_asan=False, enable_ubsan=False, enable_coverage=False, coverage_platform=[]): # Create this in a "twister/" subdirectory otherwise this # will pass this overlay to kconfig.py *twice* and kconfig.cmake # will silently give that second time precedence over any # --extra-args=CONFIG_* subdir = os.path.join(self.build_dir, "twister") content = "" if self.testcase.extra_configs: content = "\n".join(self.testcase.extra_configs) if enable_coverage: if platform.name in coverage_platform: content = content + "\nCONFIG_COVERAGE=y" content = content + "\nCONFIG_COVERAGE_DUMP=y" if enable_asan: if platform.type == "native": content = content + "\nCONFIG_ASAN=y" if enable_ubsan: if platform.type == "native": content = content + "\nCONFIG_UBSAN=y" if content: os.makedirs(subdir, exist_ok=True) file = os.path.join(subdir, "testcase_extra.conf") with open(file, "w") as f: f.write(content) return content def calculate_sizes(self): """Get the RAM/ROM sizes of a test case. This can only be run after the instance has been executed by MakeGenerator, otherwise there won't be any binaries to measure. @return A SizeCalculator object """ fns = glob.glob(os.path.join(self.build_dir, "zephyr", "*.elf")) fns.extend(glob.glob(os.path.join(self.build_dir, "zephyr", "*.exe"))) fns = [x for x in fns if not x.endswith('_prebuilt.elf')] if len(fns) != 1: raise BuildError("Missing/multiple output ELF binary") return SizeCalculator(fns[0], self.testcase.extra_sections) def fill_results_by_status(self): """Fills results according to self.status The method is used to propagate the instance level status to the test cases inside. Useful when the whole instance is skipped and the info is required also at the test cases level for reporting. Should be used with caution, e.g. should not be used to fill all results with passes """ status_to_verdict = { 'skipped': 'SKIP', 'error': 'BLOCK', 'failure': 'FAILED' } for k in self.results: self.results[k] = status_to_verdict[self.status] def __repr__(self): return "<TestCase %s on %s>" % (self.testcase.name, self.platform.name) class CMake(): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') def __init__(self, testcase, platform, source_dir, build_dir): self.cwd = None self.capture_output = True self.defconfig = {} self.cmake_cache = {} self.instance = None self.testcase = testcase self.platform = platform self.source_dir = source_dir self.build_dir = build_dir self.log = "build.log" self.generator = None self.generator_cmd = None def parse_generated(self): self.defconfig = {} return {} def run_build(self, args=[]): logger.debug("Building %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [] cmake_args.extend(args) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() results = {} if p.returncode == 0: msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) self.instance.status = "passed" results = {'msg': msg, "returncode": p.returncode, "instance": self.instance} if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) else: return None else: # A real error occurred, raise an exception log_msg = "" if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) if log_msg: res = re.findall("region `(FLASH|RAM|ICCM|DCCM|SRAM)' overflowed by", log_msg) if res and not self.overflow_as_errors: logger.debug("Test skipped due to {} Overflow".format(res[0])) self.instance.status = "skipped" self.instance.reason = "{} overflow".format(res[0]) else: self.instance.status = "error" self.instance.reason = "Build failure" results = { "returncode": p.returncode, "instance": self.instance, } return results def run_cmake(self, args=[]): if self.warnings_as_errors: ldflags = "-Wl,--fatal-warnings" cflags = "-Werror" aflags = "-Wa,--fatal-warnings" gen_defines_args = "--err-on-deprecated-properties" else: ldflags = cflags = aflags = "" gen_defines_args = "" logger.debug("Running cmake on %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [ f'-B{self.build_dir}', f'-S{self.source_dir}', f'-DEXTRA_CFLAGS="{cflags}"', f'-DEXTRA_AFLAGS="{aflags}', f'-DEXTRA_LDFLAGS="{ldflags}"', f'-DEXTRA_GEN_DEFINES_ARGS={gen_defines_args}', f'-G{self.generator}' ] if self.cmake_only: cmake_args.append("-DCMAKE_EXPORT_COMPILE_COMMANDS=1") args = ["-D{}".format(a.replace('"', '')) for a in args] cmake_args.extend(args) cmake_opts = ['-DBOARD={}'.format(self.platform.name)] cmake_args.extend(cmake_opts) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: filter_results = self.parse_generated() msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) logger.debug(msg) results = {'msg': msg, 'filter': filter_results} else: self.instance.status = "error" self.instance.reason = "Cmake build failure" logger.error("Cmake build failure: %s for %s" % (self.source_dir, self.platform.name)) results = {"returncode": p.returncode} if out: with open(os.path.join(self.build_dir, self.log), "a") as log: log_msg = out.decode(sys.getdefaultencoding()) log.write(log_msg) return results @staticmethod def run_cmake_script(args=[]): logger.debug("Running cmake script %s" % (args[0])) cmake_args = ["-D{}".format(a.replace('"', '')) for a in args[1:]] cmake_args.extend(['-P', args[0]]) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') if not cmake: msg = "Unable to find `cmake` in path" logger.error(msg) raise Exception(msg) cmd = [cmake] + cmake_args kwargs = dict() kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: msg = "Finished running %s" % (args[0]) logger.debug(msg) results = {"returncode": p.returncode, "msg": msg, "stdout": out} else: logger.error("Cmake script failure: %s" % (args[0])) results = {"returncode": p.returncode} return results class FilterBuilder(CMake): def __init__(self, testcase, platform, source_dir, build_dir): super().__init__(testcase, platform, source_dir, build_dir) self.log = "config-twister.log" def parse_generated(self): if self.platform.name == "unit_testing": return {} cmake_cache_path = os.path.join(self.build_dir, "CMakeCache.txt") defconfig_path = os.path.join(self.build_dir, "zephyr", ".config") with open(defconfig_path, "r") as fp: defconfig = {} for line in fp.readlines(): m = self.config_re.match(line) if not m: if line.strip() and not line.startswith("#"): sys.stderr.write("Unrecognized line %s\n" % line) continue defconfig[m.group(1)] = m.group(2).strip() self.defconfig = defconfig cmake_conf = {} try: cache = CMakeCache.from_file(cmake_cache_path) except FileNotFoundError: cache = {} for k in iter(cache): cmake_conf[k.name] = k.value self.cmake_cache = cmake_conf filter_data = { "ARCH": self.platform.arch, "PLATFORM": self.platform.name } filter_data.update(os.environ) filter_data.update(self.defconfig) filter_data.update(self.cmake_cache) edt_pickle = os.path.join(self.build_dir, "zephyr", "edt.pickle") if self.testcase and self.testcase.tc_filter: try: if os.path.exists(edt_pickle): with open(edt_pickle, 'rb') as f: edt = pickle.load(f) else: edt = None res = expr_parser.parse(self.testcase.tc_filter, filter_data, edt) except (ValueError, SyntaxError) as se: sys.stderr.write( "Failed processing %s\n" % self.testcase.yamlfile) raise se if not res: return {os.path.join(self.platform.name, self.testcase.name): True} else: return {os.path.join(self.platform.name, self.testcase.name): False} else: self.platform.filter_data = filter_data return filter_data class ProjectBuilder(FilterBuilder): def __init__(self, suite, instance, **kwargs): super().__init__(instance.testcase, instance.platform, instance.testcase.source_dir, instance.build_dir) self.log = "build.log" self.instance = instance self.suite = suite self.filtered_tests = 0 self.lsan = kwargs.get('lsan', False) self.asan = kwargs.get('asan', False) self.ubsan = kwargs.get('ubsan', False) self.valgrind = kwargs.get('valgrind', False) self.extra_args = kwargs.get('extra_args', []) self.device_testing = kwargs.get('device_testing', False) self.cmake_only = kwargs.get('cmake_only', False) self.cleanup = kwargs.get('cleanup', False) self.coverage = kwargs.get('coverage', False) self.inline_logs = kwargs.get('inline_logs', False) self.generator = kwargs.get('generator', None) self.generator_cmd = kwargs.get('generator_cmd', None) self.verbose = kwargs.get('verbose', None) self.warnings_as_errors = kwargs.get('warnings_as_errors', True) self.overflow_as_errors = kwargs.get('overflow_as_errors', False) @staticmethod def log_info(filename, inline_logs): filename = os.path.abspath(os.path.realpath(filename)) if inline_logs: logger.info("{:-^100}".format(filename)) try: with open(filename) as fp: data = fp.read() except Exception as e: data = "Unable to read log data (%s)\n" % (str(e)) logger.error(data) logger.info("{:-^100}".format(filename)) else: logger.error("see: " + Fore.YELLOW + filename + Fore.RESET) def log_info_file(self, inline_logs): build_dir = self.instance.build_dir h_log = "{}/handler.log".format(build_dir) b_log = "{}/build.log".format(build_dir) v_log = "{}/valgrind.log".format(build_dir) d_log = "{}/device.log".format(build_dir) if os.path.exists(v_log) and "Valgrind" in self.instance.reason: self.log_info("{}".format(v_log), inline_logs) elif os.path.exists(h_log) and os.path.getsize(h_log) > 0: self.log_info("{}".format(h_log), inline_logs) elif os.path.exists(d_log) and os.path.getsize(d_log) > 0: self.log_info("{}".format(d_log), inline_logs) else: self.log_info("{}".format(b_log), inline_logs) def setup_handler(self): instance = self.instance args = [] # FIXME: Needs simplification if instance.platform.simulation == "qemu": instance.handler = QEMUHandler(instance, "qemu") args.append("QEMU_PIPE=%s" % instance.handler.get_fifo()) instance.handler.call_make_run = True elif instance.testcase.type == "unit": instance.handler = BinaryHandler(instance, "unit") instance.handler.binary = os.path.join(instance.build_dir, "testbinary") if self.coverage: args.append("COVERAGE=1") elif instance.platform.type == "native": handler = BinaryHandler(instance, "native") handler.asan = self.asan handler.valgrind = self.valgrind handler.lsan = self.lsan handler.ubsan = self.ubsan handler.coverage = self.coverage handler.binary = os.path.join(instance.build_dir, "zephyr", "zephyr.exe") instance.handler = handler elif instance.platform.simulation == "renode": if find_executable("renode"): instance.handler = BinaryHandler(instance, "renode") instance.handler.pid_fn = os.path.join(instance.build_dir, "renode.pid") instance.handler.call_make_run = True elif instance.platform.simulation == "tsim": instance.handler = BinaryHandler(instance, "tsim") instance.handler.call_make_run = True elif self.device_testing: instance.handler = DeviceHandler(instance, "device") instance.handler.coverage = self.coverage elif instance.platform.simulation == "nsim": if find_executable("nsimdrv"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "mdb-nsim": if find_executable("mdb"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.pid_fn = os.path.join(instance.build_dir, "mdb.pid") instance.handler.call_west_flash = True elif instance.platform.simulation == "armfvp": instance.handler = BinaryHandler(instance, "armfvp") instance.handler.call_make_run = True if instance.handler: instance.handler.args = args instance.handler.generator_cmd = self.generator_cmd instance.handler.generator = self.generator def process(self, pipeline, done, message, lock, results): op = message.get('op') if not self.instance.handler: self.setup_handler() # The build process, call cmake and build with configured generator if op == "cmake": res = self.cmake() if self.instance.status in ["failed", "error"]: pipeline.put({"op": "report", "test": self.instance}) elif self.cmake_only: if self.instance.status is None: self.instance.status = "passed" pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.name in res['filter'] and res['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = "skipped" self.instance.reason = "filter" results.skipped_runtime += 1 for case in self.instance.testcase.cases: self.instance.results.update({case: 'SKIP'}) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "build", "test": self.instance}) elif op == "build": logger.debug("build test: %s" % self.instance.name) res = self.build() if not res: self.instance.status = "error" self.instance.reason = "Build Failure" pipeline.put({"op": "report", "test": self.instance}) else: # Count skipped cases during build, for example # due to ram/rom overflow. inst = res.get("instance", None) if inst and inst.status == "skipped": results.skipped_runtime += 1 if res.get('returncode', 1) > 0: pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.run and self.instance.handler: pipeline.put({"op": "run", "test": self.instance}) else: pipeline.put({"op": "report", "test": self.instance}) # Run the generated binary using one of the supported handlers elif op == "run": logger.debug("run test: %s" % self.instance.name) self.run() self.instance.status, _ = self.instance.handler.get_state() logger.debug(f"run status: {self.instance.name} {self.instance.status}") # to make it work with pickle self.instance.handler.thread = None self.instance.handler.suite = None pipeline.put({ "op": "report", "test": self.instance, "status": self.instance.status, "reason": self.instance.reason } ) # Report results and output progress to screen elif op == "report": with lock: done.put(self.instance) self.report_out(results) if self.cleanup and not self.coverage and self.instance.status == "passed": pipeline.put({ "op": "cleanup", "test": self.instance }) elif op == "cleanup": if self.device_testing: self.cleanup_device_testing_artifacts() else: self.cleanup_artifacts() def cleanup_artifacts(self, additional_keep=[]): logger.debug("Cleaning up {}".format(self.instance.build_dir)) allow = [ 'zephyr/.config', 'handler.log', 'build.log', 'device.log', 'recording.csv', ] allow += additional_keep allow = [os.path.join(self.instance.build_dir, file) for file in allow] for dirpath, dirnames, filenames in os.walk(self.instance.build_dir, topdown=False): for name in filenames: path = os.path.join(dirpath, name) if path not in allow: os.remove(path) # Remove empty directories and symbolic links to directories for dir in dirnames: path = os.path.join(dirpath, dir) if os.path.islink(path): os.remove(path) elif not os.listdir(path): os.rmdir(path) def cleanup_device_testing_artifacts(self): logger.debug("Cleaning up for Device Testing {}".format(self.instance.build_dir)) sanitizelist = [ 'CMakeCache.txt', 'zephyr/runners.yaml', ] keep = [ 'zephyr/zephyr.hex', 'zephyr/zephyr.bin', 'zephyr/zephyr.elf', ] keep += sanitizelist self.cleanup_artifacts(keep) # sanitize paths so files are relocatable for file in sanitizelist: file = os.path.join(self.instance.build_dir, file) with open(file, "rt") as fin: data = fin.read() data = data.replace(canonical_zephyr_base+"/", "") with open(file, "wt") as fin: fin.write(data) def report_out(self, results): total_to_do = results.total - results.skipped_configs total_tests_width = len(str(total_to_do)) results.done += 1 instance = self.instance if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.status == "error": results.error += 1 results.failed += 1 if self.verbose: status = Fore.RED + "FAILED " + Fore.RESET + instance.reason else: print("") logger.error( "{:<25} {:<50} {}FAILED{}: {}".format( instance.platform.name, instance.testcase.name, Fore.RED, Fore.RESET, instance.reason)) if not self.verbose: self.log_info_file(self.inline_logs) elif instance.status == "skipped": status = Fore.YELLOW + "SKIPPED" + Fore.RESET elif instance.status == "passed": status = Fore.GREEN + "PASSED" + Fore.RESET else: logger.debug(f"Unknown status = {instance.status}") status = Fore.YELLOW + "UNKNOWN" + Fore.RESET if self.verbose: if self.cmake_only: more_info = "cmake" elif instance.status == "skipped": more_info = instance.reason else: if instance.handler and instance.run: more_info = instance.handler.type_str htime = instance.handler.duration if htime: more_info += " {:.3f}s".format(htime) else: more_info = "build" logger.info("{:>{}}/{} {:<25} {:<50} {} ({})".format( results.done, total_tests_width, total_to_do, instance.platform.name, instance.testcase.name, status, more_info)) if instance.status in ["error", "failed", "timeout"]: self.log_info_file(self.inline_logs) else: completed_perc = 0 if total_to_do > 0: completed_perc = int((float(results.done) / total_to_do) * 100) skipped = results.skipped_configs + results.skipped_runtime sys.stdout.write("\rINFO - Total complete: %s%4d/%4d%s %2d%% skipped: %s%4d%s, failed: %s%4d%s" % ( Fore.GREEN, results.done, total_to_do, Fore.RESET, completed_perc, Fore.YELLOW if skipped > 0 else Fore.RESET, skipped, Fore.RESET, Fore.RED if results.failed > 0 else Fore.RESET, results.failed, Fore.RESET ) ) sys.stdout.flush() def cmake(self): instance = self.instance args = self.testcase.extra_args[:] args += self.extra_args if instance.handler: args += instance.handler.args # merge overlay files into one variable def extract_overlays(args): re_overlay = re.compile('OVERLAY_CONFIG=(.*)') other_args = [] overlays = [] for arg in args: match = re_overlay.search(arg) if match: overlays.append(match.group(1).strip('\'"')) else: other_args.append(arg) args[:] = other_args return overlays overlays = extract_overlays(args) if os.path.exists(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")): overlays.append(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")) if overlays: args.append("OVERLAY_CONFIG=\"%s\"" % (" ".join(overlays))) res = self.run_cmake(args) return res def build(self): res = self.run_build(['--build', self.build_dir]) return res def run(self): instance = self.instance if instance.handler: if instance.handler.type_str == "device": instance.handler.suite = self.suite instance.handler.handle() sys.stdout.flush() class TestSuite(DisablePyTestCollectionMixin): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') tc_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "testcase-schema.yaml")) quarantine_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "quarantine-schema.yaml")) testcase_valid_keys = {"tags": {"type": "set", "required": False}, "type": {"type": "str", "default": "integration"}, "extra_args": {"type": "list"}, "extra_configs": {"type": "list"}, "build_only": {"type": "bool", "default": False}, "build_on_all": {"type": "bool", "default": False}, "skip": {"type": "bool", "default": False}, "slow": {"type": "bool", "default": False}, "timeout": {"type": "int", "default": 60}, "min_ram": {"type": "int", "default": 8}, "depends_on": {"type": "set"}, "min_flash": {"type": "int", "default": 32}, "arch_allow": {"type": "set"}, "arch_exclude": {"type": "set"}, "extra_sections": {"type": "list", "default": []}, "integration_platforms": {"type": "list", "default": []}, "platform_exclude": {"type": "set"}, "platform_allow": {"type": "set"}, "toolchain_exclude": {"type": "set"}, "toolchain_allow": {"type": "set"}, "filter": {"type": "str"}, "harness": {"type": "str"}, "harness_config": {"type": "map", "default": {}} } RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "release", "twister_last_release.csv") SAMPLE_FILENAME = 'sample.yaml' TESTCASE_FILENAME = 'testcase.yaml' def __init__(self, board_root_list=[], testcase_roots=[], outdir=None): self.roots = testcase_roots if not isinstance(board_root_list, list): self.board_roots = [board_root_list] else: self.board_roots = board_root_list # Testsuite Options self.coverage_platform = [] self.build_only = False self.cmake_only = False self.cleanup = False self.enable_slow = False self.device_testing = False self.fixtures = [] self.enable_coverage = False self.enable_ubsan = False self.enable_lsan = False self.enable_asan = False self.enable_valgrind = False self.extra_args = [] self.inline_logs = False self.enable_sizes_report = False self.west_flash = None self.west_runner = None self.generator = None self.generator_cmd = None self.warnings_as_errors = True self.overflow_as_errors = False self.quarantine_verify = False # Keep track of which test cases we've filtered out and why self.testcases = {} self.quarantine = {} self.platforms = [] self.selected_platforms = [] self.filtered_platforms = [] self.default_platforms = [] self.outdir = os.path.abspath(outdir) self.discards = {} self.load_errors = 0 self.instances = dict() self.total_platforms = 0 self.start_time = 0 self.duration = 0 self.warnings = 0 # hardcoded for now self.duts = [] # run integration tests only self.integration = False self.pipeline = None self.version = "NA" def check_zephyr_version(self): try: subproc = subprocess.run(["git", "describe", "--abbrev=12"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: self.version = subproc.stdout.strip() logger.info(f"Zephyr version: {self.version}") except OSError: logger.info("Cannot read zephyr version.") def get_platform_instances(self, platform): filtered_dict = {k:v for k,v in self.instances.items() if k.startswith(platform + "/")} return filtered_dict def config(self): logger.info("coverage platform: {}".format(self.coverage_platform)) # Debug Functions @staticmethod def info(what): sys.stdout.write(what + "\n") sys.stdout.flush() def update_counting(self, results=None, initial=False): results.skipped_configs = 0 results.skipped_cases = 0 for instance in self.instances.values(): if initial: results.cases += len(instance.testcase.cases) if instance.status == 'skipped': results.skipped_configs += 1 results.skipped_cases += len(instance.testcase.cases) elif instance.status == "passed": results.passed += 1 for res in instance.results.values(): if res == 'SKIP': results.skipped_cases += 1 def compare_metrics(self, filename): # name, datatype, lower results better interesting_metrics = [("ram_size", int, True), ("rom_size", int, True)] if not os.path.exists(filename): logger.error("Cannot compare metrics, %s not found" % filename) return [] results = [] saved_metrics = {} with open(filename) as fp: cr = csv.DictReader(fp) for row in cr: d = {} for m, _, _ in interesting_metrics: d[m] = row[m] saved_metrics[(row["test"], row["platform"])] = d for instance in self.instances.values(): mkey = (instance.testcase.name, instance.platform.name) if mkey not in saved_metrics: continue sm = saved_metrics[mkey] for metric, mtype, lower_better in interesting_metrics: if metric not in instance.metrics: continue if sm[metric] == "": continue delta = instance.metrics.get(metric, 0) - mtype(sm[metric]) if delta == 0: continue results.append((instance, metric, instance.metrics.get(metric, 0), delta, lower_better)) return results def footprint_reports(self, report, show_footprint, all_deltas, footprint_threshold, last_metrics): if not report: return logger.debug("running footprint_reports") deltas = self.compare_metrics(report) warnings = 0 if deltas and show_footprint: for i, metric, value, delta, lower_better in deltas: if not all_deltas and ((delta < 0 and lower_better) or (delta > 0 and not lower_better)): continue percentage = 0 if value > delta: percentage = (float(delta) / float(value - delta)) if not all_deltas and (percentage < (footprint_threshold / 100.0)): continue logger.info("{:<25} {:<60} {}{}{}: {} {:<+4}, is now {:6} {:+.2%}".format( i.platform.name, i.testcase.name, Fore.YELLOW, "INFO" if all_deltas else "WARNING", Fore.RESET, metric, delta, value, percentage)) warnings += 1 if warnings: logger.warning("Deltas based on metrics from last %s" % ("release" if not last_metrics else "run")) def summary(self, results, unrecognized_sections): failed = 0 run = 0 for instance in self.instances.values(): if instance.status == "failed": failed += 1 elif instance.metrics.get("unrecognized") and not unrecognized_sections: logger.error("%sFAILED%s: %s has unrecognized binary sections: %s" % (Fore.RED, Fore.RESET, instance.name, str(instance.metrics.get("unrecognized", [])))) failed += 1 if instance.metrics.get('handler_time', None): run += 1 if results.total and results.total != results.skipped_configs: pass_rate = (float(results.passed) / float(results.total - results.skipped_configs)) else: pass_rate = 0 logger.info( "{}{} of {}{} test configurations passed ({:.2%}), {}{}{} failed, {} skipped with {}{}{} warnings in {:.2f} seconds".format( Fore.RED if failed else Fore.GREEN, results.passed, results.total - results.skipped_configs, Fore.RESET, pass_rate, Fore.RED if results.failed else Fore.RESET, results.failed, Fore.RESET, results.skipped_configs, Fore.YELLOW if self.warnings else Fore.RESET, self.warnings, Fore.RESET, self.duration)) self.total_platforms = len(self.platforms) # if we are only building, do not report about tests being executed. if self.platforms and not self.build_only: logger.info("In total {} test cases were executed, {} skipped on {} out of total {} platforms ({:02.2f}%)".format( results.cases - results.skipped_cases, results.skipped_cases, len(self.filtered_platforms), self.total_platforms, (100 * len(self.filtered_platforms) / len(self.platforms)) )) logger.info(f"{Fore.GREEN}{run}{Fore.RESET} test configurations executed on platforms, \ {Fore.RED}{results.total - run - results.skipped_configs}{Fore.RESET} test configurations were only built.") def save_reports(self, name, suffix, report_dir, no_update, release, only_failed, platform_reports, json_report): if not self.instances: return logger.info("Saving reports...") if name: report_name = name else: report_name = "twister" if report_dir: os.makedirs(report_dir, exist_ok=True) filename = os.path.join(report_dir, report_name) outdir = report_dir else: filename = os.path.join(self.outdir, report_name) outdir = self.outdir if suffix: filename = "{}_{}".format(filename, suffix) if not no_update: self.xunit_report(filename + ".xml", full_report=False, append=only_failed, version=self.version) self.xunit_report(filename + "_report.xml", full_report=True, append=only_failed, version=self.version) self.csv_report(filename + ".csv") if json_report: self.json_report(filename + ".json", append=only_failed, version=self.version) if platform_reports: self.target_report(outdir, suffix, append=only_failed) if self.discards: self.discard_report(filename + "_discard.csv") if release: self.csv_report(self.RELEASE_DATA) def add_configurations(self): for board_root in self.board_roots: board_root = os.path.abspath(board_root) logger.debug("Reading platform configuration files under %s..." % board_root) for file in glob.glob(os.path.join(board_root, "*", "*", "*.yaml")): try: platform = Platform() platform.load(file) if platform.name in [p.name for p in self.platforms]: logger.error(f"Duplicate platform {platform.name} in {file}") raise Exception(f"Duplicate platform identifier {platform.name} found") if platform.twister: self.platforms.append(platform) if platform.default: self.default_platforms.append(platform.name) except RuntimeError as e: logger.error("E: %s: can't load: %s" % (file, e)) self.load_errors += 1 def get_all_tests(self): tests = [] for _, tc in self.testcases.items(): for case in tc.cases: tests.append(case) return tests @staticmethod def get_toolchain(): toolchain_script = Path(ZEPHYR_BASE) / Path('cmake/verify-toolchain.cmake') result = CMake.run_cmake_script([toolchain_script, "FORMAT=json"]) try: if result['returncode']: raise TwisterRuntimeError("E: Variable ZEPHYR_TOOLCHAIN_VARIANT is not defined") except Exception as e: print(str(e)) sys.exit(2) toolchain = json.loads(result['stdout'])['ZEPHYR_TOOLCHAIN_VARIANT'] logger.info(f"Using '{toolchain}' toolchain.") return toolchain def add_testcases(self, testcase_filter=[]): for root in self.roots: root = os.path.abspath(root) logger.debug("Reading test case configuration files under %s..." % root) for dirpath, _, filenames in os.walk(root, topdown=True): if self.SAMPLE_FILENAME in filenames: filename = self.SAMPLE_FILENAME elif self.TESTCASE_FILENAME in filenames: filename = self.TESTCASE_FILENAME else: continue logger.debug("Found possible test case in " + dirpath) tc_path = os.path.join(dirpath, filename) try: parsed_data = TwisterConfigParser(tc_path, self.tc_schema) parsed_data.load() tc_path = os.path.dirname(tc_path) workdir = os.path.relpath(tc_path, root) for name in parsed_data.tests.keys(): tc = TestCase(root, workdir, name) tc_dict = parsed_data.get_test(name, self.testcase_valid_keys) tc.source_dir = tc_path tc.yamlfile = tc_path tc.type = tc_dict["type"] tc.tags = tc_dict["tags"] tc.extra_args = tc_dict["extra_args"] tc.extra_configs = tc_dict["extra_configs"] tc.arch_allow = tc_dict["arch_allow"] tc.arch_exclude = tc_dict["arch_exclude"] tc.skip = tc_dict["skip"] tc.platform_exclude = tc_dict["platform_exclude"] tc.platform_allow = tc_dict["platform_allow"] tc.toolchain_exclude = tc_dict["toolchain_exclude"] tc.toolchain_allow = tc_dict["toolchain_allow"] tc.tc_filter = tc_dict["filter"] tc.timeout = tc_dict["timeout"] tc.harness = tc_dict["harness"] tc.harness_config = tc_dict["harness_config"] if tc.harness == 'console' and not tc.harness_config: raise Exception('Harness config error: console harness defined without a configuration.') tc.build_only = tc_dict["build_only"] tc.build_on_all = tc_dict["build_on_all"] tc.slow = tc_dict["slow"] tc.min_ram = tc_dict["min_ram"] tc.depends_on = tc_dict["depends_on"] tc.min_flash = tc_dict["min_flash"] tc.extra_sections = tc_dict["extra_sections"] tc.integration_platforms = tc_dict["integration_platforms"] tc.parse_subcases(tc_path) if testcase_filter: if tc.name and tc.name in testcase_filter: self.testcases[tc.name] = tc else: self.testcases[tc.name] = tc except Exception as e: logger.error("%s: can't load (skipping): %s" % (tc_path, e)) self.load_errors += 1 return len(self.testcases) def get_platform(self, name): selected_platform = None for platform in self.platforms: if platform.name == name: selected_platform = platform break return selected_platform def load_quarantine(self, file): """ Loads quarantine list from the given yaml file. Creates a dictionary of all tests configurations (platform + scenario: comment) that shall be skipped due to quarantine """ # Load yaml into quarantine_yaml quarantine_yaml = scl.yaml_load_verify(file, self.quarantine_schema) # Create quarantine_list with a product of the listed # platforms and scenarios for each entry in quarantine yaml quarantine_list = [] for quar_dict in quarantine_yaml: if quar_dict['platforms'][0] == "all": plat = [p.name for p in self.platforms] else: plat = quar_dict['platforms'] comment = quar_dict.get('comment', "NA") quarantine_list.append([{".".join([p, s]): comment} for p in plat for s in quar_dict['scenarios']]) # Flatten the quarantine_list quarantine_list = [it for sublist in quarantine_list for it in sublist] # Change quarantine_list into a dictionary for d in quarantine_list: self.quarantine.update(d) def load_from_file(self, file, filter_status=[], filter_platform=[]): try: with open(file, "r") as fp: cr = csv.DictReader(fp) instance_list = [] for row in cr: if row["status"] in filter_status: continue test = row["test"] platform = self.get_platform(row["platform"]) if filter_platform and platform.name not in filter_platform: continue instance = TestInstance(self.testcases[test], platform, self.outdir) if self.device_testing: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) instance.create_overlay(platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) instance_list.append(instance) self.add_instances(instance_list) except KeyError as e: logger.error("Key error while parsing tests file.({})".format(str(e))) sys.exit(2) except FileNotFoundError as e: logger.error("Couldn't find input file with list of tests. ({})".format(e)) sys.exit(2) def apply_filters(self, **kwargs): toolchain = self.get_toolchain() discards = {} platform_filter = kwargs.get('platform') exclude_platform = kwargs.get('exclude_platform', []) testcase_filter = kwargs.get('run_individual_tests', []) arch_filter = kwargs.get('arch') tag_filter = kwargs.get('tag') exclude_tag = kwargs.get('exclude_tag') all_filter = kwargs.get('all') runnable = kwargs.get('runnable') force_toolchain = kwargs.get('force_toolchain') force_platform = kwargs.get('force_platform') emu_filter = kwargs.get('emulation_only') logger.debug("platform filter: " + str(platform_filter)) logger.debug(" arch_filter: " + str(arch_filter)) logger.debug(" tag_filter: " + str(tag_filter)) logger.debug(" exclude_tag: " + str(exclude_tag)) default_platforms = False emulation_platforms = False if all_filter: logger.info("Selecting all possible platforms per test case") # When --all used, any --platform arguments ignored platform_filter = [] elif not platform_filter and not emu_filter: logger.info("Selecting default platforms per test case") default_platforms = True elif emu_filter: logger.info("Selecting emulation platforms per test case") emulation_platforms = True if platform_filter: platforms = list(filter(lambda p: p.name in platform_filter, self.platforms)) elif emu_filter: platforms = list(filter(lambda p: p.simulation != 'na', self.platforms)) elif arch_filter: platforms = list(filter(lambda p: p.arch in arch_filter, self.platforms)) elif default_platforms: platforms = list(filter(lambda p: p.default, self.platforms)) else: platforms = self.platforms logger.info("Building initial testcase list...") for tc_name, tc in self.testcases.items(): if tc.build_on_all and not platform_filter: platform_scope = self.platforms elif tc.integration_platforms and self.integration: platform_scope = list(filter(lambda item: item.name in tc.integration_platforms, \ self.platforms)) else: platform_scope = platforms integration = self.integration and tc.integration_platforms # If there isn't any overlap between the platform_allow list and the platform_scope # we set the scope to the platform_allow list if tc.platform_allow and not platform_filter and not integration: a = set(platform_scope) b = set(filter(lambda item: item.name in tc.platform_allow, self.platforms)) c = a.intersection(b) if not c: platform_scope = list(filter(lambda item: item.name in tc.platform_allow, \ self.platforms)) # list of instances per testcase, aka configurations. instance_list = [] for plat in platform_scope: instance = TestInstance(tc, plat, self.outdir) if runnable: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) for t in tc.cases: instance.results[t] = None if runnable and self.duts: for h in self.duts: if h.platform == plat.name: if tc.harness_config.get('fixture') in h.fixtures: instance.run = True if not force_platform and plat.name in exclude_platform: discards[instance] = discards.get(instance, "Platform is excluded on command line.") if (plat.arch == "unit") != (tc.type == "unit"): # Discard silently continue if runnable and not instance.run: discards[instance] = discards.get(instance, "Not runnable on device") if self.integration and tc.integration_platforms and plat.name not in tc.integration_platforms: discards[instance] = discards.get(instance, "Not part of integration platforms") if tc.skip: discards[instance] = discards.get(instance, "Skip filter") if tag_filter and not tc.tags.intersection(tag_filter): discards[instance] = discards.get(instance, "Command line testcase tag filter") if exclude_tag and tc.tags.intersection(exclude_tag): discards[instance] = discards.get(instance, "Command line testcase exclude filter") if testcase_filter and tc_name not in testcase_filter: discards[instance] = discards.get(instance, "Testcase name filter") if arch_filter and plat.arch not in arch_filter: discards[instance] = discards.get(instance, "Command line testcase arch filter") if not force_platform: if tc.arch_allow and plat.arch not in tc.arch_allow: discards[instance] = discards.get(instance, "Not in test case arch allow list") if tc.arch_exclude and plat.arch in tc.arch_exclude: discards[instance] = discards.get(instance, "In test case arch exclude") if tc.platform_exclude and plat.name in tc.platform_exclude: discards[instance] = discards.get(instance, "In test case platform exclude") if tc.toolchain_exclude and toolchain in tc.toolchain_exclude: discards[instance] = discards.get(instance, "In test case toolchain exclude") if platform_filter and plat.name not in platform_filter: discards[instance] = discards.get(instance, "Command line platform filter") if tc.platform_allow and plat.name not in tc.platform_allow: discards[instance] = discards.get(instance, "Not in testcase platform allow list") if tc.toolchain_allow and toolchain not in tc.toolchain_allow: discards[instance] = discards.get(instance, "Not in testcase toolchain allow list") if not plat.env_satisfied: discards[instance] = discards.get(instance, "Environment ({}) not satisfied".format(", ".join(plat.env))) if not force_toolchain \ and toolchain and (toolchain not in plat.supported_toolchains) \ and tc.type != 'unit': discards[instance] = discards.get(instance, "Not supported by the toolchain") if plat.ram < tc.min_ram: discards[instance] = discards.get(instance, "Not enough RAM") if tc.depends_on: dep_intersection = tc.depends_on.intersection(set(plat.supported)) if dep_intersection != set(tc.depends_on): discards[instance] = discards.get(instance, "No hardware support") if plat.flash < tc.min_flash: discards[instance] = discards.get(instance, "Not enough FLASH") if set(plat.ignore_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (exclude_tags)") if plat.only_tags and not set(plat.only_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (only_tags)") test_configuration = ".".join([instance.platform.name, instance.testcase.id]) # skip quarantined tests if test_configuration in self.quarantine and not self.quarantine_verify: discards[instance] = discards.get(instance, f"Quarantine: {self.quarantine[test_configuration]}") # run only quarantined test to verify their statuses (skip everything else) if self.quarantine_verify and test_configuration not in self.quarantine: discards[instance] = discards.get(instance, "Not under quarantine") # if nothing stopped us until now, it means this configuration # needs to be added. instance_list.append(instance) # no configurations, so jump to next testcase if not instance_list: continue # if twister was launched with no platform options at all, we # take all default platforms if default_platforms and not tc.build_on_all and not integration: if tc.platform_allow: a = set(self.default_platforms) b = set(tc.platform_allow) c = a.intersection(b) if c: aa = list(filter(lambda tc: tc.platform.name in c, instance_list)) self.add_instances(aa) else: self.add_instances(instance_list) else: instances = list(filter(lambda tc: tc.platform.default, instance_list)) self.add_instances(instances) elif integration: instances = list(filter(lambda item: item.platform.name in tc.integration_platforms, instance_list)) self.add_instances(instances) elif emulation_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.simulation != 'na', instance_list)): discards[instance] = discards.get(instance, "Not an emulated platform") else: self.add_instances(instance_list) for _, case in self.instances.items(): case.create_overlay(case.platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) self.discards = discards self.selected_platforms = set(p.platform.name for p in self.instances.values()) for instance in self.discards: instance.reason = self.discards[instance] # If integration mode is on all skips on integration_platforms are treated as errors. # TODO: add quarantine relief here when PR with quarantine feature gets merged if self.integration and instance.platform.name in instance.testcase.integration_platforms: instance.status = "error" instance.reason += " but is one of the integration platforms" instance.fill_results_by_status() self.instances[instance.name] = instance else: instance.status = "skipped" instance.fill_results_by_status() self.filtered_platforms = set(p.platform.name for p in self.instances.values() if p.status != "skipped" ) return discards def add_instances(self, instance_list): for instance in instance_list: self.instances[instance.name] = instance @staticmethod def calc_one_elf_size(instance): if instance.status not in ["error", "failed", "skipped"]: if instance.platform.type != "native": size_calc = instance.calculate_sizes() instance.metrics["ram_size"] = size_calc.get_ram_size() instance.metrics["rom_size"] = size_calc.get_rom_size() instance.metrics["unrecognized"] = size_calc.unrecognized_sections() else: instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["unrecognized"] = [] instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 def add_tasks_to_queue(self, pipeline, build_only=False, test_only=False): for instance in self.instances.values(): if build_only: instance.run = False if test_only and instance.run: pipeline.put({"op": "run", "test": instance}) else: if instance.status not in ['passed', 'skipped', 'error']: logger.debug(f"adding {instance.name}") instance.status = None pipeline.put({"op": "cmake", "test": instance}) # If the instance got 'error' status before, proceed to the report stage if instance.status == "error": pipeline.put({"op": "report", "test": instance}) def pipeline_mgr(self, pipeline, done_queue, lock, results): while True: try: task = pipeline.get_nowait() except queue.Empty: break else: test = task['test'] pb = ProjectBuilder(self, test, lsan=self.enable_lsan, asan=self.enable_asan, ubsan=self.enable_ubsan, coverage=self.enable_coverage, extra_args=self.extra_args, device_testing=self.device_testing, cmake_only=self.cmake_only, cleanup=self.cleanup, valgrind=self.enable_valgrind, inline_logs=self.inline_logs, generator=self.generator, generator_cmd=self.generator_cmd, verbose=self.verbose, warnings_as_errors=self.warnings_as_errors, overflow_as_errors=self.overflow_as_errors ) pb.process(pipeline, done_queue, task, lock, results) return True def execute(self, pipeline, done, results): lock = Lock() logger.info("Adding tasks to the queue...") self.add_tasks_to_queue(pipeline, self.build_only, self.test_only) logger.info("Added initial list of jobs to queue") processes = [] for job in range(self.jobs): logger.debug(f"Launch process {job}") p = Process(target=self.pipeline_mgr, args=(pipeline, done, lock, results, )) processes.append(p) p.start() try: for p in processes: p.join() except KeyboardInterrupt: logger.info("Execution interrupted") for p in processes: p.terminate() # FIXME: This needs to move out. if self.enable_size_report and not self.cmake_only: # Parallelize size calculation executor = concurrent.futures.ThreadPoolExecutor(self.jobs) futures = [executor.submit(self.calc_one_elf_size, instance) for instance in self.instances.values()] concurrent.futures.wait(futures) else: for instance in self.instances.values(): instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 instance.metrics["unrecognized"] = [] return results def discard_report(self, filename): try: if not self.discards: raise TwisterRuntimeError("apply_filters() hasn't been run!") except Exception as e: logger.error(str(e)) sys.exit(2) with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "reason"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance, reason in sorted(self.discards.items()): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "reason": reason} cw.writerow(rowdict) def target_report(self, outdir, suffix, append=False): platforms = {inst.platform.name for _, inst in self.instances.items()} for platform in platforms: if suffix: filename = os.path.join(outdir,"{}_{}.xml".format(platform, suffix)) else: filename = os.path.join(outdir,"{}.xml".format(platform)) self.xunit_report(filename, platform, full_report=True, append=append, version=self.version) @staticmethod def process_log(log_file): filtered_string = "" if os.path.exists(log_file): with open(log_file, "rb") as f: log = f.read().decode("utf-8") filtered_string = ''.join(filter(lambda x: x in string.printable, log)) return filtered_string def xunit_report(self, filename, platform=None, full_report=False, append=False, version="NA"): total = 0 fails = passes = errors = skips = 0 if platform: selected = [platform] logger.info(f"Writing target report for {platform}...") else: logger.info(f"Writing xunit report {filename}...") selected = self.selected_platforms if os.path.exists(filename) and append: tree = ET.parse(filename) eleTestsuites = tree.getroot() else: eleTestsuites = ET.Element('testsuites') for p in selected: inst = self.get_platform_instances(p) fails = 0 passes = 0 errors = 0 skips = 0 duration = 0 for _, instance in inst.items(): handler_time = instance.metrics.get('handler_time', 0) duration += handler_time if full_report and instance.run: for k in instance.results.keys(): if instance.results[k] == 'PASS': passes += 1 elif instance.results[k] == 'BLOCK': errors += 1 elif instance.results[k] == 'SKIP' or instance.status in ['skipped']: skips += 1 else: fails += 1 else: if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.reason in ['build_error', 'handler_crash']: errors += 1 else: fails += 1 elif instance.status == 'skipped': skips += 1 elif instance.status == 'passed': passes += 1 else: if instance.status: logger.error(f"{instance.name}: Unknown status {instance.status}") else: logger.error(f"{instance.name}: No status") total = (errors + passes + fails + skips) # do not produce a report if no tests were actually run (only built) if total == 0: continue run = p eleTestsuite = None # When we re-run the tests, we re-use the results and update only with # the newly run tests. if os.path.exists(filename) and append: ts = eleTestsuites.findall(f'testsuite/[@name="{p}"]') if ts: eleTestsuite = ts[0] eleTestsuite.attrib['failures'] = "%d" % fails eleTestsuite.attrib['errors'] = "%d" % errors eleTestsuite.attrib['skipped'] = "%d" % skips else: logger.info(f"Did not find any existing results for {p}") eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) else: eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) for _, instance in inst.items(): if full_report: tname = os.path.basename(instance.testcase.name) else: tname = instance.testcase.id handler_time = instance.metrics.get('handler_time', 0) if full_report: for k in instance.results.keys(): # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@name="{k}"]'): eleTestsuite.remove(tc) classname = ".".join(tname.split(".")[:2]) eleTestcase = ET.SubElement( eleTestsuite, 'testcase', classname=classname, name="%s" % (k), time="%f" % handler_time) if instance.results[k] in ['FAIL', 'BLOCK'] or \ (not instance.run and instance.status in ["error", "failed", "timeout"]): if instance.results[k] == 'FAIL': el = ET.SubElement( eleTestcase, 'failure', type="failure", message="failed") else: el = ET.SubElement( eleTestcase, 'error', type="failure", message=instance.reason) log_root = os.path.join(self.outdir, instance.platform.name, instance.testcase.name) log_file = os.path.join(log_root, "handler.log") el.text = self.process_log(log_file) elif instance.results[k] == 'PASS' \ or (not instance.run and instance.status in ["passed"]): pass elif instance.results[k] == 'SKIP' or (instance.status in ["skipped"]): el = ET.SubElement(eleTestcase, 'skipped', type="skipped", message=instance.reason) else: el = ET.SubElement( eleTestcase, 'error', type="error", message=f"{instance.reason}") else: if platform: classname = ".".join(instance.testcase.name.split(".")[:2]) else: classname = p + ":" + ".".join(instance.testcase.name.split(".")[:2]) # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@classname="{classname}"][@name="{instance.testcase.name}"]'): eleTestsuite.remove(tc) eleTestcase = ET.SubElement(eleTestsuite, 'testcase', classname=classname, name="%s" % (instance.testcase.name), time="%f" % handler_time) if instance.status in ["error", "failed", "timeout", "flash_error"]: failure = ET.SubElement( eleTestcase, 'failure', type="failure", message=instance.reason) log_root = ("%s/%s/%s" % (self.outdir, instance.platform.name, instance.testcase.name)) bl = os.path.join(log_root, "build.log") hl = os.path.join(log_root, "handler.log") log_file = bl if instance.reason != 'Build error': if os.path.exists(hl): log_file = hl else: log_file = bl failure.text = self.process_log(log_file) elif instance.status == "skipped": ET.SubElement(eleTestcase, 'skipped', type="skipped", message="Skipped") result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) return fails, passes, errors, skips def csv_report(self, filename): with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "status", "extra_args", "handler", "handler_time", "ram_size", "rom_size"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance in self.instances.values(): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "extra_args": " ".join(instance.testcase.extra_args), "handler": instance.platform.simulation} rowdict["status"] = instance.status if instance.status not in ["error", "failed", "timeout"]: if instance.handler: rowdict["handler_time"] = instance.metrics.get("handler_time", 0) ram_size = instance.metrics.get("ram_size", 0) rom_size = instance.metrics.get("rom_size", 0) rowdict["ram_size"] = ram_size rowdict["rom_size"] = rom_size cw.writerow(rowdict) def json_report(self, filename, append=False, version="NA"): logger.info(f"Writing JSON report {filename}") report = {} selected = self.selected_platforms report["environment"] = {"os": os.name, "zephyr_version": version, "toolchain": self.get_toolchain() } json_data = {} if os.path.exists(filename) and append: with open(filename, 'r') as json_file: json_data = json.load(json_file) suites = json_data.get("testsuites", []) if suites: suite = suites[0] testcases = suite.get("testcases", []) else: suite = {} testcases = [] for p in selected: inst = self.get_platform_instances(p) for _, instance in inst.items(): testcase = {} handler_log = os.path.join(instance.build_dir, "handler.log") build_log = os.path.join(instance.build_dir, "build.log") device_log = os.path.join(instance.build_dir, "device.log") handler_time = instance.metrics.get('handler_time', 0) ram_size = instance.metrics.get ("ram_size", 0) rom_size = instance.metrics.get("rom_size",0) for k in instance.results.keys(): testcases = list(filter(lambda d: not (d.get('testcase') == k and d.get('platform') == p), testcases )) testcase = {"testcase": k, "arch": instance.platform.arch, "platform": p, } if ram_size: testcase["ram_size"] = ram_size if rom_size: testcase["rom_size"] = rom_size if instance.results[k] in ["PASS"]: testcase["status"] = "passed" if instance.handler: testcase["execution_time"] = handler_time elif instance.results[k] in ['FAIL', 'BLOCK'] or instance.status in ["error", "failed", "timeout"]: testcase["status"] = "failed" testcase["reason"] = instance.reason testcase["execution_time"] = handler_time if os.path.exists(handler_log): testcase["test_output"] = self.process_log(handler_log) elif os.path.exists(device_log): testcase["device_log"] = self.process_log(device_log) else: testcase["build_log"] = self.process_log(build_log) else: testcase["status"] = "skipped" testcase["reason"] = instance.reason testcases.append(testcase) suites = [ {"testcases": testcases} ] report["testsuites"] = suites with open(filename, "wt") as json_file: json.dump(report, json_file, indent=4, separators=(',',':')) def get_testcase(self, identifier): results = [] for _, tc in self.testcases.items(): for case in tc.cases: if case == identifier: results.append(tc) return results class CoverageTool: """ Base class for every supported coverage tool """ def __init__(self): self.gcov_tool = None self.base_dir = None @staticmethod def factory(tool): if tool == 'lcov': t = Lcov() elif tool == 'gcovr': t = Gcovr() else: logger.error("Unsupported coverage tool specified: {}".format(tool)) return None logger.debug(f"Select {tool} as the coverage tool...") return t @staticmethod def retrieve_gcov_data(intput_file): logger.debug("Working on %s" % intput_file) extracted_coverage_info = {} capture_data = False capture_complete = False with open(intput_file, 'r') as fp: for line in fp.readlines(): if re.search("GCOV_COVERAGE_DUMP_START", line): capture_data = True continue if re.search("GCOV_COVERAGE_DUMP_END", line): capture_complete = True break # Loop until the coverage data is found. if not capture_data: continue if line.startswith("*"): sp = line.split("<") if len(sp) > 1: # Remove the leading delimiter "*" file_name = sp[0][1:] # Remove the trailing new line char hex_dump = sp[1][:-1] else: continue else: continue extracted_coverage_info.update({file_name: hex_dump}) if not capture_data: capture_complete = True return {'complete': capture_complete, 'data': extracted_coverage_info} @staticmethod def create_gcda_files(extracted_coverage_info): logger.debug("Generating gcda files") for filename, hexdump_val in extracted_coverage_info.items(): # if kobject_hash is given for coverage gcovr fails # hence skipping it problem only in gcovr v4.1 if "kobject_hash" in filename: filename = (filename[:-4]) + "gcno" try: os.remove(filename) except Exception: pass continue with open(filename, 'wb') as fp: fp.write(bytes.fromhex(hexdump_val)) def generate(self, outdir): for filename in glob.glob("%s/**/handler.log" % outdir, recursive=True): gcov_data = self.__class__.retrieve_gcov_data(filename) capture_complete = gcov_data['complete'] extracted_coverage_info = gcov_data['data'] if capture_complete: self.__class__.create_gcda_files(extracted_coverage_info) logger.debug("Gcov data captured: {}".format(filename)) else: logger.error("Gcov data capture incomplete: {}".format(filename)) with open(os.path.join(outdir, "coverage.log"), "a") as coveragelog: ret = self._generate(outdir, coveragelog) if ret == 0: logger.info("HTML report generated: {}".format( os.path.join(outdir, "coverage", "index.html"))) class Lcov(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('*' + pattern + '*') def add_ignore_directory(self, pattern): self.ignores.append('*/' + pattern + '/*') def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.info") ztestfile = os.path.join(outdir, "ztest.info") cmd = ["lcov", "--gcov-tool", self.gcov_tool, "--capture", "--directory", outdir, "--rc", "lcov_branch_coverage=1", "--output-file", coveragefile] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--extract", coveragefile, os.path.join(self.base_dir, "tests", "ztest", "*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--remove", ztestfile, os.path.join(self.base_dir, "tests/ztest/test/*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) files = [coveragefile, ztestfile] else: files = [coveragefile] for i in self.ignores: subprocess.call( ["lcov", "--gcov-tool", self.gcov_tool, "--remove", coveragefile, i, "--output-file", coveragefile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) # The --ignore-errors source option is added to avoid it exiting due to # samples/application_development/external_lib/ return subprocess.call(["genhtml", "--legend", "--branch-coverage", "--ignore-errors", "source", "-output-directory", os.path.join(outdir, "coverage")] + files, stdout=coveragelog) class Gcovr(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('.*' + pattern + '.*') def add_ignore_directory(self, pattern): self.ignores.append(".*/" + pattern + '/.*') @staticmethod def _interleave_list(prefix, list): tuple_list = [(prefix, item) for item in list] return [item for sublist in tuple_list for item in sublist] def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.json") ztestfile = os.path.join(outdir, "ztest.json") excludes = Gcovr._interleave_list("-e", self.ignores) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-e", "tests/*"] + excludes + ["--json", "-o", coveragefile, outdir] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) subprocess.call(["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-f", "tests/ztest", "-e", "tests/ztest/test/*", "--json", "-o", ztestfile, outdir], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: files = [coveragefile, ztestfile] else: files = [coveragefile] subdir = os.path.join(outdir, "coverage") os.makedirs(subdir, exist_ok=True) tracefiles = self._interleave_list("--add-tracefile", files) return subprocess.call(["gcovr", "-r", self.base_dir, "--html", "--html-details"] + tracefiles + ["-o", os.path.join(subdir, "index.html")], stdout=coveragelog) class DUT(object): def __init__(self, id=None, serial=None, platform=None, product=None, serial_pty=None, connected=False, pre_script=None, post_script=None, post_flash_script=None, runner=None): self.serial = serial self.platform = platform self.serial_pty = serial_pty self._counter = Value("i", 0) self._available = Value("i", 1) self.connected = connected self.pre_script = pre_script self.id = id self.product = product self.runner = runner self.fixtures = [] self.post_flash_script = post_flash_script self.post_script = post_script self.pre_script = pre_script self.probe_id = None self.notes = None self.lock = Lock() self.match = False @property def available(self): with self._available.get_lock(): return self._available.value @available.setter def available(self, value): with self._available.get_lock(): self._available.value = value @property def counter(self): with self._counter.get_lock(): return self._counter.value @counter.setter def counter(self, value): with self._counter.get_lock(): self._counter.value = value def to_dict(self): d = {} exclude = ['_available', '_counter', 'match'] v = vars(self) for k in v.keys(): if k not in exclude and v[k]: d[k] = v[k] return d def __repr__(self): return f"<{self.platform} ({self.product}) on {self.serial}>" class HardwareMap: schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "hwmap-schema.yaml") manufacturer = [ 'ARM', 'SEGGER', 'MBED', 'STMicroelectronics', 'Atmel Corp.', 'Texas Instruments', 'Silicon Labs', 'NXP Semiconductors', 'Microchip Technology Inc.', 'FTDI', 'Digilent' ] runner_mapping = { 'pyocd': [ 'DAPLink CMSIS-DAP', 'MBED CMSIS-DAP' ], 'jlink': [ 'J-Link', 'J-Link OB' ], 'openocd': [ 'STM32 STLink', '^XDS110.*', 'STLINK-V3' ], 'dediprog': [ 'TTL232R-3V3', 'MCP2200 USB Serial Port Emulator' ] } def __init__(self): self.detected = [] self.duts = [] def add_device(self, serial, platform, pre_script, is_pty): device = DUT(platform=platform, connected=True, pre_script=pre_script) if is_pty: device.serial_pty = serial else: device.serial = serial self.duts.append(device) def load(self, map_file): hwm_schema = scl.yaml_load(self.schema_path) duts = scl.yaml_load_verify(map_file, hwm_schema) for dut in duts: pre_script = dut.get('pre_script') post_script = dut.get('post_script') post_flash_script = dut.get('post_flash_script') platform = dut.get('platform') id = dut.get('id') runner = dut.get('runner') serial = dut.get('serial') product = dut.get('product') fixtures = dut.get('fixtures', []) new_dut = DUT(platform=platform, product=product, runner=runner, id=id, serial=serial, connected=serial is not None, pre_script=pre_script, post_script=post_script, post_flash_script=post_flash_script) new_dut.fixtures = fixtures new_dut.counter = 0 self.duts.append(new_dut) def scan(self, persistent=False): from serial.tools import list_ports if persistent and platform.system() == 'Linux': # On Linux, /dev/serial/by-id provides symlinks to # '/dev/ttyACMx' nodes using names which are unique as # long as manufacturers fill out USB metadata nicely. # # This creates a map from '/dev/ttyACMx' device nodes # to '/dev/serial/by-id/usb-...' symlinks. The symlinks # go into the hardware map because they stay the same # even when the user unplugs / replugs the device. # # Some inexpensive USB/serial adapters don't result # in unique names here, though, so use of this feature # requires explicitly setting persistent=True. by_id = Path('/dev/serial/by-id') def readlink(link): return str((by_id / link).resolve()) persistent_map = {readlink(link): str(link) for link in by_id.iterdir()} else: persistent_map = {} serial_devices = list_ports.comports() logger.info("Scanning connected hardware...") for d in serial_devices: if d.manufacturer in self.manufacturer: # TI XDS110 can have multiple serial devices for a single board # assume endpoint 0 is the serial, skip all others if d.manufacturer == 'Texas Instruments' and not d.location.endswith('0'): continue s_dev = DUT(platform="unknown", id=d.serial_number, serial=persistent_map.get(d.device, d.device), product=d.product, runner='unknown') for runner, _ in self.runner_mapping.items(): products = self.runner_mapping.get(runner) if d.product in products: s_dev.runner = runner continue # Try regex matching for p in products: if re.match(p, d.product): s_dev.runner = runner s_dev.connected = True self.detected.append(s_dev) else: logger.warning("Unsupported device (%s): %s" % (d.manufacturer, d)) def save(self, hwm_file): # use existing map self.detected.sort(key=lambda x: x.serial or '') if os.path.exists(hwm_file): with open(hwm_file, 'r') as yaml_file: hwm = yaml.load(yaml_file, Loader=SafeLoader) if hwm: hwm.sort(key=lambda x: x['serial'] or '') # disconnect everything for h in hwm: h['connected'] = False h['serial'] = None for _detected in self.detected: for h in hwm: if _detected.id == h['id'] and _detected.product == h['product'] and not _detected.match: h['connected'] = True h['serial'] = _detected.serial _detected.match = True new_duts = list(filter(lambda d: not d.match, self.detected)) new = [] for d in new_duts: new.append(d.to_dict()) if hwm: hwm = hwm + new else: hwm = new with open(hwm_file, 'w') as yaml_file: yaml.dump(hwm, yaml_file, Dumper=Dumper, default_flow_style=False) self.load(hwm_file) logger.info("Registered devices:") self.dump() else: # create new file dl = [] for _connected in self.detected: platform = _connected.platform id = _connected.id runner = _connected.runner serial = _connected.serial product = _connected.product d = { 'platform': platform, 'id': id, 'runner': runner, 'serial': serial, 'product': product } dl.append(d) with open(hwm_file, 'w') as yaml_file: yaml.dump(dl, yaml_file, Dumper=Dumper, default_flow_style=False) logger.info("Detected devices:") self.dump(detected=True) def dump(self, filtered=[], header=[], connected_only=False, detected=False): print("") table = [] if detected: to_show = self.detected else: to_show = self.duts if not header: header = ["Platform", "ID", "Serial device"] for p in to_show: platform = p.platform connected = p.connected if filtered and platform not in filtered: continue if not connected_only or connected: table.append([platform, p.id, p.serial]) print(tabulate(table, headers=header, tablefmt="github"))
#!/usr/bin/env python # # Tests the German credit toy distribution. # # This file is part of PINTS. # Copyright (c) 2017-2019, University of Oxford. # For licensing information, see the LICENSE file distributed with the PINTS # software package. # import pints import pints.toy import unittest import numpy as np import io import urllib import urllib.request from scipy import stats class TestGermanCreditHierarchicalLogPDF(unittest.TestCase): """ Tests the logpdf toy distribution from fitting a hierarchical logistic model to German credit data. """ @classmethod def setUpClass(cls): """ Set up problem for tests. """ # download data url="http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data-numeric" # noqa with urllib.request.urlopen(url) as url: raw_data = url.read() a = np.genfromtxt(io.BytesIO(raw_data), delimiter=4)[:, :25] # get output y = a[:, -1] y[y == 1] = -1 y[y == 2] = 1 cls.y = y # get inputs and standardise x = a[:, :-1] x = stats.zscore(x) x1 = np.zeros((x.shape[0], x.shape[1] + 1)) x1[:, 0] = np.ones(x.shape[0]) x1[:, 1:] = x x = np.copy(x1) cls.x = x cls.model = pints.toy.GermanCreditHierarchicalLogPDF(x, y) def test_download(self): # tests that method can download data from UCI repo model = pints.toy.GermanCreditHierarchicalLogPDF(download=True) x, y, z = model.data() self.assertTrue(np.array_equal(x, self.x)) self.assertTrue(np.array_equal(y, self.y)) def test_errors(self): # tests errors of inapropriate function calls and inits self.assertRaises(ValueError, pints.toy.GermanCreditLogPDF, np.zeros((27, 27)), self.y) self.assertRaises(ValueError, pints.toy.GermanCreditLogPDF, self.x, np.ones(1000) * 2) self.assertRaises(ValueError, pints.toy.GermanCreditLogPDF, self.x, self.y, True) self.assertRaises(ValueError, pints.toy.GermanCreditLogPDF, None, self.y) self.assertRaises(ValueError, pints.toy.GermanCreditLogPDF, self.x, None) def test_values(self): # tests calls self.assertAlmostEqual(self.model(np.ones(326)), -20174.077700157857, places=6) def test_sensitivities(self): # test sensitivity values vs reference val, dp = self.model.evaluateS1(np.ones(326)) self.assertEqual(val, self.model(np.ones(326))) self.assertEqual(len(dp), 326) self.assertAlmostEqual(dp[0], -1000.02) self.assertAlmostEqual(dp[1], -700.8386959844057, places=6) def test_givens(self): # tests whether boundaries are correct and n_parameters self.assertEqual(326, self.model.n_parameters()) borders = self.model.suggested_bounds() self.assertEqual(borders[0][0], -100) self.assertEqual(borders[1][0], 100) if __name__ == '__main__': unittest.main() Update test_toy_german_credit_hierarchical_logpdf.py #!/usr/bin/env python # # Tests the German credit toy distribution. # # This file is part of PINTS. # Copyright (c) 2017-2019, University of Oxford. # For licensing information, see the LICENSE file distributed with the PINTS # software package. # import pints import pints.toy import unittest import numpy as np import io import urllib import urllib.request from scipy import stats class TestGermanCreditHierarchicalLogPDF(unittest.TestCase): """ Tests the logpdf toy distribution from fitting a hierarchical logistic model to German credit data. """ @classmethod def setUpClass(cls): """ Set up problem for tests. """ # download data url="http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data-numeric" # noqa with urllib.request.urlopen(url) as url: raw_data = url.read() a = np.genfromtxt(io.BytesIO(raw_data), delimiter=4)[:, :25] # get output y = a[:, -1] y[y == 1] = -1 y[y == 2] = 1 cls.y = y # get inputs and standardise x = a[:, :-1] x = stats.zscore(x) x1 = np.zeros((x.shape[0], x.shape[1] + 1)) x1[:, 0] = np.ones(x.shape[0]) x1[:, 1:] = x x = np.copy(x1) cls.x = x cls.model = pints.toy.GermanCreditHierarchicalLogPDF(x, y) def test_download(self): # tests that method can download data from UCI repo model = pints.toy.GermanCreditHierarchicalLogPDF(download=True) x, y, z = model.data() self.assertTrue(np.array_equal(x, self.x)) self.assertTrue(np.array_equal(y, self.y)) def test_errors(self): # tests errors of inapropriate function calls and inits self.assertRaises(ValueError, pints.toy.GermanCreditHierarchicalLogPDF, np.zeros((27, 27)), self.y) self.assertRaises(ValueError, pints.toy.GermanCreditHierarchicalLogPDF, self.x, np.ones(1000) * 2) self.assertRaises(ValueError, pints.toy.GermanCreditHierarchicalLogPDF, self.x, self.y, True) self.assertRaises(ValueError, pints.toy.GermanCreditHierarchicalLogPDF, None, self.y) self.assertRaises(ValueError, pints.toy.GermanCreditHierarchicalLogPDF, self.x, None) def test_values(self): # tests calls self.assertAlmostEqual(self.model(np.ones(326)), -20174.077700157857, places=6) def test_sensitivities(self): # test sensitivity values vs reference val, dp = self.model.evaluateS1(np.ones(326)) self.assertEqual(val, self.model(np.ones(326))) self.assertEqual(len(dp), 326) self.assertAlmostEqual(dp[0], -1000.02) self.assertAlmostEqual(dp[1], -700.8386959844057, places=6) def test_givens(self): # tests whether boundaries are correct and n_parameters self.assertEqual(326, self.model.n_parameters()) borders = self.model.suggested_bounds() self.assertEqual(borders[0][0], -100) self.assertEqual(borders[1][0], 100) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 - # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # # Copyright 2011 Cloudant, Inc. version_info = (0, 0, 8) __version__ = ".".join(map(str, version_info)) Bump version for release # -*- coding: utf-8 - # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # # Copyright 2011 Cloudant, Inc. version_info = (0, 0, 9) __version__ = ".".join(map(str, version_info))
#!/usr/bin/env python3 # vim: set syntax=python ts=4 : # # Copyright (c) 2018 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import contextlib import string import mmap import sys import re import subprocess import select import shutil import shlex import signal import threading import concurrent.futures from collections import OrderedDict import queue import time import csv import glob import concurrent import xml.etree.ElementTree as ET import logging import pty from pathlib import Path from distutils.spawn import find_executable from colorama import Fore import pickle import platform import yaml import json from multiprocessing import Lock, Process, Value try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import SafeLoader, Dumper try: import serial except ImportError: print("Install pyserial python module with pip to use --device-testing option.") try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") try: import psutil except ImportError: print("Install psutil python module with pip to run in Qemu.") ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") # This is needed to load edt.pickle files. sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts")) import edtlib # pylint: disable=unused-import # Use this for internal comparisons; that's what canonicalization is # for. Don't use it when invoking other components of the build system # to avoid confusing and hard to trace inconsistencies in error messages # and logs, generated Makefiles, etc. compared to when users invoke these # components directly. # Note "normalization" is different from canonicalization, see os.path. canonical_zephyr_base = os.path.realpath(ZEPHYR_BASE) sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import scl import expr_parser logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ExecutionCounter(object): def __init__(self, total=0): self._done = Value('i', 0) self._passed = Value('i', 0) self._skipped_configs = Value('i', 0) self._skipped_runtime = Value('i', 0) self._skipped_cases = Value('i', 0) self._error = Value('i', 0) self._failed = Value('i', 0) self._total = Value('i', total) self._cases = Value('i', 0) self.lock = Lock() @property def cases(self): with self._cases.get_lock(): return self._cases.value @cases.setter def cases(self, value): with self._cases.get_lock(): self._cases.value = value @property def skipped_cases(self): with self._skipped_cases.get_lock(): return self._skipped_cases.value @skipped_cases.setter def skipped_cases(self, value): with self._skipped_cases.get_lock(): self._skipped_cases.value = value @property def error(self): with self._error.get_lock(): return self._error.value @error.setter def error(self, value): with self._error.get_lock(): self._error.value = value @property def done(self): with self._done.get_lock(): return self._done.value @done.setter def done(self, value): with self._done.get_lock(): self._done.value = value @property def passed(self): with self._passed.get_lock(): return self._passed.value @passed.setter def passed(self, value): with self._passed.get_lock(): self._passed.value = value @property def skipped_configs(self): with self._skipped_configs.get_lock(): return self._skipped_configs.value @skipped_configs.setter def skipped_configs(self, value): with self._skipped_configs.get_lock(): self._skipped_configs.value = value @property def skipped_runtime(self): with self._skipped_runtime.get_lock(): return self._skipped_runtime.value @skipped_runtime.setter def skipped_runtime(self, value): with self._skipped_runtime.get_lock(): self._skipped_runtime.value = value @property def failed(self): with self._failed.get_lock(): return self._failed.value @failed.setter def failed(self, value): with self._failed.get_lock(): self._failed.value = value @property def total(self): with self._total.get_lock(): return self._total.value class CMakeCacheEntry: '''Represents a CMake cache entry. This class understands the type system in a CMakeCache.txt, and converts the following cache types to Python types: Cache Type Python type ---------- ------------------------------------------- FILEPATH str PATH str STRING str OR list of str (if ';' is in the value) BOOL bool INTERNAL str OR list of str (if ';' is in the value) ---------- ------------------------------------------- ''' # Regular expression for a cache entry. # # CMake variable names can include escape characters, allowing a # wider set of names than is easy to match with a regular # expression. To be permissive here, use a non-greedy match up to # the first colon (':'). This breaks if the variable name has a # colon inside, but it's good enough. CACHE_ENTRY = re.compile( r'''(?P<name>.*?) # name :(?P<type>FILEPATH|PATH|STRING|BOOL|INTERNAL) # type =(?P<value>.*) # value ''', re.X) @classmethod def _to_bool(cls, val): # Convert a CMake BOOL string into a Python bool. # # "True if the constant is 1, ON, YES, TRUE, Y, or a # non-zero number. False if the constant is 0, OFF, NO, # FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in # the suffix -NOTFOUND. Named boolean constants are # case-insensitive. If the argument is not one of these # constants, it is treated as a variable." # # https://cmake.org/cmake/help/v3.0/command/if.html val = val.upper() if val in ('ON', 'YES', 'TRUE', 'Y'): return 1 elif val in ('OFF', 'NO', 'FALSE', 'N', 'IGNORE', 'NOTFOUND', ''): return 0 elif val.endswith('-NOTFOUND'): return 0 else: try: v = int(val) return v != 0 except ValueError as exc: raise ValueError('invalid bool {}'.format(val)) from exc @classmethod def from_line(cls, line, line_no): # Comments can only occur at the beginning of a line. # (The value of an entry could contain a comment character). if line.startswith('//') or line.startswith('#'): return None # Whitespace-only lines do not contain cache entries. if not line.strip(): return None m = cls.CACHE_ENTRY.match(line) if not m: return None name, type_, value = (m.group(g) for g in ('name', 'type', 'value')) if type_ == 'BOOL': try: value = cls._to_bool(value) except ValueError as exc: args = exc.args + ('on line {}: {}'.format(line_no, line),) raise ValueError(args) from exc elif type_ in ['STRING', 'INTERNAL']: # If the value is a CMake list (i.e. is a string which # contains a ';'), convert to a Python list. if ';' in value: value = value.split(';') return CMakeCacheEntry(name, value) def __init__(self, name, value): self.name = name self.value = value def __str__(self): fmt = 'CMakeCacheEntry(name={}, value={})' return fmt.format(self.name, self.value) class CMakeCache: '''Parses and represents a CMake cache file.''' @staticmethod def from_file(cache_file): return CMakeCache(cache_file) def __init__(self, cache_file): self.cache_file = cache_file self.load(cache_file) def load(self, cache_file): entries = [] with open(cache_file, 'r') as cache: for line_no, line in enumerate(cache): entry = CMakeCacheEntry.from_line(line, line_no) if entry: entries.append(entry) self._entries = OrderedDict((e.name, e) for e in entries) def get(self, name, default=None): entry = self._entries.get(name) if entry is not None: return entry.value else: return default def get_list(self, name, default=None): if default is None: default = [] entry = self._entries.get(name) if entry is not None: value = entry.value if isinstance(value, list): return value elif isinstance(value, str): return [value] if value else [] else: msg = 'invalid value {} type {}' raise RuntimeError(msg.format(value, type(value))) else: return default def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name].value def __setitem__(self, name, entry): if not isinstance(entry, CMakeCacheEntry): msg = 'improper type {} for value {}, expecting CMakeCacheEntry' raise TypeError(msg.format(type(entry), entry)) self._entries[name] = entry def __delitem__(self, name): del self._entries[name] def __iter__(self): return iter(self._entries.values()) class TwisterException(Exception): pass class TwisterRuntimeError(TwisterException): pass class ConfigurationError(TwisterException): def __init__(self, cfile, message): TwisterException.__init__(self, cfile + ": " + message) class BuildError(TwisterException): pass class ExecutionError(TwisterException): pass class HarnessImporter: def __init__(self, name): sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister")) module = __import__("harness") if name: my_class = getattr(module, name) else: my_class = getattr(module, "Test") self.instance = my_class() class Handler: def __init__(self, instance, type_str="build"): """Constructor """ self.state = "waiting" self.run = False self.duration = 0 self.type_str = type_str self.binary = None self.pid_fn = None self.call_make_run = False self.name = instance.name self.instance = instance self.timeout = instance.testcase.timeout self.sourcedir = instance.testcase.source_dir self.build_dir = instance.build_dir self.log = os.path.join(self.build_dir, "handler.log") self.returncode = 0 self.set_state("running", self.duration) self.generator = None self.generator_cmd = None self.args = [] def set_state(self, state, duration): self.state = state self.duration = duration def get_state(self): ret = (self.state, self.duration) return ret def record(self, harness): if harness.recording: filename = os.path.join(self.build_dir, "recording.csv") with open(filename, "at") as csvfile: cw = csv.writer(csvfile, harness.fieldnames, lineterminator=os.linesep) cw.writerow(harness.fieldnames) for instance in harness.recording: cw.writerow(instance) class BinaryHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.terminated = False self.call_west_flash = False # Tool options self.valgrind = False self.lsan = False self.asan = False self.ubsan = False self.coverage = False def try_kill_process_by_pid(self): if self.pid_fn: pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) self.pid_fn = None # clear so we don't try to kill the binary twice try: os.kill(pid, signal.SIGTERM) except ProcessLookupError: pass def terminate(self, proc): # encapsulate terminate functionality so we do it consistently where ever # we might want to terminate the proc. We need try_kill_process_by_pid # because of both how newer ninja (1.6.0 or greater) and .NET / renode # work. Newer ninja's don't seem to pass SIGTERM down to the children # so we need to use try_kill_process_by_pid. for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except ProcessLookupError: pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() self.terminated = True def _output_reader(self, proc): self.line = proc.stdout.readline() def _output_handler(self, proc, harness): log_out_fp = open(self.log, "wt") timeout_extended = False timeout_time = time.time() + self.timeout while True: this_timeout = timeout_time - time.time() if this_timeout < 0: break reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(this_timeout) if not reader_t.is_alive(): line = self.line logger.debug("OUTPUT: {0}".format(line.decode('utf-8').rstrip())) log_out_fp.write(line.decode('utf-8')) log_out_fp.flush() harness.handle(line.decode('utf-8').rstrip()) if harness.state: if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 else: reader_t.join(0) break try: # POSIX arch based ztests end on their own, # so let's give it up to 100ms to do so proc.wait(0.1) except subprocess.TimeoutExpired: self.terminate(proc) log_out_fp.close() def handle(self): harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) if self.call_make_run: command = [self.generator_cmd, "run"] elif self.call_west_flash: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] else: command = [self.binary] run_valgrind = False if self.valgrind and shutil.which("valgrind"): command = ["valgrind", "--error-exitcode=2", "--leak-check=full", "--suppressions=" + ZEPHYR_BASE + "/scripts/valgrind.supp", "--log-file=" + self.build_dir + "/valgrind.log" ] + command run_valgrind = True logger.debug("Spawning process: " + " ".join(shlex.quote(word) for word in command) + os.linesep + "in directory: " + self.build_dir) start_time = time.time() env = os.environ.copy() if self.asan: env["ASAN_OPTIONS"] = "log_path=stdout:" + \ env.get("ASAN_OPTIONS", "") if not self.lsan: env["ASAN_OPTIONS"] += "detect_leaks=0" if self.ubsan: env["UBSAN_OPTIONS"] = "log_path=stdout:halt_on_error=1:" + \ env.get("UBSAN_OPTIONS", "") with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir, env=env) as proc: logger.debug("Spawning BinaryHandler Thread for %s" % self.name) t = threading.Thread(target=self._output_handler, args=(proc, harness,), daemon=True) t.start() t.join() if t.is_alive(): self.terminate(proc) t.join() proc.wait() self.returncode = proc.returncode self.try_kill_process_by_pid() handler_time = time.time() - start_time if self.coverage: subprocess.call(["GCOV_PREFIX=" + self.build_dir, "gcov", self.sourcedir, "-b", "-s", self.build_dir], shell=True) # FIXME: This is needed when killing the simulator, the console is # garbled and needs to be reset. Did not find a better way to do that. if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) self.instance.results = harness.tests if not self.terminated and self.returncode != 0: # When a process is killed, the default handler returns 128 + SIGTERM # so in that case the return code itself is not meaningful self.set_state("failed", handler_time) self.instance.reason = "Failed" elif run_valgrind and self.returncode == 2: self.set_state("failed", handler_time) self.instance.reason = "Valgrind error" elif harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state("timeout", handler_time) self.instance.reason = "Timeout" self.record(harness) class DeviceHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.suite = None def monitor_serial(self, ser, halt_fileno, harness): log_out_fp = open(self.log, "wt") ser_fileno = ser.fileno() readlist = [halt_fileno, ser_fileno] if self.coverage: # Set capture_coverage to True to indicate that right after # test results we should get coverage data, otherwise we exit # from the test. harness.capture_coverage = True ser.flush() while ser.isOpen(): readable, _, _ = select.select(readlist, [], [], self.timeout) if halt_fileno in readable: logger.debug('halted') ser.close() break if ser_fileno not in readable: continue # Timeout. serial_line = None try: serial_line = ser.readline() except TypeError: pass except serial.SerialException: ser.close() break # Just because ser_fileno has data doesn't mean an entire line # is available yet. if serial_line: sl = serial_line.decode('utf-8', 'ignore').lstrip() logger.debug("DEVICE: {0}".format(sl.rstrip())) log_out_fp.write(sl) log_out_fp.flush() harness.handle(sl.rstrip()) if harness.state: if not harness.capture_coverage: ser.close() break log_out_fp.close() def get_available_device(self, instance): device = instance.platform.name for d in self.suite.duts: if d.platform == device and d.available and (d.serial or d.serial_pty): d.available = 0 d.counter += 1 return d return None def device_is_available(self, instance): device = instance.platform.name fixture = instance.testcase.harness_config.get("fixture") for d in self.suite.duts: if fixture and fixture not in d.fixtures: continue if d.platform == device and d.available and (d.serial or d.serial_pty): d.available = 0 d.counter += 1 return d return None def make_device_available(self, serial): for d in self.suite.duts: if d.serial == serial or d.serial_pty: d.available = 1 @staticmethod def run_custom_script(script, timeout): with subprocess.Popen(script, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, _ = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) except subprocess.TimeoutExpired: proc.kill() proc.communicate() logger.error("{} timed out".format(script)) def handle(self): out_state = "failed" runner = None hardware = self.device_is_available(self.instance) while not hardware: logger.debug("Waiting for device {} to become available".format(self.instance.platform.name)) time.sleep(1) hardware = self.device_is_available(self.instance) runner = hardware.runner or self.suite.west_runner serial_pty = hardware.serial_pty ser_pty_process = None if serial_pty: master, slave = pty.openpty() try: ser_pty_process = subprocess.Popen(re.split(',| ', serial_pty), stdout=master, stdin=master, stderr=master) except subprocess.CalledProcessError as error: logger.error("Failed to run subprocess {}, error {}".format(serial_pty, error.output)) return serial_device = os.ttyname(slave) else: serial_device = hardware.serial logger.debug("Using serial device {}".format(serial_device)) if (self.suite.west_flash is not None) or runner: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] command_extra_args = [] # There are three ways this option is used. # 1) bare: --west-flash # This results in options.west_flash == [] # 2) with a value: --west-flash="--board-id=42" # This results in options.west_flash == "--board-id=42" # 3) Multiple values: --west-flash="--board-id=42,--erase" # This results in options.west_flash == "--board-id=42 --erase" if self.suite.west_flash and self.suite.west_flash != []: command_extra_args.extend(self.suite.west_flash.split(',')) if runner: command.append("--runner") command.append(runner) board_id = hardware.probe_id or hardware.id product = hardware.product if board_id is not None: if runner == "pyocd": command_extra_args.append("--board-id") command_extra_args.append(board_id) elif runner == "nrfjprog": command_extra_args.append("--snr") command_extra_args.append(board_id) elif runner == "openocd" and product == "STM32 STLink": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "STLINK-V3": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "EDBG CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("cmsis_dap_serial %s" % (board_id)) elif runner == "jlink": command.append("--tool-opt=-SelectEmuBySN %s" % (board_id)) if command_extra_args != []: command.append('--') command.extend(command_extra_args) else: command = [self.generator_cmd, "-C", self.build_dir, "flash"] pre_script = hardware.pre_script post_flash_script = hardware.post_flash_script post_script = hardware.post_script if pre_script: self.run_custom_script(pre_script, 30) try: ser = serial.Serial( serial_device, baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=self.timeout ) except serial.SerialException as e: self.set_state("failed", 0) self.instance.reason = "Failed" logger.error("Serial device error: %s" % (str(e))) if serial_pty and ser_pty_process: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) self.make_device_available(serial_device) return ser.flush() harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) read_pipe, write_pipe = os.pipe() start_time = time.time() t = threading.Thread(target=self.monitor_serial, daemon=True, args=(ser, read_pipe, harness)) t.start() d_log = "{}/device.log".format(self.instance.build_dir) logger.debug('Flash command: %s', command) try: stdout = stderr = None with subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: (stdout, stderr) = proc.communicate(timeout=30) logger.debug(stdout.decode()) if proc.returncode != 0: self.instance.reason = "Device issue (Flash?)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.TimeoutExpired: proc.kill() (stdout, stderr) = proc.communicate() self.instance.reason = "Device issue (Timeout)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.CalledProcessError: os.write(write_pipe, b'x') # halt the thread if post_flash_script: self.run_custom_script(post_flash_script, 30) t.join(self.timeout) if t.is_alive(): logger.debug("Timed out while monitoring serial output on {}".format(self.instance.platform.name)) out_state = "timeout" if ser.isOpen(): ser.close() if serial_pty: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) os.close(write_pipe) os.close(read_pipe) handler_time = time.time() - start_time if out_state == "timeout": for c in self.instance.testcase.cases: if c not in harness.tests: harness.tests[c] = "BLOCK" self.instance.reason = "Timeout" self.instance.results = harness.tests # sometimes a test instance hasn't been executed successfully with an # empty dictionary results, in order to include it into final report, # so fill the results as BLOCK if self.instance.results == {}: for k in self.instance.testcase.cases: self.instance.results[k] = 'BLOCK' if harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state(out_state, handler_time) if post_script: self.run_custom_script(post_script, 30) self.make_device_available(serial_device) self.record(harness) class QEMUHandler(Handler): """Spawns a thread to monitor QEMU output from pipes We pass QEMU_PIPE to 'make run' and monitor the pipes for output. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") if "ignore_qemu_crash" in instance.testcase.tags: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process exection time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results, harness, ignore_unexpected_eof=False): fifo_in = fifo_fn + ".in" fifo_out = fifo_fn + ".out" # These in/out nodes are named from QEMU's perspective, not ours if os.path.exists(fifo_in): os.unlink(fifo_in) os.mkfifo(fifo_in) if os.path.exists(fifo_out): os.unlink(fifo_out) os.mkfifo(fifo_out) # We don't do anything with out_fp but we need to open it for # writing so that QEMU doesn't block, due to the way pipes work out_fp = open(fifo_in, "wb") # Disable internal buffering, we don't # want read() or poll() to ever block if there is data in there in_fp = open(fifo_out, "rb", buffering=0) log_out_fp = open(logfile, "wt") start_time = time.time() timeout_time = start_time + timeout p = select.poll() p.register(in_fp, select.POLLIN) out_state = None line = "" timeout_extended = False pid = 0 if os.path.exists(pid_fn): pid = int(open(pid_fn).read()) while True: this_timeout = int((timeout_time - time.time()) * 1000) if this_timeout < 0 or not p.poll(this_timeout): try: if pid and this_timeout > 0: #there's possibility we polled nothing because #of not enough CPU time scheduled by host for #QEMU process during p.poll(this_timeout) cpu_time = QEMUHandler._get_cpu_time(pid) if cpu_time < timeout and not out_state: timeout_time = time.time() + (timeout - cpu_time) continue except ProcessLookupError: out_state = "failed" break if not out_state: out_state = "timeout" break if pid == 0 and os.path.exists(pid_fn): pid = int(open(pid_fn).read()) try: c = in_fp.read(1).decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail out_state = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: out_state = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(line) log_out_fp.flush() line = line.strip() logger.debug(f"QEMU ({pid}): {line}") harness.handle(line) if harness.state: # if we have registered a fail make sure the state is not # overridden by a false success message coming from the # testsuite if out_state not in ['failed', 'unexpected eof', 'unexpected byte']: out_state = harness.state # if we get some state, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" handler.record(harness) handler_time = time.time() - start_time logger.debug(f"QEMU ({pid}) complete ({out_state}) after {handler_time} seconds") if out_state == "timeout": handler.instance.reason = "Timeout" handler.set_state("failed", handler_time) elif out_state == "failed": handler.instance.reason = "Failed" handler.set_state("failed", handler_time) elif out_state in ['unexpected eof', 'unexpected byte']: handler.instance.reason = out_state handler.set_state("failed", handler_time) else: handler.set_state(out_state, handler_time) log_out_fp.close() out_fp.close() in_fp.close() if pid: try: if pid: os.kill(pid, signal.SIGTERM) except ProcessLookupError: # Oh well, as long as it's dead! User probably sent Ctrl-C pass os.unlink(fifo_in) os.unlink(fifo_out) def handle(self): self.results = {} self.run = True # We pass this to QEMU which looks for fifos with .in and .out # suffixes. self.fifo_fn = os.path.join(self.instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(self.instance.build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log harness_import = HarnessImporter(self.instance.testcase.harness.capitalize()) harness = harness_import.instance harness.configure(self.instance) self.thread = threading.Thread(name=self.name, target=QEMUHandler._thread, args=(self, self.timeout, self.build_dir, self.log_fn, self.fifo_fn, self.pid_fn, self.results, harness, self.ignore_unexpected_eof)) self.instance.results = harness.tests self.thread.daemon = True logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread.start() if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) logger.debug("Running %s (%s)" % (self.name, self.type_str)) command = [self.generator_cmd] command += ["-C", self.build_dir, "run"] is_timeout = False qemu_pid = None with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) try: proc.wait(self.timeout) except subprocess.TimeoutExpired: # sometimes QEMU can't handle SIGTERM signal correctly # in that case kill -9 QEMU process directly and leave # twister to judge testing result by console output is_timeout = True if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) try: os.kill(qemu_pid, signal.SIGKILL) except ProcessLookupError: pass proc.wait() if harness.state == "passed": self.returncode = 0 else: self.returncode = proc.returncode else: proc.terminate() proc.kill() self.returncode = proc.returncode else: if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) logger.debug(f"No timeout, return code from QEMU ({qemu_pid}): {proc.returncode}") self.returncode = proc.returncode # Need to wait for harness to finish processing # output from QEMU. Otherwise it might miss some # error messages. self.thread.join() if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({qemu_pid}): {self.returncode}") if (self.returncode != 0 and not self.ignore_qemu_crash) or not harness.state: self.set_state("failed", 0) if is_timeout: self.instance.reason = "Timeout" else: self.instance.reason = "Exited with {}".format(self.returncode) def get_fifo(self): return self.fifo_fn class SizeCalculator: alloc_sections = [ "bss", "noinit", "app_bss", "app_noinit", "ccm_bss", "ccm_noinit" ] rw_sections = [ "datas", "initlevel", "exceptions", "initshell", "_static_thread_data_area", "k_timer_area", "k_mem_slab_area", "k_mem_pool_area", "sw_isr_table", "k_sem_area", "k_mutex_area", "app_shmem_regions", "_k_fifo_area", "_k_lifo_area", "k_stack_area", "k_msgq_area", "k_mbox_area", "k_pipe_area", "net_if_area", "net_if_dev_area", "net_l2_area", "net_l2_data", "k_queue_area", "_net_buf_pool_area", "app_datas", "kobject_data", "mmu_tables", "app_pad", "priv_stacks", "ccm_data", "usb_descriptor", "usb_data", "usb_bos_desc", "uart_mux", 'log_backends_sections', 'log_dynamic_sections', 'log_const_sections', "app_smem", 'shell_root_cmds_sections', 'log_const_sections', "font_entry_sections", "priv_stacks_noinit", "_GCOV_BSS_SECTION_NAME", "gcov", "nocache", "devices", "k_heap_area", ] # These get copied into RAM only on non-XIP ro_sections = [ "rom_start", "text", "ctors", "init_array", "reset", "z_object_assignment_area", "rodata", "net_l2", "vector", "sw_isr_table", "settings_handler_static_area", "bt_l2cap_fixed_chan_area", "bt_l2cap_br_fixed_chan_area", "bt_gatt_service_static_area", "vectors", "net_socket_register_area", "net_ppp_proto", "shell_area", "tracing_backend_area", "ppp_protocol_handler_area", ] def __init__(self, filename, extra_sections): """Constructor @param filename Path to the output binary The <filename> is parsed by objdump to determine section sizes """ # Make sure this is an ELF binary with open(filename, "rb") as f: magic = f.read(4) try: if magic != b'\x7fELF': raise TwisterRuntimeError("%s is not an ELF binary" % filename) except Exception as e: print(str(e)) sys.exit(2) # Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK. # GREP can not be used as it returns an error if the symbol is not # found. is_xip_command = "nm " + filename + \ " | awk '/CONFIG_XIP/ { print $3 }'" is_xip_output = subprocess.check_output( is_xip_command, shell=True, stderr=subprocess.STDOUT).decode( "utf-8").strip() try: if is_xip_output.endswith("no symbols"): raise TwisterRuntimeError("%s has no symbol information" % filename) except Exception as e: print(str(e)) sys.exit(2) self.is_xip = (len(is_xip_output) != 0) self.filename = filename self.sections = [] self.rom_size = 0 self.ram_size = 0 self.extra_sections = extra_sections self._calculate_sizes() def get_ram_size(self): """Get the amount of RAM the application will use up on the device @return amount of RAM, in bytes """ return self.ram_size def get_rom_size(self): """Get the size of the data that this application uses on device's flash @return amount of ROM, in bytes """ return self.rom_size def unrecognized_sections(self): """Get a list of sections inside the binary that weren't recognized @return list of unrecognized section names """ slist = [] for v in self.sections: if not v["recognized"]: slist.append(v["name"]) return slist def _calculate_sizes(self): """ Calculate RAM and ROM usage by section """ objdump_command = "objdump -h " + self.filename objdump_output = subprocess.check_output( objdump_command, shell=True).decode("utf-8").splitlines() for line in objdump_output: words = line.split() if not words: # Skip lines that are too short continue index = words[0] if not index[0].isdigit(): # Skip lines that do not start continue # with a digit name = words[1] # Skip lines with section names if name[0] == '.': # starting with '.' continue # TODO this doesn't actually reflect the size in flash or RAM as # it doesn't include linker-imposed padding between sections. # It is close though. size = int(words[2], 16) if size == 0: continue load_addr = int(words[4], 16) virt_addr = int(words[3], 16) # Add section to memory use totals (for both non-XIP and XIP scenarios) # Unrecognized section names are not included in the calculations. recognized = True if name in SizeCalculator.alloc_sections: self.ram_size += size stype = "alloc" elif name in SizeCalculator.rw_sections: self.ram_size += size self.rom_size += size stype = "rw" elif name in SizeCalculator.ro_sections: self.rom_size += size if not self.is_xip: self.ram_size += size stype = "ro" else: stype = "unknown" if name not in self.extra_sections: recognized = False self.sections.append({"name": name, "load_addr": load_addr, "size": size, "virt_addr": virt_addr, "type": stype, "recognized": recognized}) class TwisterConfigParser: """Class to read test case files with semantic checking """ def __init__(self, filename, schema): """Instantiate a new TwisterConfigParser object @param filename Source .yaml file to read """ self.data = {} self.schema = schema self.filename = filename self.tests = {} self.common = {} def load(self): self.data = scl.yaml_load_verify(self.filename, self.schema) if 'tests' in self.data: self.tests = self.data['tests'] if 'common' in self.data: self.common = self.data['common'] def _cast_value(self, value, typestr): if isinstance(value, str): v = value.strip() if typestr == "str": return v elif typestr == "float": return float(value) elif typestr == "int": return int(value) elif typestr == "bool": return value elif typestr.startswith("list") and isinstance(value, list): return value elif typestr.startswith("list") and isinstance(value, str): vs = v.split() if len(typestr) > 4 and typestr[4] == ":": return [self._cast_value(vsi, typestr[5:]) for vsi in vs] else: return vs elif typestr.startswith("set"): vs = v.split() if len(typestr) > 3 and typestr[3] == ":": return {self._cast_value(vsi, typestr[4:]) for vsi in vs} else: return set(vs) elif typestr.startswith("map"): return value else: raise ConfigurationError( self.filename, "unknown type '%s'" % value) def get_test(self, name, valid_keys): """Get a dictionary representing the keys/values within a test @param name The test in the .yaml file to retrieve data from @param valid_keys A dictionary representing the intended semantics for this test. Each key in this dictionary is a key that could be specified, if a key is given in the .yaml file which isn't in here, it will generate an error. Each value in this dictionary is another dictionary containing metadata: "default" - Default value if not given "type" - Data type to convert the text value to. Simple types supported are "str", "float", "int", "bool" which will get converted to respective Python data types. "set" and "list" may also be specified which will split the value by whitespace (but keep the elements as strings). finally, "list:<type>" and "set:<type>" may be given which will perform a type conversion after splitting the value up. "required" - If true, raise an error if not defined. If false and "default" isn't specified, a type conversion will be done on an empty string @return A dictionary containing the test key-value pairs with type conversion and default values filled in per valid_keys """ d = {} for k, v in self.common.items(): d[k] = v for k, v in self.tests[name].items(): if k in d: if isinstance(d[k], str): # By default, we just concatenate string values of keys # which appear both in "common" and per-test sections, # but some keys are handled in adhoc way based on their # semantics. if k == "filter": d[k] = "(%s) and (%s)" % (d[k], v) else: d[k] += " " + v else: d[k] = v for k, kinfo in valid_keys.items(): if k not in d: if "required" in kinfo: required = kinfo["required"] else: required = False if required: raise ConfigurationError( self.filename, "missing required value for '%s' in test '%s'" % (k, name)) else: if "default" in kinfo: default = kinfo["default"] else: default = self._cast_value("", kinfo["type"]) d[k] = default else: try: d[k] = self._cast_value(d[k], kinfo["type"]) except ValueError: raise ConfigurationError( self.filename, "bad %s value '%s' for key '%s' in name '%s'" % (kinfo["type"], d[k], k, name)) return d class Platform: """Class representing metadata for a particular platform Maps directly to BOARD when building""" platform_schema = scl.yaml_load(os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "platform-schema.yaml")) def __init__(self): """Constructor. """ self.name = "" self.twister = True # if no RAM size is specified by the board, take a default of 128K self.ram = 128 self.ignore_tags = [] self.only_tags = [] self.default = False # if no flash size is specified by the board, take a default of 512K self.flash = 512 self.supported = set() self.arch = "" self.type = "na" self.simulation = "na" self.supported_toolchains = [] self.env = [] self.env_satisfied = True self.filter_data = dict() def load(self, platform_file): scp = TwisterConfigParser(platform_file, self.platform_schema) scp.load() data = scp.data self.name = data['identifier'] self.twister = data.get("twister", True) # if no RAM size is specified by the board, take a default of 128K self.ram = data.get("ram", 128) testing = data.get("testing", {}) self.ignore_tags = testing.get("ignore_tags", []) self.only_tags = testing.get("only_tags", []) self.default = testing.get("default", False) # if no flash size is specified by the board, take a default of 512K self.flash = data.get("flash", 512) self.supported = set() for supp_feature in data.get("supported", []): for item in supp_feature.split(":"): self.supported.add(item) self.arch = data['arch'] self.type = data.get('type', "na") self.simulation = data.get('simulation', "na") self.supported_toolchains = data.get("toolchain", []) self.env = data.get("env", []) self.env_satisfied = True for env in self.env: if not os.environ.get(env, None): self.env_satisfied = False def __repr__(self): return "<%s on %s>" % (self.name, self.arch) class DisablePyTestCollectionMixin(object): __test__ = False class TestCase(DisablePyTestCollectionMixin): """Class representing a test application """ def __init__(self, testcase_root, workdir, name): """TestCase constructor. This gets called by TestSuite as it finds and reads test yaml files. Multiple TestCase instances may be generated from a single testcase.yaml, each one corresponds to an entry within that file. We need to have a unique name for every single test case. Since a testcase.yaml can define multiple tests, the canonical name for the test case is <workdir>/<name>. @param testcase_root os.path.abspath() of one of the --testcase-root @param workdir Sub-directory of testcase_root where the .yaml test configuration file was found @param name Name of this test case, corresponding to the entry name in the test case configuration file. For many test cases that just define one test, can be anything and is usually "test". This is really only used to distinguish between different cases when the testcase.yaml defines multiple tests """ self.source_dir = "" self.yamlfile = "" self.cases = [] self.name = self.get_unique(testcase_root, workdir, name) self.id = name self.type = None self.tags = set() self.extra_args = None self.extra_configs = None self.arch_allow = None self.arch_exclude = None self.skip = False self.platform_exclude = None self.platform_allow = None self.toolchain_exclude = None self.toolchain_allow = None self.tc_filter = None self.timeout = 60 self.harness = "" self.harness_config = {} self.build_only = True self.build_on_all = False self.slow = False self.min_ram = -1 self.depends_on = None self.min_flash = -1 self.extra_sections = None self.integration_platforms = [] @staticmethod def get_unique(testcase_root, workdir, name): canonical_testcase_root = os.path.realpath(testcase_root) if Path(canonical_zephyr_base) in Path(canonical_testcase_root).parents: # This is in ZEPHYR_BASE, so include path in name for uniqueness # FIXME: We should not depend on path of test for unique names. relative_tc_root = os.path.relpath(canonical_testcase_root, start=canonical_zephyr_base) else: relative_tc_root = "" # workdir can be "." unique = os.path.normpath(os.path.join(relative_tc_root, workdir, name)) check = name.split(".") if len(check) < 2: raise TwisterException(f"""bad test name '{name}' in {testcase_root}/{workdir}. \ Tests should reference the category and subsystem with a dot as a separator. """ ) return unique @staticmethod def scan_file(inf_name): suite_regex = re.compile( # do not match until end-of-line, otherwise we won't allow # stc_regex below to catch the ones that are declared in the same # line--as we only search starting the end of this match br"^\s*ztest_test_suite\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) stc_regex = re.compile( br"^\s*" # empy space at the beginning is ok # catch the case where it is declared in the same sentence, e.g: # # ztest_test_suite(mutex_complex, ztest_user_unit_test(TESTNAME)); br"(?:ztest_test_suite\([a-zA-Z0-9_]+,\s*)?" # Catch ztest[_user]_unit_test-[_setup_teardown](TESTNAME) br"ztest_(?:1cpu_)?(?:user_)?unit_test(?:_setup_teardown)?" # Consume the argument that becomes the extra testcse br"\(\s*" br"(?P<stc_name>[a-zA-Z0-9_]+)" # _setup_teardown() variant has two extra arguments that we ignore br"(?:\s*,\s*[a-zA-Z0-9_]+\s*,\s*[a-zA-Z0-9_]+)?" br"\s*\)", # We don't check how it finishes; we don't care re.MULTILINE) suite_run_regex = re.compile( br"^\s*ztest_run_test_suite\((?P<suite_name>[a-zA-Z0-9_]+)\)", re.MULTILINE) achtung_regex = re.compile( br"(#ifdef|#endif)", re.MULTILINE) warnings = None with open(inf_name) as inf: if os.name == 'nt': mmap_args = {'fileno': inf.fileno(), 'length': 0, 'access': mmap.ACCESS_READ} else: mmap_args = {'fileno': inf.fileno(), 'length': 0, 'flags': mmap.MAP_PRIVATE, 'prot': mmap.PROT_READ, 'offset': 0} with contextlib.closing(mmap.mmap(**mmap_args)) as main_c: suite_regex_match = suite_regex.search(main_c) if not suite_regex_match: # can't find ztest_test_suite, maybe a client, because # it includes ztest.h return None, None suite_run_match = suite_run_regex.search(main_c) if not suite_run_match: raise ValueError("can't find ztest_run_test_suite") achtung_matches = re.findall( achtung_regex, main_c[suite_regex_match.end():suite_run_match.start()]) if achtung_matches: warnings = "found invalid %s in ztest_test_suite()" \ % ", ".join(sorted({match.decode() for match in achtung_matches},reverse = True)) _matches = re.findall( stc_regex, main_c[suite_regex_match.end():suite_run_match.start()]) for match in _matches: if not match.decode().startswith("test_"): warnings = "Found a test that does not start with test_" matches = [match.decode().replace("test_", "", 1) for match in _matches] return matches, warnings def scan_path(self, path): subcases = [] for filename in glob.glob(os.path.join(path, "src", "*.c*")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) raise TwisterRuntimeError("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) for filename in glob.glob(os.path.join(path, "*.c")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) return subcases def parse_subcases(self, test_path): results = self.scan_path(test_path) for sub in results: name = "{}.{}".format(self.id, sub) self.cases.append(name) if not results: self.cases.append(self.id) def __str__(self): return self.name class TestInstance(DisablePyTestCollectionMixin): """Class representing the execution of a particular TestCase on a platform @param test The TestCase object we want to build/execute @param platform Platform object that we want to build and run against @param base_outdir Base directory for all test results. The actual out directory used is <outdir>/<platform>/<test case name> """ def __init__(self, testcase, platform, outdir): self.testcase = testcase self.platform = platform self.status = None self.reason = "Unknown" self.metrics = dict() self.handler = None self.outdir = outdir self.name = os.path.join(platform.name, testcase.name) self.build_dir = os.path.join(outdir, platform.name, testcase.name) self.run = False self.results = {} def __getstate__(self): d = self.__dict__.copy() return d def __setstate__(self, d): self.__dict__.update(d) def __lt__(self, other): return self.name < other.name @staticmethod def testcase_runnable(testcase, fixtures): can_run = False # console harness allows us to run the test and capture data. if testcase.harness in [ 'console', 'ztest']: can_run = True # if we have a fixture that is also being supplied on the # command-line, then we need to run the test, not just build it. fixture = testcase.harness_config.get('fixture') if fixture: can_run = (fixture in fixtures) elif testcase.harness: can_run = False else: can_run = True return can_run # Global testsuite parameters def check_runnable(self, enable_slow=False, filter='buildable', fixtures=[]): # right now we only support building on windows. running is still work # in progress. if os.name == 'nt': return False # we asked for build-only on the command line if self.testcase.build_only: return False # Do not run slow tests: skip_slow = self.testcase.slow and not enable_slow if skip_slow: return False target_ready = bool(self.testcase.type == "unit" or \ self.platform.type == "native" or \ self.platform.simulation in ["mdb-nsim", "nsim", "renode", "qemu", "tsim"] or \ filter == 'runnable') if self.platform.simulation == "nsim": if not find_executable("nsimdrv"): target_ready = False if self.platform.simulation == "mdb-nsim": if not find_executable("mdb"): target_ready = False if self.platform.simulation == "renode": if not find_executable("renode"): target_ready = False if self.platform.simulation == "tsim": if not find_executable("tsim-leon3"): target_ready = False testcase_runnable = self.testcase_runnable(self.testcase, fixtures) return testcase_runnable and target_ready def create_overlay(self, platform, enable_asan=False, enable_ubsan=False, enable_coverage=False, coverage_platform=[]): # Create this in a "twister/" subdirectory otherwise this # will pass this overlay to kconfig.py *twice* and kconfig.cmake # will silently give that second time precedence over any # --extra-args=CONFIG_* subdir = os.path.join(self.build_dir, "twister") content = "" if self.testcase.extra_configs: content = "\n".join(self.testcase.extra_configs) if enable_coverage: if platform.name in coverage_platform: content = content + "\nCONFIG_COVERAGE=y" content = content + "\nCONFIG_COVERAGE_DUMP=y" if enable_asan: if platform.type == "native": content = content + "\nCONFIG_ASAN=y" if enable_ubsan: if platform.type == "native": content = content + "\nCONFIG_UBSAN=y" if content: os.makedirs(subdir, exist_ok=True) file = os.path.join(subdir, "testcase_extra.conf") with open(file, "w") as f: f.write(content) return content def calculate_sizes(self): """Get the RAM/ROM sizes of a test case. This can only be run after the instance has been executed by MakeGenerator, otherwise there won't be any binaries to measure. @return A SizeCalculator object """ fns = glob.glob(os.path.join(self.build_dir, "zephyr", "*.elf")) fns.extend(glob.glob(os.path.join(self.build_dir, "zephyr", "*.exe"))) fns = [x for x in fns if not x.endswith('_prebuilt.elf')] if len(fns) != 1: raise BuildError("Missing/multiple output ELF binary") return SizeCalculator(fns[0], self.testcase.extra_sections) def fill_results_by_status(self): """Fills results according to self.status The method is used to propagate the instance level status to the test cases inside. Useful when the whole instance is skipped and the info is required also at the test cases level for reporting. Should be used with caution, e.g. should not be used to fill all results with passes """ status_to_verdict = { 'skipped': 'SKIP', 'error': 'BLOCK', 'failure': 'FAILED' } for k in self.results: self.results[k] = status_to_verdict[self.status] def __repr__(self): return "<TestCase %s on %s>" % (self.testcase.name, self.platform.name) class CMake(): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') def __init__(self, testcase, platform, source_dir, build_dir): self.cwd = None self.capture_output = True self.defconfig = {} self.cmake_cache = {} self.instance = None self.testcase = testcase self.platform = platform self.source_dir = source_dir self.build_dir = build_dir self.log = "build.log" self.generator = None self.generator_cmd = None def parse_generated(self): self.defconfig = {} return {} def run_build(self, args=[]): logger.debug("Building %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [] cmake_args.extend(args) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() results = {} if p.returncode == 0: msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) self.instance.status = "passed" results = {'msg': msg, "returncode": p.returncode, "instance": self.instance} if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) else: return None else: # A real error occurred, raise an exception log_msg = "" if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) if log_msg: res = re.findall("region `(FLASH|RAM|SRAM)' overflowed by", log_msg) if res and not self.overflow_as_errors: logger.debug("Test skipped due to {} Overflow".format(res[0])) self.instance.status = "skipped" self.instance.reason = "{} overflow".format(res[0]) else: self.instance.status = "error" self.instance.reason = "Build failure" results = { "returncode": p.returncode, "instance": self.instance, } return results def run_cmake(self, args=[]): if self.warnings_as_errors: ldflags = "-Wl,--fatal-warnings" cflags = "-Werror" aflags = "-Wa,--fatal-warnings" else: ldflags = cflags = aflags = "" logger.debug("Running cmake on %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [ f'-B{self.build_dir}', f'-S{self.source_dir}', f'-DEXTRA_CFLAGS="{cflags}"', f'-DEXTRA_AFLAGS="{aflags}', f'-DEXTRA_LDFLAGS="{ldflags}"', f'-G{self.generator}' ] if self.cmake_only: cmake_args.append("-DCMAKE_EXPORT_COMPILE_COMMANDS=1") args = ["-D{}".format(a.replace('"', '')) for a in args] cmake_args.extend(args) cmake_opts = ['-DBOARD={}'.format(self.platform.name)] cmake_args.extend(cmake_opts) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: filter_results = self.parse_generated() msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) logger.debug(msg) results = {'msg': msg, 'filter': filter_results} else: self.instance.status = "error" self.instance.reason = "Cmake build failure" logger.error("Cmake build failure: %s for %s" % (self.source_dir, self.platform.name)) results = {"returncode": p.returncode} if out: with open(os.path.join(self.build_dir, self.log), "a") as log: log_msg = out.decode(sys.getdefaultencoding()) log.write(log_msg) return results @staticmethod def run_cmake_script(args=[]): logger.debug("Running cmake script %s" % (args[0])) cmake_args = ["-D{}".format(a.replace('"', '')) for a in args[1:]] cmake_args.extend(['-P', args[0]]) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: msg = "Finished running %s" % (args[0]) logger.debug(msg) results = {"returncode": p.returncode, "msg": msg, "stdout": out} else: logger.error("Cmake script failure: %s" % (args[0])) results = {"returncode": p.returncode} return results class FilterBuilder(CMake): def __init__(self, testcase, platform, source_dir, build_dir): super().__init__(testcase, platform, source_dir, build_dir) self.log = "config-twister.log" def parse_generated(self): if self.platform.name == "unit_testing": return {} cmake_cache_path = os.path.join(self.build_dir, "CMakeCache.txt") defconfig_path = os.path.join(self.build_dir, "zephyr", ".config") with open(defconfig_path, "r") as fp: defconfig = {} for line in fp.readlines(): m = self.config_re.match(line) if not m: if line.strip() and not line.startswith("#"): sys.stderr.write("Unrecognized line %s\n" % line) continue defconfig[m.group(1)] = m.group(2).strip() self.defconfig = defconfig cmake_conf = {} try: cache = CMakeCache.from_file(cmake_cache_path) except FileNotFoundError: cache = {} for k in iter(cache): cmake_conf[k.name] = k.value self.cmake_cache = cmake_conf filter_data = { "ARCH": self.platform.arch, "PLATFORM": self.platform.name } filter_data.update(os.environ) filter_data.update(self.defconfig) filter_data.update(self.cmake_cache) edt_pickle = os.path.join(self.build_dir, "zephyr", "edt.pickle") if self.testcase and self.testcase.tc_filter: try: if os.path.exists(edt_pickle): with open(edt_pickle, 'rb') as f: edt = pickle.load(f) else: edt = None res = expr_parser.parse(self.testcase.tc_filter, filter_data, edt) except (ValueError, SyntaxError) as se: sys.stderr.write( "Failed processing %s\n" % self.testcase.yamlfile) raise se if not res: return {os.path.join(self.platform.name, self.testcase.name): True} else: return {os.path.join(self.platform.name, self.testcase.name): False} else: self.platform.filter_data = filter_data return filter_data class ProjectBuilder(FilterBuilder): def __init__(self, suite, instance, **kwargs): super().__init__(instance.testcase, instance.platform, instance.testcase.source_dir, instance.build_dir) self.log = "build.log" self.instance = instance self.suite = suite self.filtered_tests = 0 self.lsan = kwargs.get('lsan', False) self.asan = kwargs.get('asan', False) self.ubsan = kwargs.get('ubsan', False) self.valgrind = kwargs.get('valgrind', False) self.extra_args = kwargs.get('extra_args', []) self.device_testing = kwargs.get('device_testing', False) self.cmake_only = kwargs.get('cmake_only', False) self.cleanup = kwargs.get('cleanup', False) self.coverage = kwargs.get('coverage', False) self.inline_logs = kwargs.get('inline_logs', False) self.generator = kwargs.get('generator', None) self.generator_cmd = kwargs.get('generator_cmd', None) self.verbose = kwargs.get('verbose', None) self.warnings_as_errors = kwargs.get('warnings_as_errors', True) self.overflow_as_errors = kwargs.get('overflow_as_errors', False) @staticmethod def log_info(filename, inline_logs): filename = os.path.abspath(os.path.realpath(filename)) if inline_logs: logger.info("{:-^100}".format(filename)) try: with open(filename) as fp: data = fp.read() except Exception as e: data = "Unable to read log data (%s)\n" % (str(e)) logger.error(data) logger.info("{:-^100}".format(filename)) else: logger.error("see: " + Fore.YELLOW + filename + Fore.RESET) def log_info_file(self, inline_logs): build_dir = self.instance.build_dir h_log = "{}/handler.log".format(build_dir) b_log = "{}/build.log".format(build_dir) v_log = "{}/valgrind.log".format(build_dir) d_log = "{}/device.log".format(build_dir) if os.path.exists(v_log) and "Valgrind" in self.instance.reason: self.log_info("{}".format(v_log), inline_logs) elif os.path.exists(h_log) and os.path.getsize(h_log) > 0: self.log_info("{}".format(h_log), inline_logs) elif os.path.exists(d_log) and os.path.getsize(d_log) > 0: self.log_info("{}".format(d_log), inline_logs) else: self.log_info("{}".format(b_log), inline_logs) def setup_handler(self): instance = self.instance args = [] # FIXME: Needs simplification if instance.platform.simulation == "qemu": instance.handler = QEMUHandler(instance, "qemu") args.append("QEMU_PIPE=%s" % instance.handler.get_fifo()) instance.handler.call_make_run = True elif instance.testcase.type == "unit": instance.handler = BinaryHandler(instance, "unit") instance.handler.binary = os.path.join(instance.build_dir, "testbinary") if self.coverage: args.append("COVERAGE=1") elif instance.platform.type == "native": handler = BinaryHandler(instance, "native") handler.asan = self.asan handler.valgrind = self.valgrind handler.lsan = self.lsan handler.ubsan = self.ubsan handler.coverage = self.coverage handler.binary = os.path.join(instance.build_dir, "zephyr", "zephyr.exe") instance.handler = handler elif instance.platform.simulation == "renode": if find_executable("renode"): instance.handler = BinaryHandler(instance, "renode") instance.handler.pid_fn = os.path.join(instance.build_dir, "renode.pid") instance.handler.call_make_run = True elif instance.platform.simulation == "tsim": instance.handler = BinaryHandler(instance, "tsim") instance.handler.call_make_run = True elif self.device_testing: instance.handler = DeviceHandler(instance, "device") instance.handler.coverage = self.coverage elif instance.platform.simulation == "nsim": if find_executable("nsimdrv"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "mdb-nsim": if find_executable("mdb"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.pid_fn = os.path.join(instance.build_dir, "mdb.pid") instance.handler.call_west_flash = True if instance.handler: instance.handler.args = args instance.handler.generator_cmd = self.generator_cmd instance.handler.generator = self.generator def process(self, pipeline, done, message, lock, results): op = message.get('op') if not self.instance.handler: self.setup_handler() # The build process, call cmake and build with configured generator if op == "cmake": res = self.cmake() if self.instance.status in ["failed", "error"]: pipeline.put({"op": "report", "test": self.instance}) elif self.cmake_only: if self.instance.status is None: self.instance.status = "passed" pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.name in res['filter'] and res['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = "skipped" self.instance.reason = "filter" results.skipped_runtime += 1 for case in self.instance.testcase.cases: self.instance.results.update({case: 'SKIP'}) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "build", "test": self.instance}) elif op == "build": logger.debug("build test: %s" % self.instance.name) res = self.build() if not res: self.instance.status = "error" self.instance.reason = "Build Failure" pipeline.put({"op": "report", "test": self.instance}) else: # Count skipped cases during build, for example # due to ram/rom overflow. inst = res.get("instance", None) if inst and inst.status == "skipped": results.skipped_runtime += 1 if res.get('returncode', 1) > 0: pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.run and self.instance.handler: pipeline.put({"op": "run", "test": self.instance}) else: pipeline.put({"op": "report", "test": self.instance}) # Run the generated binary using one of the supported handlers elif op == "run": logger.debug("run test: %s" % self.instance.name) self.run() self.instance.status, _ = self.instance.handler.get_state() logger.debug(f"run status: {self.instance.name} {self.instance.status}") # to make it work with pickle self.instance.handler.thread = None self.instance.handler.suite = None pipeline.put({ "op": "report", "test": self.instance, "status": self.instance.status, "reason": self.instance.reason } ) # Report results and output progress to screen elif op == "report": with lock: done.put(self.instance) self.report_out(results) if self.cleanup and not self.coverage and self.instance.status == "passed": pipeline.put({ "op": "cleanup", "test": self.instance }) elif op == "cleanup": if self.device_testing: self.cleanup_device_testing_artifacts() else: self.cleanup_artifacts() def cleanup_artifacts(self, additional_keep=[]): logger.debug("Cleaning up {}".format(self.instance.build_dir)) allow = [ 'zephyr/.config', 'handler.log', 'build.log', 'device.log', 'recording.csv', ] allow += additional_keep allow = [os.path.join(self.instance.build_dir, file) for file in allow] for dirpath, dirnames, filenames in os.walk(self.instance.build_dir, topdown=False): for name in filenames: path = os.path.join(dirpath, name) if path not in allow: os.remove(path) # Remove empty directories and symbolic links to directories for dir in dirnames: path = os.path.join(dirpath, dir) if os.path.islink(path): os.remove(path) elif not os.listdir(path): os.rmdir(path) def cleanup_device_testing_artifacts(self): logger.debug("Cleaning up for Device Testing {}".format(self.instance.build_dir)) sanitizelist = [ 'CMakeCache.txt', 'zephyr/runners.yaml', ] keep = [ 'zephyr/zephyr.hex', 'zephyr/zephyr.bin', 'zephyr/zephyr.elf', ] keep += sanitizelist self.cleanup_artifacts(keep) # sanitize paths so files are relocatable for file in sanitizelist: file = os.path.join(self.instance.build_dir, file) with open(file, "rt") as fin: data = fin.read() data = data.replace(canonical_zephyr_base+"/", "") with open(file, "wt") as fin: fin.write(data) def report_out(self, results): total_to_do = results.total - results.skipped_configs total_tests_width = len(str(total_to_do)) results.done += 1 instance = self.instance if instance.status in ["error", "failed", "timeout"]: if instance.status == "error": results.error += 1 results.failed += 1 if self.verbose: status = Fore.RED + "FAILED " + Fore.RESET + instance.reason else: print("") logger.error( "{:<25} {:<50} {}FAILED{}: {}".format( instance.platform.name, instance.testcase.name, Fore.RED, Fore.RESET, instance.reason)) if not self.verbose: self.log_info_file(self.inline_logs) elif instance.status == "skipped": status = Fore.YELLOW + "SKIPPED" + Fore.RESET elif instance.status == "passed": status = Fore.GREEN + "PASSED" + Fore.RESET else: logger.debug(f"Unknown status = {instance.status}") status = Fore.YELLOW + "UNKNOWN" + Fore.RESET if self.verbose: if self.cmake_only: more_info = "cmake" elif instance.status == "skipped": more_info = instance.reason else: if instance.handler and instance.run: more_info = instance.handler.type_str htime = instance.handler.duration if htime: more_info += " {:.3f}s".format(htime) else: more_info = "build" logger.info("{:>{}}/{} {:<25} {:<50} {} ({})".format( results.done, total_tests_width, total_to_do, instance.platform.name, instance.testcase.name, status, more_info)) if instance.status in ["error", "failed", "timeout"]: self.log_info_file(self.inline_logs) else: completed_perc = 0 if total_to_do > 0: completed_perc = int((float(results.done) / total_to_do) * 100) skipped = results.skipped_configs + results.skipped_runtime sys.stdout.write("\rINFO - Total complete: %s%4d/%4d%s %2d%% skipped: %s%4d%s, failed: %s%4d%s" % ( Fore.GREEN, results.done, total_to_do, Fore.RESET, completed_perc, Fore.YELLOW if skipped > 0 else Fore.RESET, skipped, Fore.RESET, Fore.RED if results.failed > 0 else Fore.RESET, results.failed, Fore.RESET ) ) sys.stdout.flush() def cmake(self): instance = self.instance args = self.testcase.extra_args[:] args += self.extra_args if instance.handler: args += instance.handler.args # merge overlay files into one variable def extract_overlays(args): re_overlay = re.compile('OVERLAY_CONFIG=(.*)') other_args = [] overlays = [] for arg in args: match = re_overlay.search(arg) if match: overlays.append(match.group(1).strip('\'"')) else: other_args.append(arg) args[:] = other_args return overlays overlays = extract_overlays(args) if os.path.exists(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")): overlays.append(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")) if overlays: args.append("OVERLAY_CONFIG=\"%s\"" % (" ".join(overlays))) res = self.run_cmake(args) return res def build(self): res = self.run_build(['--build', self.build_dir]) return res def run(self): instance = self.instance if instance.handler: if instance.handler.type_str == "device": instance.handler.suite = self.suite instance.handler.handle() sys.stdout.flush() class TestSuite(DisablePyTestCollectionMixin): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') tc_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "testcase-schema.yaml")) testcase_valid_keys = {"tags": {"type": "set", "required": False}, "type": {"type": "str", "default": "integration"}, "extra_args": {"type": "list"}, "extra_configs": {"type": "list"}, "build_only": {"type": "bool", "default": False}, "build_on_all": {"type": "bool", "default": False}, "skip": {"type": "bool", "default": False}, "slow": {"type": "bool", "default": False}, "timeout": {"type": "int", "default": 60}, "min_ram": {"type": "int", "default": 8}, "depends_on": {"type": "set"}, "min_flash": {"type": "int", "default": 32}, "arch_allow": {"type": "set"}, "arch_exclude": {"type": "set"}, "extra_sections": {"type": "list", "default": []}, "integration_platforms": {"type": "list", "default": []}, "platform_exclude": {"type": "set"}, "platform_allow": {"type": "set"}, "toolchain_exclude": {"type": "set"}, "toolchain_allow": {"type": "set"}, "filter": {"type": "str"}, "harness": {"type": "str"}, "harness_config": {"type": "map", "default": {}} } RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "release", "twister_last_release.csv") SAMPLE_FILENAME = 'sample.yaml' TESTCASE_FILENAME = 'testcase.yaml' def __init__(self, board_root_list=[], testcase_roots=[], outdir=None): self.roots = testcase_roots if not isinstance(board_root_list, list): self.board_roots = [board_root_list] else: self.board_roots = board_root_list # Testsuite Options self.coverage_platform = [] self.build_only = False self.cmake_only = False self.cleanup = False self.enable_slow = False self.device_testing = False self.fixtures = [] self.enable_coverage = False self.enable_ubsan = False self.enable_lsan = False self.enable_asan = False self.enable_valgrind = False self.extra_args = [] self.inline_logs = False self.enable_sizes_report = False self.west_flash = None self.west_runner = None self.generator = None self.generator_cmd = None self.warnings_as_errors = True self.overflow_as_errors = False # Keep track of which test cases we've filtered out and why self.testcases = {} self.platforms = [] self.selected_platforms = [] self.filtered_platforms = [] self.default_platforms = [] self.outdir = os.path.abspath(outdir) self.discards = {} self.load_errors = 0 self.instances = dict() self.total_platforms = 0 self.start_time = 0 self.duration = 0 self.warnings = 0 # hardcoded for now self.duts = [] # run integration tests only self.integration = False self.pipeline = None self.version = "NA" def check_zephyr_version(self): try: subproc = subprocess.run(["git", "describe", "--abbrev=12"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: self.version = subproc.stdout.strip() logger.info(f"Zephyr version: {self.version}") except OSError: logger.info("Cannot read zephyr version.") def get_platform_instances(self, platform): filtered_dict = {k:v for k,v in self.instances.items() if k.startswith(platform + "/")} return filtered_dict def config(self): logger.info("coverage platform: {}".format(self.coverage_platform)) # Debug Functions @staticmethod def info(what): sys.stdout.write(what + "\n") sys.stdout.flush() def update_counting(self, results=None, initial=False): results.skipped_configs = 0 results.skipped_cases = 0 for instance in self.instances.values(): if initial: results.cases += len(instance.testcase.cases) if instance.status == 'skipped': results.skipped_configs += 1 results.skipped_cases += len(instance.testcase.cases) elif instance.status == "passed": results.passed += 1 for res in instance.results.values(): if res == 'SKIP': results.skipped_cases += 1 def compare_metrics(self, filename): # name, datatype, lower results better interesting_metrics = [("ram_size", int, True), ("rom_size", int, True)] if not os.path.exists(filename): logger.error("Cannot compare metrics, %s not found" % filename) return [] results = [] saved_metrics = {} with open(filename) as fp: cr = csv.DictReader(fp) for row in cr: d = {} for m, _, _ in interesting_metrics: d[m] = row[m] saved_metrics[(row["test"], row["platform"])] = d for instance in self.instances.values(): mkey = (instance.testcase.name, instance.platform.name) if mkey not in saved_metrics: continue sm = saved_metrics[mkey] for metric, mtype, lower_better in interesting_metrics: if metric not in instance.metrics: continue if sm[metric] == "": continue delta = instance.metrics.get(metric, 0) - mtype(sm[metric]) if delta == 0: continue results.append((instance, metric, instance.metrics.get(metric, 0), delta, lower_better)) return results def footprint_reports(self, report, show_footprint, all_deltas, footprint_threshold, last_metrics): if not report: return logger.debug("running footprint_reports") deltas = self.compare_metrics(report) warnings = 0 if deltas and show_footprint: for i, metric, value, delta, lower_better in deltas: if not all_deltas and ((delta < 0 and lower_better) or (delta > 0 and not lower_better)): continue percentage = 0 if value > delta: percentage = (float(delta) / float(value - delta)) if not all_deltas and (percentage < (footprint_threshold / 100.0)): continue logger.info("{:<25} {:<60} {}{}{}: {} {:<+4}, is now {:6} {:+.2%}".format( i.platform.name, i.testcase.name, Fore.YELLOW, "INFO" if all_deltas else "WARNING", Fore.RESET, metric, delta, value, percentage)) warnings += 1 if warnings: logger.warning("Deltas based on metrics from last %s" % ("release" if not last_metrics else "run")) def summary(self, results, unrecognized_sections): failed = 0 run = 0 for instance in self.instances.values(): if instance.status == "failed": failed += 1 elif instance.metrics.get("unrecognized") and not unrecognized_sections: logger.error("%sFAILED%s: %s has unrecognized binary sections: %s" % (Fore.RED, Fore.RESET, instance.name, str(instance.metrics.get("unrecognized", [])))) failed += 1 if instance.metrics.get('handler_time', None): run += 1 if results.total and results.total != results.skipped_configs: pass_rate = (float(results.passed) / float(results.total - results.skipped_configs)) else: pass_rate = 0 logger.info( "{}{} of {}{} test configurations passed ({:.2%}), {}{}{} failed, {} skipped with {}{}{} warnings in {:.2f} seconds".format( Fore.RED if failed else Fore.GREEN, results.passed, results.total - results.skipped_configs, Fore.RESET, pass_rate, Fore.RED if results.failed else Fore.RESET, results.failed, Fore.RESET, results.skipped_configs, Fore.YELLOW if self.warnings else Fore.RESET, self.warnings, Fore.RESET, self.duration)) self.total_platforms = len(self.platforms) # if we are only building, do not report about tests being executed. if self.platforms and not self.build_only: logger.info("In total {} test cases were executed, {} skipped on {} out of total {} platforms ({:02.2f}%)".format( results.cases - results.skipped_cases, results.skipped_cases, len(self.filtered_platforms), self.total_platforms, (100 * len(self.filtered_platforms) / len(self.platforms)) )) logger.info(f"{Fore.GREEN}{run}{Fore.RESET} test configurations executed on platforms, \ {Fore.RED}{results.total - run - results.skipped_configs}{Fore.RESET} test configurations were only built.") def save_reports(self, name, suffix, report_dir, no_update, release, only_failed, platform_reports, json_report): if not self.instances: return logger.info("Saving reports...") if name: report_name = name else: report_name = "twister" if report_dir: os.makedirs(report_dir, exist_ok=True) filename = os.path.join(report_dir, report_name) outdir = report_dir else: filename = os.path.join(self.outdir, report_name) outdir = self.outdir if suffix: filename = "{}_{}".format(filename, suffix) if not no_update: self.xunit_report(filename + ".xml", full_report=False, append=only_failed, version=self.version) self.xunit_report(filename + "_report.xml", full_report=True, append=only_failed, version=self.version) self.csv_report(filename + ".csv") if json_report: self.json_report(filename + ".json", append=only_failed, version=self.version) if platform_reports: self.target_report(outdir, suffix, append=only_failed) if self.discards: self.discard_report(filename + "_discard.csv") if release: self.csv_report(self.RELEASE_DATA) def add_configurations(self): for board_root in self.board_roots: board_root = os.path.abspath(board_root) logger.debug("Reading platform configuration files under %s..." % board_root) for file in glob.glob(os.path.join(board_root, "*", "*", "*.yaml")): try: platform = Platform() platform.load(file) if platform.name in [p.name for p in self.platforms]: logger.error(f"Duplicate platform {platform.name} in {file}") raise Exception(f"Duplicate platform identifier {platform.name} found") if platform.twister: self.platforms.append(platform) if platform.default: self.default_platforms.append(platform.name) except RuntimeError as e: logger.error("E: %s: can't load: %s" % (file, e)) self.load_errors += 1 def get_all_tests(self): tests = [] for _, tc in self.testcases.items(): for case in tc.cases: tests.append(case) return tests @staticmethod def get_toolchain(): toolchain_script = Path(ZEPHYR_BASE) / Path('cmake/verify-toolchain.cmake') result = CMake.run_cmake_script([toolchain_script, "FORMAT=json"]) try: if result['returncode']: raise TwisterRuntimeError("E: Variable ZEPHYR_TOOLCHAIN_VARIANT is not defined") except Exception as e: print(str(e)) sys.exit(2) toolchain = json.loads(result['stdout'])['ZEPHYR_TOOLCHAIN_VARIANT'] logger.info(f"Using '{toolchain}' toolchain.") return toolchain def add_testcases(self, testcase_filter=[]): for root in self.roots: root = os.path.abspath(root) logger.debug("Reading test case configuration files under %s..." % root) for dirpath, dirnames, filenames in os.walk(root, topdown=True): if self.SAMPLE_FILENAME in filenames: filename = self.SAMPLE_FILENAME elif self.TESTCASE_FILENAME in filenames: filename = self.TESTCASE_FILENAME else: continue logger.debug("Found possible test case in " + dirpath) dirnames[:] = [] tc_path = os.path.join(dirpath, filename) try: parsed_data = TwisterConfigParser(tc_path, self.tc_schema) parsed_data.load() tc_path = os.path.dirname(tc_path) workdir = os.path.relpath(tc_path, root) for name in parsed_data.tests.keys(): tc = TestCase(root, workdir, name) tc_dict = parsed_data.get_test(name, self.testcase_valid_keys) tc.source_dir = tc_path tc.yamlfile = tc_path tc.type = tc_dict["type"] tc.tags = tc_dict["tags"] tc.extra_args = tc_dict["extra_args"] tc.extra_configs = tc_dict["extra_configs"] tc.arch_allow = tc_dict["arch_allow"] tc.arch_exclude = tc_dict["arch_exclude"] tc.skip = tc_dict["skip"] tc.platform_exclude = tc_dict["platform_exclude"] tc.platform_allow = tc_dict["platform_allow"] tc.toolchain_exclude = tc_dict["toolchain_exclude"] tc.toolchain_allow = tc_dict["toolchain_allow"] tc.tc_filter = tc_dict["filter"] tc.timeout = tc_dict["timeout"] tc.harness = tc_dict["harness"] tc.harness_config = tc_dict["harness_config"] if tc.harness == 'console' and not tc.harness_config: raise Exception('Harness config error: console harness defined without a configuration.') tc.build_only = tc_dict["build_only"] tc.build_on_all = tc_dict["build_on_all"] tc.slow = tc_dict["slow"] tc.min_ram = tc_dict["min_ram"] tc.depends_on = tc_dict["depends_on"] tc.min_flash = tc_dict["min_flash"] tc.extra_sections = tc_dict["extra_sections"] tc.integration_platforms = tc_dict["integration_platforms"] tc.parse_subcases(tc_path) if testcase_filter: if tc.name and tc.name in testcase_filter: self.testcases[tc.name] = tc else: self.testcases[tc.name] = tc except Exception as e: logger.error("%s: can't load (skipping): %s" % (tc_path, e)) self.load_errors += 1 return len(self.testcases) def get_platform(self, name): selected_platform = None for platform in self.platforms: if platform.name == name: selected_platform = platform break return selected_platform def load_from_file(self, file, filter_status=[], filter_platform=[]): try: with open(file, "r") as fp: cr = csv.DictReader(fp) instance_list = [] for row in cr: if row["status"] in filter_status: continue test = row["test"] platform = self.get_platform(row["platform"]) if filter_platform and platform.name not in filter_platform: continue instance = TestInstance(self.testcases[test], platform, self.outdir) if self.device_testing: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) instance.create_overlay(platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) instance_list.append(instance) self.add_instances(instance_list) except KeyError as e: logger.error("Key error while parsing tests file.({})".format(str(e))) sys.exit(2) except FileNotFoundError as e: logger.error("Couldn't find input file with list of tests. ({})".format(e)) sys.exit(2) def apply_filters(self, **kwargs): toolchain = self.get_toolchain() discards = {} platform_filter = kwargs.get('platform') exclude_platform = kwargs.get('exclude_platform', []) testcase_filter = kwargs.get('run_individual_tests', []) arch_filter = kwargs.get('arch') tag_filter = kwargs.get('tag') exclude_tag = kwargs.get('exclude_tag') all_filter = kwargs.get('all') runnable = kwargs.get('runnable') force_toolchain = kwargs.get('force_toolchain') force_platform = kwargs.get('force_platform') emu_filter = kwargs.get('emulation_only') logger.debug("platform filter: " + str(platform_filter)) logger.debug(" arch_filter: " + str(arch_filter)) logger.debug(" tag_filter: " + str(tag_filter)) logger.debug(" exclude_tag: " + str(exclude_tag)) default_platforms = False emulation_platforms = False if all_filter: logger.info("Selecting all possible platforms per test case") # When --all used, any --platform arguments ignored platform_filter = [] elif not platform_filter and not emu_filter: logger.info("Selecting default platforms per test case") default_platforms = True elif emu_filter: logger.info("Selecting emulation platforms per test case") emulation_platforms = True if platform_filter: platforms = list(filter(lambda p: p.name in platform_filter, self.platforms)) elif emu_filter: platforms = list(filter(lambda p: p.simulation != 'na', self.platforms)) elif arch_filter: platforms = list(filter(lambda p: p.arch in arch_filter, self.platforms)) elif default_platforms: platforms = list(filter(lambda p: p.default, self.platforms)) else: platforms = self.platforms logger.info("Building initial testcase list...") for tc_name, tc in self.testcases.items(): if tc.build_on_all and not platform_filter: platform_scope = self.platforms else: platform_scope = platforms # list of instances per testcase, aka configurations. instance_list = [] for plat in platform_scope: instance = TestInstance(tc, plat, self.outdir) if runnable: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) for t in tc.cases: instance.results[t] = None if runnable and self.duts: for h in self.duts: if h.platform == plat.name: if tc.harness_config.get('fixture') in h.fixtures: instance.run = True if not force_platform and plat.name in exclude_platform: discards[instance] = discards.get(instance, "Platform is excluded on command line.") if (plat.arch == "unit") != (tc.type == "unit"): # Discard silently continue if runnable and not instance.run: discards[instance] = discards.get(instance, "Not runnable on device") if self.integration and tc.integration_platforms and plat.name not in tc.integration_platforms: discards[instance] = discards.get(instance, "Not part of integration platforms") if tc.skip: discards[instance] = discards.get(instance, "Skip filter") if tag_filter and not tc.tags.intersection(tag_filter): discards[instance] = discards.get(instance, "Command line testcase tag filter") if exclude_tag and tc.tags.intersection(exclude_tag): discards[instance] = discards.get(instance, "Command line testcase exclude filter") if testcase_filter and tc_name not in testcase_filter: discards[instance] = discards.get(instance, "Testcase name filter") if arch_filter and plat.arch not in arch_filter: discards[instance] = discards.get(instance, "Command line testcase arch filter") if not force_platform: if tc.arch_allow and plat.arch not in tc.arch_allow: discards[instance] = discards.get(instance, "Not in test case arch allow list") if tc.arch_exclude and plat.arch in tc.arch_exclude: discards[instance] = discards.get(instance, "In test case arch exclude") if tc.platform_exclude and plat.name in tc.platform_exclude: discards[instance] = discards.get(instance, "In test case platform exclude") if tc.toolchain_exclude and toolchain in tc.toolchain_exclude: discards[instance] = discards.get(instance, "In test case toolchain exclude") if platform_filter and plat.name not in platform_filter: discards[instance] = discards.get(instance, "Command line platform filter") if tc.platform_allow and plat.name not in tc.platform_allow: discards[instance] = discards.get(instance, "Not in testcase platform allow list") if tc.toolchain_allow and toolchain not in tc.toolchain_allow: discards[instance] = discards.get(instance, "Not in testcase toolchain allow list") if not plat.env_satisfied: discards[instance] = discards.get(instance, "Environment ({}) not satisfied".format(", ".join(plat.env))) if not force_toolchain \ and toolchain and (toolchain not in plat.supported_toolchains) \ and tc.type != 'unit': discards[instance] = discards.get(instance, "Not supported by the toolchain") if plat.ram < tc.min_ram: discards[instance] = discards.get(instance, "Not enough RAM") if tc.depends_on: dep_intersection = tc.depends_on.intersection(set(plat.supported)) if dep_intersection != set(tc.depends_on): discards[instance] = discards.get(instance, "No hardware support") if plat.flash < tc.min_flash: discards[instance] = discards.get(instance, "Not enough FLASH") if set(plat.ignore_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (exclude_tags)") if plat.only_tags and not set(plat.only_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (only_tags)") # if nothing stopped us until now, it means this configuration # needs to be added. instance_list.append(instance) # no configurations, so jump to next testcase if not instance_list: continue # if twister was launched with no platform options at all, we # take all default platforms if default_platforms and not tc.build_on_all: if tc.platform_allow: a = set(self.default_platforms) b = set(tc.platform_allow) c = a.intersection(b) if c: aa = list(filter(lambda tc: tc.platform.name in c, instance_list)) self.add_instances(aa) else: self.add_instances(instance_list[:1]) else: instances = list(filter(lambda tc: tc.platform.default, instance_list)) if self.integration: instances += list(filter(lambda item: item.platform.name in tc.integration_platforms, \ instance_list)) self.add_instances(instances) elif emulation_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.simulation != 'na', instance_list)): discards[instance] = discards.get(instance, "Not an emulated platform") else: self.add_instances(instance_list) for _, case in self.instances.items(): case.create_overlay(case.platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) self.discards = discards self.selected_platforms = set(p.platform.name for p in self.instances.values()) for instance in self.discards: instance.reason = self.discards[instance] instance.status = "skipped" instance.fill_results_by_status() self.filtered_platforms = set(p.platform.name for p in self.instances.values() if p.status != "skipped" ) return discards def add_instances(self, instance_list): for instance in instance_list: self.instances[instance.name] = instance @staticmethod def calc_one_elf_size(instance): if instance.status not in ["error", "failed", "skipped"]: if instance.platform.type != "native": size_calc = instance.calculate_sizes() instance.metrics["ram_size"] = size_calc.get_ram_size() instance.metrics["rom_size"] = size_calc.get_rom_size() instance.metrics["unrecognized"] = size_calc.unrecognized_sections() else: instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["unrecognized"] = [] instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 def add_tasks_to_queue(self, pipeline, build_only=False, test_only=False): for instance in self.instances.values(): if build_only: instance.run = False if test_only and instance.run: pipeline.put({"op": "run", "test": instance}) else: if instance.status not in ['passed', 'skipped', 'error']: logger.debug(f"adding {instance.name}") instance.status = None pipeline.put({"op": "cmake", "test": instance}) def pipeline_mgr(self, pipeline, done_queue, lock, results): while True: try: task = pipeline.get_nowait() except queue.Empty: break else: test = task['test'] pb = ProjectBuilder(self, test, lsan=self.enable_lsan, asan=self.enable_asan, ubsan=self.enable_ubsan, coverage=self.enable_coverage, extra_args=self.extra_args, device_testing=self.device_testing, cmake_only=self.cmake_only, cleanup=self.cleanup, valgrind=self.enable_valgrind, inline_logs=self.inline_logs, generator=self.generator, generator_cmd=self.generator_cmd, verbose=self.verbose, warnings_as_errors=self.warnings_as_errors, overflow_as_errors=self.overflow_as_errors ) pb.process(pipeline, done_queue, task, lock, results) return True def execute(self, pipeline, done, results): lock = Lock() logger.info("Adding tasks to the queue...") self.add_tasks_to_queue(pipeline, self.build_only, self.test_only) logger.info("Added initial list of jobs to queue") processes = [] for job in range(self.jobs): logger.debug(f"Launch process {job}") p = Process(target=self.pipeline_mgr, args=(pipeline, done, lock, results, )) processes.append(p) p.start() try: for p in processes: p.join() except KeyboardInterrupt: logger.info("Execution interrupted") for p in processes: p.terminate() # FIXME: This needs to move out. if self.enable_size_report and not self.cmake_only: # Parallelize size calculation executor = concurrent.futures.ThreadPoolExecutor(self.jobs) futures = [executor.submit(self.calc_one_elf_size, instance) for instance in self.instances.values()] concurrent.futures.wait(futures) else: for instance in self.instances.values(): instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 instance.metrics["unrecognized"] = [] return results def discard_report(self, filename): try: if not self.discards: raise TwisterRuntimeError("apply_filters() hasn't been run!") except Exception as e: logger.error(str(e)) sys.exit(2) with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "reason"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance, reason in sorted(self.discards.items()): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "reason": reason} cw.writerow(rowdict) def target_report(self, outdir, suffix, append=False): platforms = {inst.platform.name for _, inst in self.instances.items()} for platform in platforms: if suffix: filename = os.path.join(outdir,"{}_{}.xml".format(platform, suffix)) else: filename = os.path.join(outdir,"{}.xml".format(platform)) self.xunit_report(filename, platform, full_report=True, append=append, version=self.version) @staticmethod def process_log(log_file): filtered_string = "" if os.path.exists(log_file): with open(log_file, "rb") as f: log = f.read().decode("utf-8") filtered_string = ''.join(filter(lambda x: x in string.printable, log)) return filtered_string def xunit_report(self, filename, platform=None, full_report=False, append=False, version="NA"): total = 0 fails = passes = errors = skips = 0 if platform: selected = [platform] logger.info(f"Writing target report for {platform}...") else: logger.info(f"Writing xunit report {filename}...") selected = self.selected_platforms if os.path.exists(filename) and append: tree = ET.parse(filename) eleTestsuites = tree.getroot() else: eleTestsuites = ET.Element('testsuites') for p in selected: inst = self.get_platform_instances(p) fails = 0 passes = 0 errors = 0 skips = 0 duration = 0 for _, instance in inst.items(): handler_time = instance.metrics.get('handler_time', 0) duration += handler_time if full_report and instance.run: for k in instance.results.keys(): if instance.results[k] == 'PASS': passes += 1 elif instance.results[k] == 'BLOCK': errors += 1 elif instance.results[k] == 'SKIP' or instance.status in ['skipped']: skips += 1 else: fails += 1 else: if instance.status in ["error", "failed", "timeout"]: if instance.reason in ['build_error', 'handler_crash']: errors += 1 else: fails += 1 elif instance.status == 'skipped': skips += 1 elif instance.status == 'passed': passes += 1 else: if instance.status: logger.error(f"{instance.name}: Unknown status {instance.status}") else: logger.error(f"{instance.name}: No status") total = (errors + passes + fails + skips) # do not produce a report if no tests were actually run (only built) if total == 0: continue run = p eleTestsuite = None # When we re-run the tests, we re-use the results and update only with # the newly run tests. if os.path.exists(filename) and append: ts = eleTestsuites.findall(f'testsuite/[@name="{p}"]') if ts: eleTestsuite = ts[0] eleTestsuite.attrib['failures'] = "%d" % fails eleTestsuite.attrib['errors'] = "%d" % errors eleTestsuite.attrib['skipped'] = "%d" % skips else: logger.info(f"Did not find any existing results for {p}") eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) else: eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) for _, instance in inst.items(): if full_report: tname = os.path.basename(instance.testcase.name) else: tname = instance.testcase.id handler_time = instance.metrics.get('handler_time', 0) if full_report: for k in instance.results.keys(): # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@name="{k}"]'): eleTestsuite.remove(tc) classname = ".".join(tname.split(".")[:2]) eleTestcase = ET.SubElement( eleTestsuite, 'testcase', classname=classname, name="%s" % (k), time="%f" % handler_time) if instance.results[k] in ['FAIL', 'BLOCK'] or \ (not instance.run and instance.status in ["error", "failed", "timeout"]): if instance.results[k] == 'FAIL': el = ET.SubElement( eleTestcase, 'failure', type="failure", message="failed") else: el = ET.SubElement( eleTestcase, 'error', type="failure", message="failed") log_root = os.path.join(self.outdir, instance.platform.name, instance.testcase.name) log_file = os.path.join(log_root, "handler.log") el.text = self.process_log(log_file) elif instance.results[k] == 'PASS' \ or (not instance.run and instance.status in ["passed"]): pass elif instance.results[k] == 'SKIP' or (instance.status in ["skipped"]): el = ET.SubElement(eleTestcase, 'skipped', type="skipped", message=instance.reason) else: el = ET.SubElement( eleTestcase, 'error', type="error", message=f"{instance.reason}") else: if platform: classname = ".".join(instance.testcase.name.split(".")[:2]) else: classname = p + ":" + ".".join(instance.testcase.name.split(".")[:2]) # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@classname="{classname}"][@name="{instance.testcase.name}"]'): eleTestsuite.remove(tc) eleTestcase = ET.SubElement(eleTestsuite, 'testcase', classname=classname, name="%s" % (instance.testcase.name), time="%f" % handler_time) if instance.status in ["error", "failed", "timeout"]: failure = ET.SubElement( eleTestcase, 'failure', type="failure", message=instance.reason) log_root = ("%s/%s/%s" % (self.outdir, instance.platform.name, instance.testcase.name)) bl = os.path.join(log_root, "build.log") hl = os.path.join(log_root, "handler.log") log_file = bl if instance.reason != 'Build error': if os.path.exists(hl): log_file = hl else: log_file = bl failure.text = self.process_log(log_file) elif instance.status == "skipped": ET.SubElement(eleTestcase, 'skipped', type="skipped", message="Skipped") result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) return fails, passes, errors, skips def csv_report(self, filename): with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "status", "extra_args", "handler", "handler_time", "ram_size", "rom_size"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance in self.instances.values(): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "extra_args": " ".join(instance.testcase.extra_args), "handler": instance.platform.simulation} rowdict["status"] = instance.status if instance.status not in ["error", "failed", "timeout"]: if instance.handler: rowdict["handler_time"] = instance.metrics.get("handler_time", 0) ram_size = instance.metrics.get("ram_size", 0) rom_size = instance.metrics.get("rom_size", 0) rowdict["ram_size"] = ram_size rowdict["rom_size"] = rom_size cw.writerow(rowdict) def json_report(self, filename, append=False, version="NA"): logger.info(f"Writing JSON report {filename}") report = {} selected = self.selected_platforms report["environment"] = {"os": os.name, "zephyr_version": version, "toolchain": self.get_toolchain() } json_data = {} if os.path.exists(filename) and append: with open(filename, 'r') as json_file: json_data = json.load(json_file) suites = json_data.get("testsuites", []) if suites: suite = suites[0] testcases = suite.get("testcases", []) else: suite = {} testcases = [] for p in selected: inst = self.get_platform_instances(p) for _, instance in inst.items(): testcase = {} handler_log = os.path.join(instance.build_dir, "handler.log") build_log = os.path.join(instance.build_dir, "build.log") device_log = os.path.join(instance.build_dir, "device.log") handler_time = instance.metrics.get('handler_time', 0) ram_size = instance.metrics.get ("ram_size", 0) rom_size = instance.metrics.get("rom_size",0) for k in instance.results.keys(): testcases = list(filter(lambda d: not (d.get('testcase') == k and d.get('platform') == p), testcases )) testcase = {"testcase": k, "arch": instance.platform.arch, "platform": p, } if instance.results[k] in ["PASS"]: testcase["status"] = "passed" if instance.handler: testcase["execution_time"] = handler_time if ram_size: testcase["ram_size"] = ram_size if rom_size: testcase["rom_size"] = rom_size elif instance.results[k] in ['FAIL', 'BLOCK'] or instance.status in ["error", "failed", "timeout"]: testcase["status"] = "failed" testcase["reason"] = instance.reason testcase["execution_time"] = handler_time if os.path.exists(handler_log): testcase["test_output"] = self.process_log(handler_log) elif os.path.exists(device_log): testcase["device_log"] = self.process_log(device_log) else: testcase["build_log"] = self.process_log(build_log) else: testcase["status"] = "skipped" testcase["reason"] = instance.reason testcases.append(testcase) suites = [ {"testcases": testcases} ] report["testsuites"] = suites with open(filename, "wt") as json_file: json.dump(report, json_file, indent=4, separators=(',',':')) def get_testcase(self, identifier): results = [] for _, tc in self.testcases.items(): for case in tc.cases: if case == identifier: results.append(tc) return results class CoverageTool: """ Base class for every supported coverage tool """ def __init__(self): self.gcov_tool = None self.base_dir = None @staticmethod def factory(tool): if tool == 'lcov': t = Lcov() elif tool == 'gcovr': t = Gcovr() else: logger.error("Unsupported coverage tool specified: {}".format(tool)) return None logger.debug(f"Select {tool} as the coverage tool...") return t @staticmethod def retrieve_gcov_data(intput_file): logger.debug("Working on %s" % intput_file) extracted_coverage_info = {} capture_data = False capture_complete = False with open(intput_file, 'r') as fp: for line in fp.readlines(): if re.search("GCOV_COVERAGE_DUMP_START", line): capture_data = True continue if re.search("GCOV_COVERAGE_DUMP_END", line): capture_complete = True break # Loop until the coverage data is found. if not capture_data: continue if line.startswith("*"): sp = line.split("<") if len(sp) > 1: # Remove the leading delimiter "*" file_name = sp[0][1:] # Remove the trailing new line char hex_dump = sp[1][:-1] else: continue else: continue extracted_coverage_info.update({file_name: hex_dump}) if not capture_data: capture_complete = True return {'complete': capture_complete, 'data': extracted_coverage_info} @staticmethod def create_gcda_files(extracted_coverage_info): logger.debug("Generating gcda files") for filename, hexdump_val in extracted_coverage_info.items(): # if kobject_hash is given for coverage gcovr fails # hence skipping it problem only in gcovr v4.1 if "kobject_hash" in filename: filename = (filename[:-4]) + "gcno" try: os.remove(filename) except Exception: pass continue with open(filename, 'wb') as fp: fp.write(bytes.fromhex(hexdump_val)) def generate(self, outdir): for filename in glob.glob("%s/**/handler.log" % outdir, recursive=True): gcov_data = self.__class__.retrieve_gcov_data(filename) capture_complete = gcov_data['complete'] extracted_coverage_info = gcov_data['data'] if capture_complete: self.__class__.create_gcda_files(extracted_coverage_info) logger.debug("Gcov data captured: {}".format(filename)) else: logger.error("Gcov data capture incomplete: {}".format(filename)) with open(os.path.join(outdir, "coverage.log"), "a") as coveragelog: ret = self._generate(outdir, coveragelog) if ret == 0: logger.info("HTML report generated: {}".format( os.path.join(outdir, "coverage", "index.html"))) class Lcov(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('*' + pattern + '*') def add_ignore_directory(self, pattern): self.ignores.append('*/' + pattern + '/*') def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.info") ztestfile = os.path.join(outdir, "ztest.info") cmd = ["lcov", "--gcov-tool", self.gcov_tool, "--capture", "--directory", outdir, "--rc", "lcov_branch_coverage=1", "--output-file", coveragefile] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--extract", coveragefile, os.path.join(self.base_dir, "tests", "ztest", "*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--remove", ztestfile, os.path.join(self.base_dir, "tests/ztest/test/*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) files = [coveragefile, ztestfile] else: files = [coveragefile] for i in self.ignores: subprocess.call( ["lcov", "--gcov-tool", self.gcov_tool, "--remove", coveragefile, i, "--output-file", coveragefile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) # The --ignore-errors source option is added to avoid it exiting due to # samples/application_development/external_lib/ return subprocess.call(["genhtml", "--legend", "--branch-coverage", "--ignore-errors", "source", "-output-directory", os.path.join(outdir, "coverage")] + files, stdout=coveragelog) class Gcovr(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('.*' + pattern + '.*') def add_ignore_directory(self, pattern): self.ignores.append(".*/" + pattern + '/.*') @staticmethod def _interleave_list(prefix, list): tuple_list = [(prefix, item) for item in list] return [item for sublist in tuple_list for item in sublist] def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.json") ztestfile = os.path.join(outdir, "ztest.json") excludes = Gcovr._interleave_list("-e", self.ignores) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-e", "tests/*"] + excludes + ["--json", "-o", coveragefile, outdir] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) subprocess.call(["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-f", "tests/ztest", "-e", "tests/ztest/test/*", "--json", "-o", ztestfile, outdir], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: files = [coveragefile, ztestfile] else: files = [coveragefile] subdir = os.path.join(outdir, "coverage") os.makedirs(subdir, exist_ok=True) tracefiles = self._interleave_list("--add-tracefile", files) return subprocess.call(["gcovr", "-r", self.base_dir, "--html", "--html-details"] + tracefiles + ["-o", os.path.join(subdir, "index.html")], stdout=coveragelog) class DUT(object): def __init__(self, id=None, serial=None, platform=None, product=None, serial_pty=None, connected=False, pre_script=None, post_script=None, post_flash_script=None, runner=None): self.serial = serial self.platform = platform self.serial_pty = serial_pty self._counter = Value("i", 0) self._available = Value("i", 1) self.connected = connected self.pre_script = pre_script self.id = id self.product = product self.runner = runner self.fixtures = [] self.post_flash_script = post_flash_script self.post_script = post_script self.pre_script = pre_script self.probe_id = None self.notes = None self.match = False @property def available(self): with self._available.get_lock(): return self._available.value @available.setter def available(self, value): with self._available.get_lock(): self._available.value = value @property def counter(self): with self._counter.get_lock(): return self._counter.value @counter.setter def counter(self, value): with self._counter.get_lock(): self._counter.value = value def to_dict(self): d = {} exclude = ['_available', '_counter', 'match'] v = vars(self) for k in v.keys(): if k not in exclude and v[k]: d[k] = v[k] return d def __repr__(self): return f"<{self.platform} ({self.product}) on {self.serial}>" class HardwareMap: schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "hwmap-schema.yaml") manufacturer = [ 'ARM', 'SEGGER', 'MBED', 'STMicroelectronics', 'Atmel Corp.', 'Texas Instruments', 'Silicon Labs', 'NXP Semiconductors', 'Microchip Technology Inc.', 'FTDI', 'Digilent' ] runner_mapping = { 'pyocd': [ 'DAPLink CMSIS-DAP', 'MBED CMSIS-DAP' ], 'jlink': [ 'J-Link', 'J-Link OB' ], 'openocd': [ 'STM32 STLink', '^XDS110.*', 'STLINK-V3' ], 'dediprog': [ 'TTL232R-3V3', 'MCP2200 USB Serial Port Emulator' ] } def __init__(self): self.detected = [] self.duts = [] def add_device(self, serial, platform, pre_script, is_pty): device = DUT(platform=platform, connected=True, pre_script=pre_script) if is_pty: device.serial_pty = serial else: device.serial = serial self.duts.append(device) def load(self, map_file): hwm_schema = scl.yaml_load(self.schema_path) duts = scl.yaml_load_verify(map_file, hwm_schema) for dut in duts: pre_script = dut.get('pre_script') post_script = dut.get('post_script') post_flash_script = dut.get('post_flash_script') platform = dut.get('platform') id = dut.get('id') runner = dut.get('runner') serial = dut.get('serial') product = dut.get('product') fixtures = dut.get('fixtures', []) new_dut = DUT(platform=platform, product=product, runner=runner, id=id, serial=serial, connected=serial is not None, pre_script=pre_script, post_script=post_script, post_flash_script=post_flash_script) new_dut.fixtures = fixtures new_dut.counter = 0 self.duts.append(new_dut) def scan(self, persistent=False): from serial.tools import list_ports if persistent and platform.system() == 'Linux': # On Linux, /dev/serial/by-id provides symlinks to # '/dev/ttyACMx' nodes using names which are unique as # long as manufacturers fill out USB metadata nicely. # # This creates a map from '/dev/ttyACMx' device nodes # to '/dev/serial/by-id/usb-...' symlinks. The symlinks # go into the hardware map because they stay the same # even when the user unplugs / replugs the device. # # Some inexpensive USB/serial adapters don't result # in unique names here, though, so use of this feature # requires explicitly setting persistent=True. by_id = Path('/dev/serial/by-id') def readlink(link): return str((by_id / link).resolve()) persistent_map = {readlink(link): str(link) for link in by_id.iterdir()} else: persistent_map = {} serial_devices = list_ports.comports() logger.info("Scanning connected hardware...") for d in serial_devices: if d.manufacturer in self.manufacturer: # TI XDS110 can have multiple serial devices for a single board # assume endpoint 0 is the serial, skip all others if d.manufacturer == 'Texas Instruments' and not d.location.endswith('0'): continue s_dev = DUT(platform="unknown", id=d.serial_number, serial=persistent_map.get(d.device, d.device), product=d.product, runner='unknown') for runner, _ in self.runner_mapping.items(): products = self.runner_mapping.get(runner) if d.product in products: s_dev.runner = runner continue # Try regex matching for p in products: if re.match(p, d.product): s_dev.runner = runner s_dev.connected = True self.detected.append(s_dev) else: logger.warning("Unsupported device (%s): %s" % (d.manufacturer, d)) def save(self, hwm_file): # use existing map self.detected.sort(key=lambda x: x.serial or '') if os.path.exists(hwm_file): with open(hwm_file, 'r') as yaml_file: hwm = yaml.load(yaml_file, Loader=SafeLoader) if hwm: hwm.sort(key=lambda x: x['serial'] or '') # disconnect everything for h in hwm: h['connected'] = False h['serial'] = None for _detected in self.detected: for h in hwm: if _detected.id == h['id'] and _detected.product == h['product'] and not _detected.match: h['connected'] = True h['serial'] = _detected.serial _detected.match = True new_duts = list(filter(lambda d: not d.match, self.detected)) new = [] for d in new_duts: new.append(d.to_dict()) if hwm: hwm = hwm + new else: hwm = new with open(hwm_file, 'w') as yaml_file: yaml.dump(hwm, yaml_file, Dumper=Dumper, default_flow_style=False) self.load(hwm_file) logger.info("Registered devices:") self.dump() else: # create new file dl = [] for _connected in self.detected: platform = _connected.platform id = _connected.id runner = _connected.runner serial = _connected.serial product = _connected.product d = { 'platform': platform, 'id': id, 'runner': runner, 'serial': serial, 'product': product } dl.append(d) with open(hwm_file, 'w') as yaml_file: yaml.dump(dl, yaml_file, Dumper=Dumper, default_flow_style=False) logger.info("Detected devices:") self.dump(detected=True) def dump(self, filtered=[], header=[], connected_only=False, detected=False): print("") table = [] if detected: to_show = self.detected else: to_show = self.duts if not header: header = ["Platform", "ID", "Serial device"] for p in to_show: platform = p.platform connected = p.connected if filtered and platform not in filtered: continue if not connected_only or connected: table.append([platform, p.id, p.serial]) print(tabulate(table, headers=header, tablefmt="github")) def size_report(sc): logger.info(sc.filename) logger.info("SECTION NAME VMA LMA SIZE HEX SZ TYPE") for i in range(len(sc.sections)): v = sc.sections[i] logger.info("%-17s 0x%08x 0x%08x %8d 0x%05x %-7s" % (v["name"], v["virt_addr"], v["load_addr"], v["size"], v["size"], v["type"])) logger.info("Totals: %d bytes (ROM), %d bytes (RAM)" % (sc.rom_size, sc.ram_size)) logger.info("") def export_tests(filename, tests): with open(filename, "wt") as csvfile: fieldnames = ['section', 'subsection', 'title', 'reference'] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) for test in tests: data = test.split(".") if len(data) > 1: subsec = " ".join(data[1].split("_")).title() rowdict = { "section": data[0].capitalize(), "subsection": subsec, "title": test, "reference": test } cw.writerow(rowdict) else: logger.info("{} can't be exported".format(test)) twisterlib: add deprecated DT props to warnings_as_errors Use EXTRA_GEN_DEFINES_ARGS to error out on deprecated devicetree properties when warnings are treated as errors. Signed-off-by: Martí Bolívar <9d90ac4c7bf6a305f6bfd81a23c7859bc883380e@nordicsemi.no> #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # # Copyright (c) 2018 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import contextlib import string import mmap import sys import re import subprocess import select import shutil import shlex import signal import threading import concurrent.futures from collections import OrderedDict import queue import time import csv import glob import concurrent import xml.etree.ElementTree as ET import logging import pty from pathlib import Path from distutils.spawn import find_executable from colorama import Fore import pickle import platform import yaml import json from multiprocessing import Lock, Process, Value try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import SafeLoader, Dumper try: import serial except ImportError: print("Install pyserial python module with pip to use --device-testing option.") try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") try: import psutil except ImportError: print("Install psutil python module with pip to run in Qemu.") ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") # This is needed to load edt.pickle files. sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts")) import edtlib # pylint: disable=unused-import # Use this for internal comparisons; that's what canonicalization is # for. Don't use it when invoking other components of the build system # to avoid confusing and hard to trace inconsistencies in error messages # and logs, generated Makefiles, etc. compared to when users invoke these # components directly. # Note "normalization" is different from canonicalization, see os.path. canonical_zephyr_base = os.path.realpath(ZEPHYR_BASE) sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import scl import expr_parser logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ExecutionCounter(object): def __init__(self, total=0): self._done = Value('i', 0) self._passed = Value('i', 0) self._skipped_configs = Value('i', 0) self._skipped_runtime = Value('i', 0) self._skipped_cases = Value('i', 0) self._error = Value('i', 0) self._failed = Value('i', 0) self._total = Value('i', total) self._cases = Value('i', 0) self.lock = Lock() @property def cases(self): with self._cases.get_lock(): return self._cases.value @cases.setter def cases(self, value): with self._cases.get_lock(): self._cases.value = value @property def skipped_cases(self): with self._skipped_cases.get_lock(): return self._skipped_cases.value @skipped_cases.setter def skipped_cases(self, value): with self._skipped_cases.get_lock(): self._skipped_cases.value = value @property def error(self): with self._error.get_lock(): return self._error.value @error.setter def error(self, value): with self._error.get_lock(): self._error.value = value @property def done(self): with self._done.get_lock(): return self._done.value @done.setter def done(self, value): with self._done.get_lock(): self._done.value = value @property def passed(self): with self._passed.get_lock(): return self._passed.value @passed.setter def passed(self, value): with self._passed.get_lock(): self._passed.value = value @property def skipped_configs(self): with self._skipped_configs.get_lock(): return self._skipped_configs.value @skipped_configs.setter def skipped_configs(self, value): with self._skipped_configs.get_lock(): self._skipped_configs.value = value @property def skipped_runtime(self): with self._skipped_runtime.get_lock(): return self._skipped_runtime.value @skipped_runtime.setter def skipped_runtime(self, value): with self._skipped_runtime.get_lock(): self._skipped_runtime.value = value @property def failed(self): with self._failed.get_lock(): return self._failed.value @failed.setter def failed(self, value): with self._failed.get_lock(): self._failed.value = value @property def total(self): with self._total.get_lock(): return self._total.value class CMakeCacheEntry: '''Represents a CMake cache entry. This class understands the type system in a CMakeCache.txt, and converts the following cache types to Python types: Cache Type Python type ---------- ------------------------------------------- FILEPATH str PATH str STRING str OR list of str (if ';' is in the value) BOOL bool INTERNAL str OR list of str (if ';' is in the value) ---------- ------------------------------------------- ''' # Regular expression for a cache entry. # # CMake variable names can include escape characters, allowing a # wider set of names than is easy to match with a regular # expression. To be permissive here, use a non-greedy match up to # the first colon (':'). This breaks if the variable name has a # colon inside, but it's good enough. CACHE_ENTRY = re.compile( r'''(?P<name>.*?) # name :(?P<type>FILEPATH|PATH|STRING|BOOL|INTERNAL) # type =(?P<value>.*) # value ''', re.X) @classmethod def _to_bool(cls, val): # Convert a CMake BOOL string into a Python bool. # # "True if the constant is 1, ON, YES, TRUE, Y, or a # non-zero number. False if the constant is 0, OFF, NO, # FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in # the suffix -NOTFOUND. Named boolean constants are # case-insensitive. If the argument is not one of these # constants, it is treated as a variable." # # https://cmake.org/cmake/help/v3.0/command/if.html val = val.upper() if val in ('ON', 'YES', 'TRUE', 'Y'): return 1 elif val in ('OFF', 'NO', 'FALSE', 'N', 'IGNORE', 'NOTFOUND', ''): return 0 elif val.endswith('-NOTFOUND'): return 0 else: try: v = int(val) return v != 0 except ValueError as exc: raise ValueError('invalid bool {}'.format(val)) from exc @classmethod def from_line(cls, line, line_no): # Comments can only occur at the beginning of a line. # (The value of an entry could contain a comment character). if line.startswith('//') or line.startswith('#'): return None # Whitespace-only lines do not contain cache entries. if not line.strip(): return None m = cls.CACHE_ENTRY.match(line) if not m: return None name, type_, value = (m.group(g) for g in ('name', 'type', 'value')) if type_ == 'BOOL': try: value = cls._to_bool(value) except ValueError as exc: args = exc.args + ('on line {}: {}'.format(line_no, line),) raise ValueError(args) from exc elif type_ in ['STRING', 'INTERNAL']: # If the value is a CMake list (i.e. is a string which # contains a ';'), convert to a Python list. if ';' in value: value = value.split(';') return CMakeCacheEntry(name, value) def __init__(self, name, value): self.name = name self.value = value def __str__(self): fmt = 'CMakeCacheEntry(name={}, value={})' return fmt.format(self.name, self.value) class CMakeCache: '''Parses and represents a CMake cache file.''' @staticmethod def from_file(cache_file): return CMakeCache(cache_file) def __init__(self, cache_file): self.cache_file = cache_file self.load(cache_file) def load(self, cache_file): entries = [] with open(cache_file, 'r') as cache: for line_no, line in enumerate(cache): entry = CMakeCacheEntry.from_line(line, line_no) if entry: entries.append(entry) self._entries = OrderedDict((e.name, e) for e in entries) def get(self, name, default=None): entry = self._entries.get(name) if entry is not None: return entry.value else: return default def get_list(self, name, default=None): if default is None: default = [] entry = self._entries.get(name) if entry is not None: value = entry.value if isinstance(value, list): return value elif isinstance(value, str): return [value] if value else [] else: msg = 'invalid value {} type {}' raise RuntimeError(msg.format(value, type(value))) else: return default def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name].value def __setitem__(self, name, entry): if not isinstance(entry, CMakeCacheEntry): msg = 'improper type {} for value {}, expecting CMakeCacheEntry' raise TypeError(msg.format(type(entry), entry)) self._entries[name] = entry def __delitem__(self, name): del self._entries[name] def __iter__(self): return iter(self._entries.values()) class TwisterException(Exception): pass class TwisterRuntimeError(TwisterException): pass class ConfigurationError(TwisterException): def __init__(self, cfile, message): TwisterException.__init__(self, cfile + ": " + message) class BuildError(TwisterException): pass class ExecutionError(TwisterException): pass class HarnessImporter: def __init__(self, name): sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister")) module = __import__("harness") if name: my_class = getattr(module, name) else: my_class = getattr(module, "Test") self.instance = my_class() class Handler: def __init__(self, instance, type_str="build"): """Constructor """ self.state = "waiting" self.run = False self.duration = 0 self.type_str = type_str self.binary = None self.pid_fn = None self.call_make_run = False self.name = instance.name self.instance = instance self.timeout = instance.testcase.timeout self.sourcedir = instance.testcase.source_dir self.build_dir = instance.build_dir self.log = os.path.join(self.build_dir, "handler.log") self.returncode = 0 self.set_state("running", self.duration) self.generator = None self.generator_cmd = None self.args = [] def set_state(self, state, duration): self.state = state self.duration = duration def get_state(self): ret = (self.state, self.duration) return ret def record(self, harness): if harness.recording: filename = os.path.join(self.build_dir, "recording.csv") with open(filename, "at") as csvfile: cw = csv.writer(csvfile, harness.fieldnames, lineterminator=os.linesep) cw.writerow(harness.fieldnames) for instance in harness.recording: cw.writerow(instance) class BinaryHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.terminated = False self.call_west_flash = False # Tool options self.valgrind = False self.lsan = False self.asan = False self.ubsan = False self.coverage = False def try_kill_process_by_pid(self): if self.pid_fn: pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) self.pid_fn = None # clear so we don't try to kill the binary twice try: os.kill(pid, signal.SIGTERM) except ProcessLookupError: pass def terminate(self, proc): # encapsulate terminate functionality so we do it consistently where ever # we might want to terminate the proc. We need try_kill_process_by_pid # because of both how newer ninja (1.6.0 or greater) and .NET / renode # work. Newer ninja's don't seem to pass SIGTERM down to the children # so we need to use try_kill_process_by_pid. for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except ProcessLookupError: pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() self.terminated = True def _output_reader(self, proc): self.line = proc.stdout.readline() def _output_handler(self, proc, harness): log_out_fp = open(self.log, "wt") timeout_extended = False timeout_time = time.time() + self.timeout while True: this_timeout = timeout_time - time.time() if this_timeout < 0: break reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(this_timeout) if not reader_t.is_alive(): line = self.line logger.debug("OUTPUT: {0}".format(line.decode('utf-8').rstrip())) log_out_fp.write(line.decode('utf-8')) log_out_fp.flush() harness.handle(line.decode('utf-8').rstrip()) if harness.state: if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 else: reader_t.join(0) break try: # POSIX arch based ztests end on their own, # so let's give it up to 100ms to do so proc.wait(0.1) except subprocess.TimeoutExpired: self.terminate(proc) log_out_fp.close() def handle(self): harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) if self.call_make_run: command = [self.generator_cmd, "run"] elif self.call_west_flash: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] else: command = [self.binary] run_valgrind = False if self.valgrind and shutil.which("valgrind"): command = ["valgrind", "--error-exitcode=2", "--leak-check=full", "--suppressions=" + ZEPHYR_BASE + "/scripts/valgrind.supp", "--log-file=" + self.build_dir + "/valgrind.log" ] + command run_valgrind = True logger.debug("Spawning process: " + " ".join(shlex.quote(word) for word in command) + os.linesep + "in directory: " + self.build_dir) start_time = time.time() env = os.environ.copy() if self.asan: env["ASAN_OPTIONS"] = "log_path=stdout:" + \ env.get("ASAN_OPTIONS", "") if not self.lsan: env["ASAN_OPTIONS"] += "detect_leaks=0" if self.ubsan: env["UBSAN_OPTIONS"] = "log_path=stdout:halt_on_error=1:" + \ env.get("UBSAN_OPTIONS", "") with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir, env=env) as proc: logger.debug("Spawning BinaryHandler Thread for %s" % self.name) t = threading.Thread(target=self._output_handler, args=(proc, harness,), daemon=True) t.start() t.join() if t.is_alive(): self.terminate(proc) t.join() proc.wait() self.returncode = proc.returncode self.try_kill_process_by_pid() handler_time = time.time() - start_time if self.coverage: subprocess.call(["GCOV_PREFIX=" + self.build_dir, "gcov", self.sourcedir, "-b", "-s", self.build_dir], shell=True) # FIXME: This is needed when killing the simulator, the console is # garbled and needs to be reset. Did not find a better way to do that. if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) self.instance.results = harness.tests if not self.terminated and self.returncode != 0: # When a process is killed, the default handler returns 128 + SIGTERM # so in that case the return code itself is not meaningful self.set_state("failed", handler_time) self.instance.reason = "Failed" elif run_valgrind and self.returncode == 2: self.set_state("failed", handler_time) self.instance.reason = "Valgrind error" elif harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state("timeout", handler_time) self.instance.reason = "Timeout" self.record(harness) class DeviceHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.suite = None def monitor_serial(self, ser, halt_fileno, harness): log_out_fp = open(self.log, "wt") ser_fileno = ser.fileno() readlist = [halt_fileno, ser_fileno] if self.coverage: # Set capture_coverage to True to indicate that right after # test results we should get coverage data, otherwise we exit # from the test. harness.capture_coverage = True ser.flush() while ser.isOpen(): readable, _, _ = select.select(readlist, [], [], self.timeout) if halt_fileno in readable: logger.debug('halted') ser.close() break if ser_fileno not in readable: continue # Timeout. serial_line = None try: serial_line = ser.readline() except TypeError: pass except serial.SerialException: ser.close() break # Just because ser_fileno has data doesn't mean an entire line # is available yet. if serial_line: sl = serial_line.decode('utf-8', 'ignore').lstrip() logger.debug("DEVICE: {0}".format(sl.rstrip())) log_out_fp.write(sl) log_out_fp.flush() harness.handle(sl.rstrip()) if harness.state: if not harness.capture_coverage: ser.close() break log_out_fp.close() def get_available_device(self, instance): device = instance.platform.name for d in self.suite.duts: if d.platform == device and d.available and (d.serial or d.serial_pty): d.available = 0 d.counter += 1 return d return None def device_is_available(self, instance): device = instance.platform.name fixture = instance.testcase.harness_config.get("fixture") for d in self.suite.duts: if fixture and fixture not in d.fixtures: continue if d.platform == device and d.available and (d.serial or d.serial_pty): d.available = 0 d.counter += 1 return d return None def make_device_available(self, serial): for d in self.suite.duts: if d.serial == serial or d.serial_pty: d.available = 1 @staticmethod def run_custom_script(script, timeout): with subprocess.Popen(script, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, _ = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) except subprocess.TimeoutExpired: proc.kill() proc.communicate() logger.error("{} timed out".format(script)) def handle(self): out_state = "failed" runner = None hardware = self.device_is_available(self.instance) while not hardware: logger.debug("Waiting for device {} to become available".format(self.instance.platform.name)) time.sleep(1) hardware = self.device_is_available(self.instance) runner = hardware.runner or self.suite.west_runner serial_pty = hardware.serial_pty ser_pty_process = None if serial_pty: master, slave = pty.openpty() try: ser_pty_process = subprocess.Popen(re.split(',| ', serial_pty), stdout=master, stdin=master, stderr=master) except subprocess.CalledProcessError as error: logger.error("Failed to run subprocess {}, error {}".format(serial_pty, error.output)) return serial_device = os.ttyname(slave) else: serial_device = hardware.serial logger.debug("Using serial device {}".format(serial_device)) if (self.suite.west_flash is not None) or runner: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] command_extra_args = [] # There are three ways this option is used. # 1) bare: --west-flash # This results in options.west_flash == [] # 2) with a value: --west-flash="--board-id=42" # This results in options.west_flash == "--board-id=42" # 3) Multiple values: --west-flash="--board-id=42,--erase" # This results in options.west_flash == "--board-id=42 --erase" if self.suite.west_flash and self.suite.west_flash != []: command_extra_args.extend(self.suite.west_flash.split(',')) if runner: command.append("--runner") command.append(runner) board_id = hardware.probe_id or hardware.id product = hardware.product if board_id is not None: if runner == "pyocd": command_extra_args.append("--board-id") command_extra_args.append(board_id) elif runner == "nrfjprog": command_extra_args.append("--snr") command_extra_args.append(board_id) elif runner == "openocd" and product == "STM32 STLink": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "STLINK-V3": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "EDBG CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("cmsis_dap_serial %s" % (board_id)) elif runner == "jlink": command.append("--tool-opt=-SelectEmuBySN %s" % (board_id)) if command_extra_args != []: command.append('--') command.extend(command_extra_args) else: command = [self.generator_cmd, "-C", self.build_dir, "flash"] pre_script = hardware.pre_script post_flash_script = hardware.post_flash_script post_script = hardware.post_script if pre_script: self.run_custom_script(pre_script, 30) try: ser = serial.Serial( serial_device, baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=self.timeout ) except serial.SerialException as e: self.set_state("failed", 0) self.instance.reason = "Failed" logger.error("Serial device error: %s" % (str(e))) if serial_pty and ser_pty_process: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) self.make_device_available(serial_device) return ser.flush() harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) read_pipe, write_pipe = os.pipe() start_time = time.time() t = threading.Thread(target=self.monitor_serial, daemon=True, args=(ser, read_pipe, harness)) t.start() d_log = "{}/device.log".format(self.instance.build_dir) logger.debug('Flash command: %s', command) try: stdout = stderr = None with subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: (stdout, stderr) = proc.communicate(timeout=30) logger.debug(stdout.decode()) if proc.returncode != 0: self.instance.reason = "Device issue (Flash?)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.TimeoutExpired: proc.kill() (stdout, stderr) = proc.communicate() self.instance.reason = "Device issue (Timeout)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.CalledProcessError: os.write(write_pipe, b'x') # halt the thread if post_flash_script: self.run_custom_script(post_flash_script, 30) t.join(self.timeout) if t.is_alive(): logger.debug("Timed out while monitoring serial output on {}".format(self.instance.platform.name)) out_state = "timeout" if ser.isOpen(): ser.close() if serial_pty: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) os.close(write_pipe) os.close(read_pipe) handler_time = time.time() - start_time if out_state == "timeout": for c in self.instance.testcase.cases: if c not in harness.tests: harness.tests[c] = "BLOCK" self.instance.reason = "Timeout" self.instance.results = harness.tests # sometimes a test instance hasn't been executed successfully with an # empty dictionary results, in order to include it into final report, # so fill the results as BLOCK if self.instance.results == {}: for k in self.instance.testcase.cases: self.instance.results[k] = 'BLOCK' if harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state(out_state, handler_time) if post_script: self.run_custom_script(post_script, 30) self.make_device_available(serial_device) self.record(harness) class QEMUHandler(Handler): """Spawns a thread to monitor QEMU output from pipes We pass QEMU_PIPE to 'make run' and monitor the pipes for output. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") if "ignore_qemu_crash" in instance.testcase.tags: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process exection time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results, harness, ignore_unexpected_eof=False): fifo_in = fifo_fn + ".in" fifo_out = fifo_fn + ".out" # These in/out nodes are named from QEMU's perspective, not ours if os.path.exists(fifo_in): os.unlink(fifo_in) os.mkfifo(fifo_in) if os.path.exists(fifo_out): os.unlink(fifo_out) os.mkfifo(fifo_out) # We don't do anything with out_fp but we need to open it for # writing so that QEMU doesn't block, due to the way pipes work out_fp = open(fifo_in, "wb") # Disable internal buffering, we don't # want read() or poll() to ever block if there is data in there in_fp = open(fifo_out, "rb", buffering=0) log_out_fp = open(logfile, "wt") start_time = time.time() timeout_time = start_time + timeout p = select.poll() p.register(in_fp, select.POLLIN) out_state = None line = "" timeout_extended = False pid = 0 if os.path.exists(pid_fn): pid = int(open(pid_fn).read()) while True: this_timeout = int((timeout_time - time.time()) * 1000) if this_timeout < 0 or not p.poll(this_timeout): try: if pid and this_timeout > 0: #there's possibility we polled nothing because #of not enough CPU time scheduled by host for #QEMU process during p.poll(this_timeout) cpu_time = QEMUHandler._get_cpu_time(pid) if cpu_time < timeout and not out_state: timeout_time = time.time() + (timeout - cpu_time) continue except ProcessLookupError: out_state = "failed" break if not out_state: out_state = "timeout" break if pid == 0 and os.path.exists(pid_fn): pid = int(open(pid_fn).read()) try: c = in_fp.read(1).decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail out_state = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: out_state = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(line) log_out_fp.flush() line = line.strip() logger.debug(f"QEMU ({pid}): {line}") harness.handle(line) if harness.state: # if we have registered a fail make sure the state is not # overridden by a false success message coming from the # testsuite if out_state not in ['failed', 'unexpected eof', 'unexpected byte']: out_state = harness.state # if we get some state, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" handler.record(harness) handler_time = time.time() - start_time logger.debug(f"QEMU ({pid}) complete ({out_state}) after {handler_time} seconds") if out_state == "timeout": handler.instance.reason = "Timeout" handler.set_state("failed", handler_time) elif out_state == "failed": handler.instance.reason = "Failed" handler.set_state("failed", handler_time) elif out_state in ['unexpected eof', 'unexpected byte']: handler.instance.reason = out_state handler.set_state("failed", handler_time) else: handler.set_state(out_state, handler_time) log_out_fp.close() out_fp.close() in_fp.close() if pid: try: if pid: os.kill(pid, signal.SIGTERM) except ProcessLookupError: # Oh well, as long as it's dead! User probably sent Ctrl-C pass os.unlink(fifo_in) os.unlink(fifo_out) def handle(self): self.results = {} self.run = True # We pass this to QEMU which looks for fifos with .in and .out # suffixes. self.fifo_fn = os.path.join(self.instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(self.instance.build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log harness_import = HarnessImporter(self.instance.testcase.harness.capitalize()) harness = harness_import.instance harness.configure(self.instance) self.thread = threading.Thread(name=self.name, target=QEMUHandler._thread, args=(self, self.timeout, self.build_dir, self.log_fn, self.fifo_fn, self.pid_fn, self.results, harness, self.ignore_unexpected_eof)) self.instance.results = harness.tests self.thread.daemon = True logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread.start() if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) logger.debug("Running %s (%s)" % (self.name, self.type_str)) command = [self.generator_cmd] command += ["-C", self.build_dir, "run"] is_timeout = False qemu_pid = None with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) try: proc.wait(self.timeout) except subprocess.TimeoutExpired: # sometimes QEMU can't handle SIGTERM signal correctly # in that case kill -9 QEMU process directly and leave # twister to judge testing result by console output is_timeout = True if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) try: os.kill(qemu_pid, signal.SIGKILL) except ProcessLookupError: pass proc.wait() if harness.state == "passed": self.returncode = 0 else: self.returncode = proc.returncode else: proc.terminate() proc.kill() self.returncode = proc.returncode else: if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) logger.debug(f"No timeout, return code from QEMU ({qemu_pid}): {proc.returncode}") self.returncode = proc.returncode # Need to wait for harness to finish processing # output from QEMU. Otherwise it might miss some # error messages. self.thread.join() if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({qemu_pid}): {self.returncode}") if (self.returncode != 0 and not self.ignore_qemu_crash) or not harness.state: self.set_state("failed", 0) if is_timeout: self.instance.reason = "Timeout" else: self.instance.reason = "Exited with {}".format(self.returncode) def get_fifo(self): return self.fifo_fn class SizeCalculator: alloc_sections = [ "bss", "noinit", "app_bss", "app_noinit", "ccm_bss", "ccm_noinit" ] rw_sections = [ "datas", "initlevel", "exceptions", "initshell", "_static_thread_data_area", "k_timer_area", "k_mem_slab_area", "k_mem_pool_area", "sw_isr_table", "k_sem_area", "k_mutex_area", "app_shmem_regions", "_k_fifo_area", "_k_lifo_area", "k_stack_area", "k_msgq_area", "k_mbox_area", "k_pipe_area", "net_if_area", "net_if_dev_area", "net_l2_area", "net_l2_data", "k_queue_area", "_net_buf_pool_area", "app_datas", "kobject_data", "mmu_tables", "app_pad", "priv_stacks", "ccm_data", "usb_descriptor", "usb_data", "usb_bos_desc", "uart_mux", 'log_backends_sections', 'log_dynamic_sections', 'log_const_sections', "app_smem", 'shell_root_cmds_sections', 'log_const_sections', "font_entry_sections", "priv_stacks_noinit", "_GCOV_BSS_SECTION_NAME", "gcov", "nocache", "devices", "k_heap_area", ] # These get copied into RAM only on non-XIP ro_sections = [ "rom_start", "text", "ctors", "init_array", "reset", "z_object_assignment_area", "rodata", "net_l2", "vector", "sw_isr_table", "settings_handler_static_area", "bt_l2cap_fixed_chan_area", "bt_l2cap_br_fixed_chan_area", "bt_gatt_service_static_area", "vectors", "net_socket_register_area", "net_ppp_proto", "shell_area", "tracing_backend_area", "ppp_protocol_handler_area", ] def __init__(self, filename, extra_sections): """Constructor @param filename Path to the output binary The <filename> is parsed by objdump to determine section sizes """ # Make sure this is an ELF binary with open(filename, "rb") as f: magic = f.read(4) try: if magic != b'\x7fELF': raise TwisterRuntimeError("%s is not an ELF binary" % filename) except Exception as e: print(str(e)) sys.exit(2) # Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK. # GREP can not be used as it returns an error if the symbol is not # found. is_xip_command = "nm " + filename + \ " | awk '/CONFIG_XIP/ { print $3 }'" is_xip_output = subprocess.check_output( is_xip_command, shell=True, stderr=subprocess.STDOUT).decode( "utf-8").strip() try: if is_xip_output.endswith("no symbols"): raise TwisterRuntimeError("%s has no symbol information" % filename) except Exception as e: print(str(e)) sys.exit(2) self.is_xip = (len(is_xip_output) != 0) self.filename = filename self.sections = [] self.rom_size = 0 self.ram_size = 0 self.extra_sections = extra_sections self._calculate_sizes() def get_ram_size(self): """Get the amount of RAM the application will use up on the device @return amount of RAM, in bytes """ return self.ram_size def get_rom_size(self): """Get the size of the data that this application uses on device's flash @return amount of ROM, in bytes """ return self.rom_size def unrecognized_sections(self): """Get a list of sections inside the binary that weren't recognized @return list of unrecognized section names """ slist = [] for v in self.sections: if not v["recognized"]: slist.append(v["name"]) return slist def _calculate_sizes(self): """ Calculate RAM and ROM usage by section """ objdump_command = "objdump -h " + self.filename objdump_output = subprocess.check_output( objdump_command, shell=True).decode("utf-8").splitlines() for line in objdump_output: words = line.split() if not words: # Skip lines that are too short continue index = words[0] if not index[0].isdigit(): # Skip lines that do not start continue # with a digit name = words[1] # Skip lines with section names if name[0] == '.': # starting with '.' continue # TODO this doesn't actually reflect the size in flash or RAM as # it doesn't include linker-imposed padding between sections. # It is close though. size = int(words[2], 16) if size == 0: continue load_addr = int(words[4], 16) virt_addr = int(words[3], 16) # Add section to memory use totals (for both non-XIP and XIP scenarios) # Unrecognized section names are not included in the calculations. recognized = True if name in SizeCalculator.alloc_sections: self.ram_size += size stype = "alloc" elif name in SizeCalculator.rw_sections: self.ram_size += size self.rom_size += size stype = "rw" elif name in SizeCalculator.ro_sections: self.rom_size += size if not self.is_xip: self.ram_size += size stype = "ro" else: stype = "unknown" if name not in self.extra_sections: recognized = False self.sections.append({"name": name, "load_addr": load_addr, "size": size, "virt_addr": virt_addr, "type": stype, "recognized": recognized}) class TwisterConfigParser: """Class to read test case files with semantic checking """ def __init__(self, filename, schema): """Instantiate a new TwisterConfigParser object @param filename Source .yaml file to read """ self.data = {} self.schema = schema self.filename = filename self.tests = {} self.common = {} def load(self): self.data = scl.yaml_load_verify(self.filename, self.schema) if 'tests' in self.data: self.tests = self.data['tests'] if 'common' in self.data: self.common = self.data['common'] def _cast_value(self, value, typestr): if isinstance(value, str): v = value.strip() if typestr == "str": return v elif typestr == "float": return float(value) elif typestr == "int": return int(value) elif typestr == "bool": return value elif typestr.startswith("list") and isinstance(value, list): return value elif typestr.startswith("list") and isinstance(value, str): vs = v.split() if len(typestr) > 4 and typestr[4] == ":": return [self._cast_value(vsi, typestr[5:]) for vsi in vs] else: return vs elif typestr.startswith("set"): vs = v.split() if len(typestr) > 3 and typestr[3] == ":": return {self._cast_value(vsi, typestr[4:]) for vsi in vs} else: return set(vs) elif typestr.startswith("map"): return value else: raise ConfigurationError( self.filename, "unknown type '%s'" % value) def get_test(self, name, valid_keys): """Get a dictionary representing the keys/values within a test @param name The test in the .yaml file to retrieve data from @param valid_keys A dictionary representing the intended semantics for this test. Each key in this dictionary is a key that could be specified, if a key is given in the .yaml file which isn't in here, it will generate an error. Each value in this dictionary is another dictionary containing metadata: "default" - Default value if not given "type" - Data type to convert the text value to. Simple types supported are "str", "float", "int", "bool" which will get converted to respective Python data types. "set" and "list" may also be specified which will split the value by whitespace (but keep the elements as strings). finally, "list:<type>" and "set:<type>" may be given which will perform a type conversion after splitting the value up. "required" - If true, raise an error if not defined. If false and "default" isn't specified, a type conversion will be done on an empty string @return A dictionary containing the test key-value pairs with type conversion and default values filled in per valid_keys """ d = {} for k, v in self.common.items(): d[k] = v for k, v in self.tests[name].items(): if k in d: if isinstance(d[k], str): # By default, we just concatenate string values of keys # which appear both in "common" and per-test sections, # but some keys are handled in adhoc way based on their # semantics. if k == "filter": d[k] = "(%s) and (%s)" % (d[k], v) else: d[k] += " " + v else: d[k] = v for k, kinfo in valid_keys.items(): if k not in d: if "required" in kinfo: required = kinfo["required"] else: required = False if required: raise ConfigurationError( self.filename, "missing required value for '%s' in test '%s'" % (k, name)) else: if "default" in kinfo: default = kinfo["default"] else: default = self._cast_value("", kinfo["type"]) d[k] = default else: try: d[k] = self._cast_value(d[k], kinfo["type"]) except ValueError: raise ConfigurationError( self.filename, "bad %s value '%s' for key '%s' in name '%s'" % (kinfo["type"], d[k], k, name)) return d class Platform: """Class representing metadata for a particular platform Maps directly to BOARD when building""" platform_schema = scl.yaml_load(os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "platform-schema.yaml")) def __init__(self): """Constructor. """ self.name = "" self.twister = True # if no RAM size is specified by the board, take a default of 128K self.ram = 128 self.ignore_tags = [] self.only_tags = [] self.default = False # if no flash size is specified by the board, take a default of 512K self.flash = 512 self.supported = set() self.arch = "" self.type = "na" self.simulation = "na" self.supported_toolchains = [] self.env = [] self.env_satisfied = True self.filter_data = dict() def load(self, platform_file): scp = TwisterConfigParser(platform_file, self.platform_schema) scp.load() data = scp.data self.name = data['identifier'] self.twister = data.get("twister", True) # if no RAM size is specified by the board, take a default of 128K self.ram = data.get("ram", 128) testing = data.get("testing", {}) self.ignore_tags = testing.get("ignore_tags", []) self.only_tags = testing.get("only_tags", []) self.default = testing.get("default", False) # if no flash size is specified by the board, take a default of 512K self.flash = data.get("flash", 512) self.supported = set() for supp_feature in data.get("supported", []): for item in supp_feature.split(":"): self.supported.add(item) self.arch = data['arch'] self.type = data.get('type', "na") self.simulation = data.get('simulation', "na") self.supported_toolchains = data.get("toolchain", []) self.env = data.get("env", []) self.env_satisfied = True for env in self.env: if not os.environ.get(env, None): self.env_satisfied = False def __repr__(self): return "<%s on %s>" % (self.name, self.arch) class DisablePyTestCollectionMixin(object): __test__ = False class TestCase(DisablePyTestCollectionMixin): """Class representing a test application """ def __init__(self, testcase_root, workdir, name): """TestCase constructor. This gets called by TestSuite as it finds and reads test yaml files. Multiple TestCase instances may be generated from a single testcase.yaml, each one corresponds to an entry within that file. We need to have a unique name for every single test case. Since a testcase.yaml can define multiple tests, the canonical name for the test case is <workdir>/<name>. @param testcase_root os.path.abspath() of one of the --testcase-root @param workdir Sub-directory of testcase_root where the .yaml test configuration file was found @param name Name of this test case, corresponding to the entry name in the test case configuration file. For many test cases that just define one test, can be anything and is usually "test". This is really only used to distinguish between different cases when the testcase.yaml defines multiple tests """ self.source_dir = "" self.yamlfile = "" self.cases = [] self.name = self.get_unique(testcase_root, workdir, name) self.id = name self.type = None self.tags = set() self.extra_args = None self.extra_configs = None self.arch_allow = None self.arch_exclude = None self.skip = False self.platform_exclude = None self.platform_allow = None self.toolchain_exclude = None self.toolchain_allow = None self.tc_filter = None self.timeout = 60 self.harness = "" self.harness_config = {} self.build_only = True self.build_on_all = False self.slow = False self.min_ram = -1 self.depends_on = None self.min_flash = -1 self.extra_sections = None self.integration_platforms = [] @staticmethod def get_unique(testcase_root, workdir, name): canonical_testcase_root = os.path.realpath(testcase_root) if Path(canonical_zephyr_base) in Path(canonical_testcase_root).parents: # This is in ZEPHYR_BASE, so include path in name for uniqueness # FIXME: We should not depend on path of test for unique names. relative_tc_root = os.path.relpath(canonical_testcase_root, start=canonical_zephyr_base) else: relative_tc_root = "" # workdir can be "." unique = os.path.normpath(os.path.join(relative_tc_root, workdir, name)) check = name.split(".") if len(check) < 2: raise TwisterException(f"""bad test name '{name}' in {testcase_root}/{workdir}. \ Tests should reference the category and subsystem with a dot as a separator. """ ) return unique @staticmethod def scan_file(inf_name): suite_regex = re.compile( # do not match until end-of-line, otherwise we won't allow # stc_regex below to catch the ones that are declared in the same # line--as we only search starting the end of this match br"^\s*ztest_test_suite\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) stc_regex = re.compile( br"^\s*" # empy space at the beginning is ok # catch the case where it is declared in the same sentence, e.g: # # ztest_test_suite(mutex_complex, ztest_user_unit_test(TESTNAME)); br"(?:ztest_test_suite\([a-zA-Z0-9_]+,\s*)?" # Catch ztest[_user]_unit_test-[_setup_teardown](TESTNAME) br"ztest_(?:1cpu_)?(?:user_)?unit_test(?:_setup_teardown)?" # Consume the argument that becomes the extra testcse br"\(\s*" br"(?P<stc_name>[a-zA-Z0-9_]+)" # _setup_teardown() variant has two extra arguments that we ignore br"(?:\s*,\s*[a-zA-Z0-9_]+\s*,\s*[a-zA-Z0-9_]+)?" br"\s*\)", # We don't check how it finishes; we don't care re.MULTILINE) suite_run_regex = re.compile( br"^\s*ztest_run_test_suite\((?P<suite_name>[a-zA-Z0-9_]+)\)", re.MULTILINE) achtung_regex = re.compile( br"(#ifdef|#endif)", re.MULTILINE) warnings = None with open(inf_name) as inf: if os.name == 'nt': mmap_args = {'fileno': inf.fileno(), 'length': 0, 'access': mmap.ACCESS_READ} else: mmap_args = {'fileno': inf.fileno(), 'length': 0, 'flags': mmap.MAP_PRIVATE, 'prot': mmap.PROT_READ, 'offset': 0} with contextlib.closing(mmap.mmap(**mmap_args)) as main_c: suite_regex_match = suite_regex.search(main_c) if not suite_regex_match: # can't find ztest_test_suite, maybe a client, because # it includes ztest.h return None, None suite_run_match = suite_run_regex.search(main_c) if not suite_run_match: raise ValueError("can't find ztest_run_test_suite") achtung_matches = re.findall( achtung_regex, main_c[suite_regex_match.end():suite_run_match.start()]) if achtung_matches: warnings = "found invalid %s in ztest_test_suite()" \ % ", ".join(sorted({match.decode() for match in achtung_matches},reverse = True)) _matches = re.findall( stc_regex, main_c[suite_regex_match.end():suite_run_match.start()]) for match in _matches: if not match.decode().startswith("test_"): warnings = "Found a test that does not start with test_" matches = [match.decode().replace("test_", "", 1) for match in _matches] return matches, warnings def scan_path(self, path): subcases = [] for filename in glob.glob(os.path.join(path, "src", "*.c*")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) raise TwisterRuntimeError("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) for filename in glob.glob(os.path.join(path, "*.c")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) return subcases def parse_subcases(self, test_path): results = self.scan_path(test_path) for sub in results: name = "{}.{}".format(self.id, sub) self.cases.append(name) if not results: self.cases.append(self.id) def __str__(self): return self.name class TestInstance(DisablePyTestCollectionMixin): """Class representing the execution of a particular TestCase on a platform @param test The TestCase object we want to build/execute @param platform Platform object that we want to build and run against @param base_outdir Base directory for all test results. The actual out directory used is <outdir>/<platform>/<test case name> """ def __init__(self, testcase, platform, outdir): self.testcase = testcase self.platform = platform self.status = None self.reason = "Unknown" self.metrics = dict() self.handler = None self.outdir = outdir self.name = os.path.join(platform.name, testcase.name) self.build_dir = os.path.join(outdir, platform.name, testcase.name) self.run = False self.results = {} def __getstate__(self): d = self.__dict__.copy() return d def __setstate__(self, d): self.__dict__.update(d) def __lt__(self, other): return self.name < other.name @staticmethod def testcase_runnable(testcase, fixtures): can_run = False # console harness allows us to run the test and capture data. if testcase.harness in [ 'console', 'ztest']: can_run = True # if we have a fixture that is also being supplied on the # command-line, then we need to run the test, not just build it. fixture = testcase.harness_config.get('fixture') if fixture: can_run = (fixture in fixtures) elif testcase.harness: can_run = False else: can_run = True return can_run # Global testsuite parameters def check_runnable(self, enable_slow=False, filter='buildable', fixtures=[]): # right now we only support building on windows. running is still work # in progress. if os.name == 'nt': return False # we asked for build-only on the command line if self.testcase.build_only: return False # Do not run slow tests: skip_slow = self.testcase.slow and not enable_slow if skip_slow: return False target_ready = bool(self.testcase.type == "unit" or \ self.platform.type == "native" or \ self.platform.simulation in ["mdb-nsim", "nsim", "renode", "qemu", "tsim"] or \ filter == 'runnable') if self.platform.simulation == "nsim": if not find_executable("nsimdrv"): target_ready = False if self.platform.simulation == "mdb-nsim": if not find_executable("mdb"): target_ready = False if self.platform.simulation == "renode": if not find_executable("renode"): target_ready = False if self.platform.simulation == "tsim": if not find_executable("tsim-leon3"): target_ready = False testcase_runnable = self.testcase_runnable(self.testcase, fixtures) return testcase_runnable and target_ready def create_overlay(self, platform, enable_asan=False, enable_ubsan=False, enable_coverage=False, coverage_platform=[]): # Create this in a "twister/" subdirectory otherwise this # will pass this overlay to kconfig.py *twice* and kconfig.cmake # will silently give that second time precedence over any # --extra-args=CONFIG_* subdir = os.path.join(self.build_dir, "twister") content = "" if self.testcase.extra_configs: content = "\n".join(self.testcase.extra_configs) if enable_coverage: if platform.name in coverage_platform: content = content + "\nCONFIG_COVERAGE=y" content = content + "\nCONFIG_COVERAGE_DUMP=y" if enable_asan: if platform.type == "native": content = content + "\nCONFIG_ASAN=y" if enable_ubsan: if platform.type == "native": content = content + "\nCONFIG_UBSAN=y" if content: os.makedirs(subdir, exist_ok=True) file = os.path.join(subdir, "testcase_extra.conf") with open(file, "w") as f: f.write(content) return content def calculate_sizes(self): """Get the RAM/ROM sizes of a test case. This can only be run after the instance has been executed by MakeGenerator, otherwise there won't be any binaries to measure. @return A SizeCalculator object """ fns = glob.glob(os.path.join(self.build_dir, "zephyr", "*.elf")) fns.extend(glob.glob(os.path.join(self.build_dir, "zephyr", "*.exe"))) fns = [x for x in fns if not x.endswith('_prebuilt.elf')] if len(fns) != 1: raise BuildError("Missing/multiple output ELF binary") return SizeCalculator(fns[0], self.testcase.extra_sections) def fill_results_by_status(self): """Fills results according to self.status The method is used to propagate the instance level status to the test cases inside. Useful when the whole instance is skipped and the info is required also at the test cases level for reporting. Should be used with caution, e.g. should not be used to fill all results with passes """ status_to_verdict = { 'skipped': 'SKIP', 'error': 'BLOCK', 'failure': 'FAILED' } for k in self.results: self.results[k] = status_to_verdict[self.status] def __repr__(self): return "<TestCase %s on %s>" % (self.testcase.name, self.platform.name) class CMake(): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') def __init__(self, testcase, platform, source_dir, build_dir): self.cwd = None self.capture_output = True self.defconfig = {} self.cmake_cache = {} self.instance = None self.testcase = testcase self.platform = platform self.source_dir = source_dir self.build_dir = build_dir self.log = "build.log" self.generator = None self.generator_cmd = None def parse_generated(self): self.defconfig = {} return {} def run_build(self, args=[]): logger.debug("Building %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [] cmake_args.extend(args) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() results = {} if p.returncode == 0: msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) self.instance.status = "passed" results = {'msg': msg, "returncode": p.returncode, "instance": self.instance} if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) else: return None else: # A real error occurred, raise an exception log_msg = "" if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) if log_msg: res = re.findall("region `(FLASH|RAM|SRAM)' overflowed by", log_msg) if res and not self.overflow_as_errors: logger.debug("Test skipped due to {} Overflow".format(res[0])) self.instance.status = "skipped" self.instance.reason = "{} overflow".format(res[0]) else: self.instance.status = "error" self.instance.reason = "Build failure" results = { "returncode": p.returncode, "instance": self.instance, } return results def run_cmake(self, args=[]): if self.warnings_as_errors: ldflags = "-Wl,--fatal-warnings" cflags = "-Werror" aflags = "-Wa,--fatal-warnings" gen_defines_args = "--err-on-deprecated-properties" else: ldflags = cflags = aflags = "" gen_defines_args = "" logger.debug("Running cmake on %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [ f'-B{self.build_dir}', f'-S{self.source_dir}', f'-DEXTRA_CFLAGS="{cflags}"', f'-DEXTRA_AFLAGS="{aflags}', f'-DEXTRA_LDFLAGS="{ldflags}"', f'-DEXTRA_GEN_DEFINES_ARGS={gen_defines_args}', f'-G{self.generator}' ] if self.cmake_only: cmake_args.append("-DCMAKE_EXPORT_COMPILE_COMMANDS=1") args = ["-D{}".format(a.replace('"', '')) for a in args] cmake_args.extend(args) cmake_opts = ['-DBOARD={}'.format(self.platform.name)] cmake_args.extend(cmake_opts) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: filter_results = self.parse_generated() msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) logger.debug(msg) results = {'msg': msg, 'filter': filter_results} else: self.instance.status = "error" self.instance.reason = "Cmake build failure" logger.error("Cmake build failure: %s for %s" % (self.source_dir, self.platform.name)) results = {"returncode": p.returncode} if out: with open(os.path.join(self.build_dir, self.log), "a") as log: log_msg = out.decode(sys.getdefaultencoding()) log.write(log_msg) return results @staticmethod def run_cmake_script(args=[]): logger.debug("Running cmake script %s" % (args[0])) cmake_args = ["-D{}".format(a.replace('"', '')) for a in args[1:]] cmake_args.extend(['-P', args[0]]) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: msg = "Finished running %s" % (args[0]) logger.debug(msg) results = {"returncode": p.returncode, "msg": msg, "stdout": out} else: logger.error("Cmake script failure: %s" % (args[0])) results = {"returncode": p.returncode} return results class FilterBuilder(CMake): def __init__(self, testcase, platform, source_dir, build_dir): super().__init__(testcase, platform, source_dir, build_dir) self.log = "config-twister.log" def parse_generated(self): if self.platform.name == "unit_testing": return {} cmake_cache_path = os.path.join(self.build_dir, "CMakeCache.txt") defconfig_path = os.path.join(self.build_dir, "zephyr", ".config") with open(defconfig_path, "r") as fp: defconfig = {} for line in fp.readlines(): m = self.config_re.match(line) if not m: if line.strip() and not line.startswith("#"): sys.stderr.write("Unrecognized line %s\n" % line) continue defconfig[m.group(1)] = m.group(2).strip() self.defconfig = defconfig cmake_conf = {} try: cache = CMakeCache.from_file(cmake_cache_path) except FileNotFoundError: cache = {} for k in iter(cache): cmake_conf[k.name] = k.value self.cmake_cache = cmake_conf filter_data = { "ARCH": self.platform.arch, "PLATFORM": self.platform.name } filter_data.update(os.environ) filter_data.update(self.defconfig) filter_data.update(self.cmake_cache) edt_pickle = os.path.join(self.build_dir, "zephyr", "edt.pickle") if self.testcase and self.testcase.tc_filter: try: if os.path.exists(edt_pickle): with open(edt_pickle, 'rb') as f: edt = pickle.load(f) else: edt = None res = expr_parser.parse(self.testcase.tc_filter, filter_data, edt) except (ValueError, SyntaxError) as se: sys.stderr.write( "Failed processing %s\n" % self.testcase.yamlfile) raise se if not res: return {os.path.join(self.platform.name, self.testcase.name): True} else: return {os.path.join(self.platform.name, self.testcase.name): False} else: self.platform.filter_data = filter_data return filter_data class ProjectBuilder(FilterBuilder): def __init__(self, suite, instance, **kwargs): super().__init__(instance.testcase, instance.platform, instance.testcase.source_dir, instance.build_dir) self.log = "build.log" self.instance = instance self.suite = suite self.filtered_tests = 0 self.lsan = kwargs.get('lsan', False) self.asan = kwargs.get('asan', False) self.ubsan = kwargs.get('ubsan', False) self.valgrind = kwargs.get('valgrind', False) self.extra_args = kwargs.get('extra_args', []) self.device_testing = kwargs.get('device_testing', False) self.cmake_only = kwargs.get('cmake_only', False) self.cleanup = kwargs.get('cleanup', False) self.coverage = kwargs.get('coverage', False) self.inline_logs = kwargs.get('inline_logs', False) self.generator = kwargs.get('generator', None) self.generator_cmd = kwargs.get('generator_cmd', None) self.verbose = kwargs.get('verbose', None) self.warnings_as_errors = kwargs.get('warnings_as_errors', True) self.overflow_as_errors = kwargs.get('overflow_as_errors', False) @staticmethod def log_info(filename, inline_logs): filename = os.path.abspath(os.path.realpath(filename)) if inline_logs: logger.info("{:-^100}".format(filename)) try: with open(filename) as fp: data = fp.read() except Exception as e: data = "Unable to read log data (%s)\n" % (str(e)) logger.error(data) logger.info("{:-^100}".format(filename)) else: logger.error("see: " + Fore.YELLOW + filename + Fore.RESET) def log_info_file(self, inline_logs): build_dir = self.instance.build_dir h_log = "{}/handler.log".format(build_dir) b_log = "{}/build.log".format(build_dir) v_log = "{}/valgrind.log".format(build_dir) d_log = "{}/device.log".format(build_dir) if os.path.exists(v_log) and "Valgrind" in self.instance.reason: self.log_info("{}".format(v_log), inline_logs) elif os.path.exists(h_log) and os.path.getsize(h_log) > 0: self.log_info("{}".format(h_log), inline_logs) elif os.path.exists(d_log) and os.path.getsize(d_log) > 0: self.log_info("{}".format(d_log), inline_logs) else: self.log_info("{}".format(b_log), inline_logs) def setup_handler(self): instance = self.instance args = [] # FIXME: Needs simplification if instance.platform.simulation == "qemu": instance.handler = QEMUHandler(instance, "qemu") args.append("QEMU_PIPE=%s" % instance.handler.get_fifo()) instance.handler.call_make_run = True elif instance.testcase.type == "unit": instance.handler = BinaryHandler(instance, "unit") instance.handler.binary = os.path.join(instance.build_dir, "testbinary") if self.coverage: args.append("COVERAGE=1") elif instance.platform.type == "native": handler = BinaryHandler(instance, "native") handler.asan = self.asan handler.valgrind = self.valgrind handler.lsan = self.lsan handler.ubsan = self.ubsan handler.coverage = self.coverage handler.binary = os.path.join(instance.build_dir, "zephyr", "zephyr.exe") instance.handler = handler elif instance.platform.simulation == "renode": if find_executable("renode"): instance.handler = BinaryHandler(instance, "renode") instance.handler.pid_fn = os.path.join(instance.build_dir, "renode.pid") instance.handler.call_make_run = True elif instance.platform.simulation == "tsim": instance.handler = BinaryHandler(instance, "tsim") instance.handler.call_make_run = True elif self.device_testing: instance.handler = DeviceHandler(instance, "device") instance.handler.coverage = self.coverage elif instance.platform.simulation == "nsim": if find_executable("nsimdrv"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "mdb-nsim": if find_executable("mdb"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.pid_fn = os.path.join(instance.build_dir, "mdb.pid") instance.handler.call_west_flash = True if instance.handler: instance.handler.args = args instance.handler.generator_cmd = self.generator_cmd instance.handler.generator = self.generator def process(self, pipeline, done, message, lock, results): op = message.get('op') if not self.instance.handler: self.setup_handler() # The build process, call cmake and build with configured generator if op == "cmake": res = self.cmake() if self.instance.status in ["failed", "error"]: pipeline.put({"op": "report", "test": self.instance}) elif self.cmake_only: if self.instance.status is None: self.instance.status = "passed" pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.name in res['filter'] and res['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = "skipped" self.instance.reason = "filter" results.skipped_runtime += 1 for case in self.instance.testcase.cases: self.instance.results.update({case: 'SKIP'}) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "build", "test": self.instance}) elif op == "build": logger.debug("build test: %s" % self.instance.name) res = self.build() if not res: self.instance.status = "error" self.instance.reason = "Build Failure" pipeline.put({"op": "report", "test": self.instance}) else: # Count skipped cases during build, for example # due to ram/rom overflow. inst = res.get("instance", None) if inst and inst.status == "skipped": results.skipped_runtime += 1 if res.get('returncode', 1) > 0: pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.run and self.instance.handler: pipeline.put({"op": "run", "test": self.instance}) else: pipeline.put({"op": "report", "test": self.instance}) # Run the generated binary using one of the supported handlers elif op == "run": logger.debug("run test: %s" % self.instance.name) self.run() self.instance.status, _ = self.instance.handler.get_state() logger.debug(f"run status: {self.instance.name} {self.instance.status}") # to make it work with pickle self.instance.handler.thread = None self.instance.handler.suite = None pipeline.put({ "op": "report", "test": self.instance, "status": self.instance.status, "reason": self.instance.reason } ) # Report results and output progress to screen elif op == "report": with lock: done.put(self.instance) self.report_out(results) if self.cleanup and not self.coverage and self.instance.status == "passed": pipeline.put({ "op": "cleanup", "test": self.instance }) elif op == "cleanup": if self.device_testing: self.cleanup_device_testing_artifacts() else: self.cleanup_artifacts() def cleanup_artifacts(self, additional_keep=[]): logger.debug("Cleaning up {}".format(self.instance.build_dir)) allow = [ 'zephyr/.config', 'handler.log', 'build.log', 'device.log', 'recording.csv', ] allow += additional_keep allow = [os.path.join(self.instance.build_dir, file) for file in allow] for dirpath, dirnames, filenames in os.walk(self.instance.build_dir, topdown=False): for name in filenames: path = os.path.join(dirpath, name) if path not in allow: os.remove(path) # Remove empty directories and symbolic links to directories for dir in dirnames: path = os.path.join(dirpath, dir) if os.path.islink(path): os.remove(path) elif not os.listdir(path): os.rmdir(path) def cleanup_device_testing_artifacts(self): logger.debug("Cleaning up for Device Testing {}".format(self.instance.build_dir)) sanitizelist = [ 'CMakeCache.txt', 'zephyr/runners.yaml', ] keep = [ 'zephyr/zephyr.hex', 'zephyr/zephyr.bin', 'zephyr/zephyr.elf', ] keep += sanitizelist self.cleanup_artifacts(keep) # sanitize paths so files are relocatable for file in sanitizelist: file = os.path.join(self.instance.build_dir, file) with open(file, "rt") as fin: data = fin.read() data = data.replace(canonical_zephyr_base+"/", "") with open(file, "wt") as fin: fin.write(data) def report_out(self, results): total_to_do = results.total - results.skipped_configs total_tests_width = len(str(total_to_do)) results.done += 1 instance = self.instance if instance.status in ["error", "failed", "timeout"]: if instance.status == "error": results.error += 1 results.failed += 1 if self.verbose: status = Fore.RED + "FAILED " + Fore.RESET + instance.reason else: print("") logger.error( "{:<25} {:<50} {}FAILED{}: {}".format( instance.platform.name, instance.testcase.name, Fore.RED, Fore.RESET, instance.reason)) if not self.verbose: self.log_info_file(self.inline_logs) elif instance.status == "skipped": status = Fore.YELLOW + "SKIPPED" + Fore.RESET elif instance.status == "passed": status = Fore.GREEN + "PASSED" + Fore.RESET else: logger.debug(f"Unknown status = {instance.status}") status = Fore.YELLOW + "UNKNOWN" + Fore.RESET if self.verbose: if self.cmake_only: more_info = "cmake" elif instance.status == "skipped": more_info = instance.reason else: if instance.handler and instance.run: more_info = instance.handler.type_str htime = instance.handler.duration if htime: more_info += " {:.3f}s".format(htime) else: more_info = "build" logger.info("{:>{}}/{} {:<25} {:<50} {} ({})".format( results.done, total_tests_width, total_to_do, instance.platform.name, instance.testcase.name, status, more_info)) if instance.status in ["error", "failed", "timeout"]: self.log_info_file(self.inline_logs) else: completed_perc = 0 if total_to_do > 0: completed_perc = int((float(results.done) / total_to_do) * 100) skipped = results.skipped_configs + results.skipped_runtime sys.stdout.write("\rINFO - Total complete: %s%4d/%4d%s %2d%% skipped: %s%4d%s, failed: %s%4d%s" % ( Fore.GREEN, results.done, total_to_do, Fore.RESET, completed_perc, Fore.YELLOW if skipped > 0 else Fore.RESET, skipped, Fore.RESET, Fore.RED if results.failed > 0 else Fore.RESET, results.failed, Fore.RESET ) ) sys.stdout.flush() def cmake(self): instance = self.instance args = self.testcase.extra_args[:] args += self.extra_args if instance.handler: args += instance.handler.args # merge overlay files into one variable def extract_overlays(args): re_overlay = re.compile('OVERLAY_CONFIG=(.*)') other_args = [] overlays = [] for arg in args: match = re_overlay.search(arg) if match: overlays.append(match.group(1).strip('\'"')) else: other_args.append(arg) args[:] = other_args return overlays overlays = extract_overlays(args) if os.path.exists(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")): overlays.append(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")) if overlays: args.append("OVERLAY_CONFIG=\"%s\"" % (" ".join(overlays))) res = self.run_cmake(args) return res def build(self): res = self.run_build(['--build', self.build_dir]) return res def run(self): instance = self.instance if instance.handler: if instance.handler.type_str == "device": instance.handler.suite = self.suite instance.handler.handle() sys.stdout.flush() class TestSuite(DisablePyTestCollectionMixin): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') tc_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "testcase-schema.yaml")) testcase_valid_keys = {"tags": {"type": "set", "required": False}, "type": {"type": "str", "default": "integration"}, "extra_args": {"type": "list"}, "extra_configs": {"type": "list"}, "build_only": {"type": "bool", "default": False}, "build_on_all": {"type": "bool", "default": False}, "skip": {"type": "bool", "default": False}, "slow": {"type": "bool", "default": False}, "timeout": {"type": "int", "default": 60}, "min_ram": {"type": "int", "default": 8}, "depends_on": {"type": "set"}, "min_flash": {"type": "int", "default": 32}, "arch_allow": {"type": "set"}, "arch_exclude": {"type": "set"}, "extra_sections": {"type": "list", "default": []}, "integration_platforms": {"type": "list", "default": []}, "platform_exclude": {"type": "set"}, "platform_allow": {"type": "set"}, "toolchain_exclude": {"type": "set"}, "toolchain_allow": {"type": "set"}, "filter": {"type": "str"}, "harness": {"type": "str"}, "harness_config": {"type": "map", "default": {}} } RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "release", "twister_last_release.csv") SAMPLE_FILENAME = 'sample.yaml' TESTCASE_FILENAME = 'testcase.yaml' def __init__(self, board_root_list=[], testcase_roots=[], outdir=None): self.roots = testcase_roots if not isinstance(board_root_list, list): self.board_roots = [board_root_list] else: self.board_roots = board_root_list # Testsuite Options self.coverage_platform = [] self.build_only = False self.cmake_only = False self.cleanup = False self.enable_slow = False self.device_testing = False self.fixtures = [] self.enable_coverage = False self.enable_ubsan = False self.enable_lsan = False self.enable_asan = False self.enable_valgrind = False self.extra_args = [] self.inline_logs = False self.enable_sizes_report = False self.west_flash = None self.west_runner = None self.generator = None self.generator_cmd = None self.warnings_as_errors = True self.overflow_as_errors = False # Keep track of which test cases we've filtered out and why self.testcases = {} self.platforms = [] self.selected_platforms = [] self.filtered_platforms = [] self.default_platforms = [] self.outdir = os.path.abspath(outdir) self.discards = {} self.load_errors = 0 self.instances = dict() self.total_platforms = 0 self.start_time = 0 self.duration = 0 self.warnings = 0 # hardcoded for now self.duts = [] # run integration tests only self.integration = False self.pipeline = None self.version = "NA" def check_zephyr_version(self): try: subproc = subprocess.run(["git", "describe", "--abbrev=12"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: self.version = subproc.stdout.strip() logger.info(f"Zephyr version: {self.version}") except OSError: logger.info("Cannot read zephyr version.") def get_platform_instances(self, platform): filtered_dict = {k:v for k,v in self.instances.items() if k.startswith(platform + "/")} return filtered_dict def config(self): logger.info("coverage platform: {}".format(self.coverage_platform)) # Debug Functions @staticmethod def info(what): sys.stdout.write(what + "\n") sys.stdout.flush() def update_counting(self, results=None, initial=False): results.skipped_configs = 0 results.skipped_cases = 0 for instance in self.instances.values(): if initial: results.cases += len(instance.testcase.cases) if instance.status == 'skipped': results.skipped_configs += 1 results.skipped_cases += len(instance.testcase.cases) elif instance.status == "passed": results.passed += 1 for res in instance.results.values(): if res == 'SKIP': results.skipped_cases += 1 def compare_metrics(self, filename): # name, datatype, lower results better interesting_metrics = [("ram_size", int, True), ("rom_size", int, True)] if not os.path.exists(filename): logger.error("Cannot compare metrics, %s not found" % filename) return [] results = [] saved_metrics = {} with open(filename) as fp: cr = csv.DictReader(fp) for row in cr: d = {} for m, _, _ in interesting_metrics: d[m] = row[m] saved_metrics[(row["test"], row["platform"])] = d for instance in self.instances.values(): mkey = (instance.testcase.name, instance.platform.name) if mkey not in saved_metrics: continue sm = saved_metrics[mkey] for metric, mtype, lower_better in interesting_metrics: if metric not in instance.metrics: continue if sm[metric] == "": continue delta = instance.metrics.get(metric, 0) - mtype(sm[metric]) if delta == 0: continue results.append((instance, metric, instance.metrics.get(metric, 0), delta, lower_better)) return results def footprint_reports(self, report, show_footprint, all_deltas, footprint_threshold, last_metrics): if not report: return logger.debug("running footprint_reports") deltas = self.compare_metrics(report) warnings = 0 if deltas and show_footprint: for i, metric, value, delta, lower_better in deltas: if not all_deltas and ((delta < 0 and lower_better) or (delta > 0 and not lower_better)): continue percentage = 0 if value > delta: percentage = (float(delta) / float(value - delta)) if not all_deltas and (percentage < (footprint_threshold / 100.0)): continue logger.info("{:<25} {:<60} {}{}{}: {} {:<+4}, is now {:6} {:+.2%}".format( i.platform.name, i.testcase.name, Fore.YELLOW, "INFO" if all_deltas else "WARNING", Fore.RESET, metric, delta, value, percentage)) warnings += 1 if warnings: logger.warning("Deltas based on metrics from last %s" % ("release" if not last_metrics else "run")) def summary(self, results, unrecognized_sections): failed = 0 run = 0 for instance in self.instances.values(): if instance.status == "failed": failed += 1 elif instance.metrics.get("unrecognized") and not unrecognized_sections: logger.error("%sFAILED%s: %s has unrecognized binary sections: %s" % (Fore.RED, Fore.RESET, instance.name, str(instance.metrics.get("unrecognized", [])))) failed += 1 if instance.metrics.get('handler_time', None): run += 1 if results.total and results.total != results.skipped_configs: pass_rate = (float(results.passed) / float(results.total - results.skipped_configs)) else: pass_rate = 0 logger.info( "{}{} of {}{} test configurations passed ({:.2%}), {}{}{} failed, {} skipped with {}{}{} warnings in {:.2f} seconds".format( Fore.RED if failed else Fore.GREEN, results.passed, results.total - results.skipped_configs, Fore.RESET, pass_rate, Fore.RED if results.failed else Fore.RESET, results.failed, Fore.RESET, results.skipped_configs, Fore.YELLOW if self.warnings else Fore.RESET, self.warnings, Fore.RESET, self.duration)) self.total_platforms = len(self.platforms) # if we are only building, do not report about tests being executed. if self.platforms and not self.build_only: logger.info("In total {} test cases were executed, {} skipped on {} out of total {} platforms ({:02.2f}%)".format( results.cases - results.skipped_cases, results.skipped_cases, len(self.filtered_platforms), self.total_platforms, (100 * len(self.filtered_platforms) / len(self.platforms)) )) logger.info(f"{Fore.GREEN}{run}{Fore.RESET} test configurations executed on platforms, \ {Fore.RED}{results.total - run - results.skipped_configs}{Fore.RESET} test configurations were only built.") def save_reports(self, name, suffix, report_dir, no_update, release, only_failed, platform_reports, json_report): if not self.instances: return logger.info("Saving reports...") if name: report_name = name else: report_name = "twister" if report_dir: os.makedirs(report_dir, exist_ok=True) filename = os.path.join(report_dir, report_name) outdir = report_dir else: filename = os.path.join(self.outdir, report_name) outdir = self.outdir if suffix: filename = "{}_{}".format(filename, suffix) if not no_update: self.xunit_report(filename + ".xml", full_report=False, append=only_failed, version=self.version) self.xunit_report(filename + "_report.xml", full_report=True, append=only_failed, version=self.version) self.csv_report(filename + ".csv") if json_report: self.json_report(filename + ".json", append=only_failed, version=self.version) if platform_reports: self.target_report(outdir, suffix, append=only_failed) if self.discards: self.discard_report(filename + "_discard.csv") if release: self.csv_report(self.RELEASE_DATA) def add_configurations(self): for board_root in self.board_roots: board_root = os.path.abspath(board_root) logger.debug("Reading platform configuration files under %s..." % board_root) for file in glob.glob(os.path.join(board_root, "*", "*", "*.yaml")): try: platform = Platform() platform.load(file) if platform.name in [p.name for p in self.platforms]: logger.error(f"Duplicate platform {platform.name} in {file}") raise Exception(f"Duplicate platform identifier {platform.name} found") if platform.twister: self.platforms.append(platform) if platform.default: self.default_platforms.append(platform.name) except RuntimeError as e: logger.error("E: %s: can't load: %s" % (file, e)) self.load_errors += 1 def get_all_tests(self): tests = [] for _, tc in self.testcases.items(): for case in tc.cases: tests.append(case) return tests @staticmethod def get_toolchain(): toolchain_script = Path(ZEPHYR_BASE) / Path('cmake/verify-toolchain.cmake') result = CMake.run_cmake_script([toolchain_script, "FORMAT=json"]) try: if result['returncode']: raise TwisterRuntimeError("E: Variable ZEPHYR_TOOLCHAIN_VARIANT is not defined") except Exception as e: print(str(e)) sys.exit(2) toolchain = json.loads(result['stdout'])['ZEPHYR_TOOLCHAIN_VARIANT'] logger.info(f"Using '{toolchain}' toolchain.") return toolchain def add_testcases(self, testcase_filter=[]): for root in self.roots: root = os.path.abspath(root) logger.debug("Reading test case configuration files under %s..." % root) for dirpath, dirnames, filenames in os.walk(root, topdown=True): if self.SAMPLE_FILENAME in filenames: filename = self.SAMPLE_FILENAME elif self.TESTCASE_FILENAME in filenames: filename = self.TESTCASE_FILENAME else: continue logger.debug("Found possible test case in " + dirpath) dirnames[:] = [] tc_path = os.path.join(dirpath, filename) try: parsed_data = TwisterConfigParser(tc_path, self.tc_schema) parsed_data.load() tc_path = os.path.dirname(tc_path) workdir = os.path.relpath(tc_path, root) for name in parsed_data.tests.keys(): tc = TestCase(root, workdir, name) tc_dict = parsed_data.get_test(name, self.testcase_valid_keys) tc.source_dir = tc_path tc.yamlfile = tc_path tc.type = tc_dict["type"] tc.tags = tc_dict["tags"] tc.extra_args = tc_dict["extra_args"] tc.extra_configs = tc_dict["extra_configs"] tc.arch_allow = tc_dict["arch_allow"] tc.arch_exclude = tc_dict["arch_exclude"] tc.skip = tc_dict["skip"] tc.platform_exclude = tc_dict["platform_exclude"] tc.platform_allow = tc_dict["platform_allow"] tc.toolchain_exclude = tc_dict["toolchain_exclude"] tc.toolchain_allow = tc_dict["toolchain_allow"] tc.tc_filter = tc_dict["filter"] tc.timeout = tc_dict["timeout"] tc.harness = tc_dict["harness"] tc.harness_config = tc_dict["harness_config"] if tc.harness == 'console' and not tc.harness_config: raise Exception('Harness config error: console harness defined without a configuration.') tc.build_only = tc_dict["build_only"] tc.build_on_all = tc_dict["build_on_all"] tc.slow = tc_dict["slow"] tc.min_ram = tc_dict["min_ram"] tc.depends_on = tc_dict["depends_on"] tc.min_flash = tc_dict["min_flash"] tc.extra_sections = tc_dict["extra_sections"] tc.integration_platforms = tc_dict["integration_platforms"] tc.parse_subcases(tc_path) if testcase_filter: if tc.name and tc.name in testcase_filter: self.testcases[tc.name] = tc else: self.testcases[tc.name] = tc except Exception as e: logger.error("%s: can't load (skipping): %s" % (tc_path, e)) self.load_errors += 1 return len(self.testcases) def get_platform(self, name): selected_platform = None for platform in self.platforms: if platform.name == name: selected_platform = platform break return selected_platform def load_from_file(self, file, filter_status=[], filter_platform=[]): try: with open(file, "r") as fp: cr = csv.DictReader(fp) instance_list = [] for row in cr: if row["status"] in filter_status: continue test = row["test"] platform = self.get_platform(row["platform"]) if filter_platform and platform.name not in filter_platform: continue instance = TestInstance(self.testcases[test], platform, self.outdir) if self.device_testing: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) instance.create_overlay(platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) instance_list.append(instance) self.add_instances(instance_list) except KeyError as e: logger.error("Key error while parsing tests file.({})".format(str(e))) sys.exit(2) except FileNotFoundError as e: logger.error("Couldn't find input file with list of tests. ({})".format(e)) sys.exit(2) def apply_filters(self, **kwargs): toolchain = self.get_toolchain() discards = {} platform_filter = kwargs.get('platform') exclude_platform = kwargs.get('exclude_platform', []) testcase_filter = kwargs.get('run_individual_tests', []) arch_filter = kwargs.get('arch') tag_filter = kwargs.get('tag') exclude_tag = kwargs.get('exclude_tag') all_filter = kwargs.get('all') runnable = kwargs.get('runnable') force_toolchain = kwargs.get('force_toolchain') force_platform = kwargs.get('force_platform') emu_filter = kwargs.get('emulation_only') logger.debug("platform filter: " + str(platform_filter)) logger.debug(" arch_filter: " + str(arch_filter)) logger.debug(" tag_filter: " + str(tag_filter)) logger.debug(" exclude_tag: " + str(exclude_tag)) default_platforms = False emulation_platforms = False if all_filter: logger.info("Selecting all possible platforms per test case") # When --all used, any --platform arguments ignored platform_filter = [] elif not platform_filter and not emu_filter: logger.info("Selecting default platforms per test case") default_platforms = True elif emu_filter: logger.info("Selecting emulation platforms per test case") emulation_platforms = True if platform_filter: platforms = list(filter(lambda p: p.name in platform_filter, self.platforms)) elif emu_filter: platforms = list(filter(lambda p: p.simulation != 'na', self.platforms)) elif arch_filter: platforms = list(filter(lambda p: p.arch in arch_filter, self.platforms)) elif default_platforms: platforms = list(filter(lambda p: p.default, self.platforms)) else: platforms = self.platforms logger.info("Building initial testcase list...") for tc_name, tc in self.testcases.items(): if tc.build_on_all and not platform_filter: platform_scope = self.platforms else: platform_scope = platforms # list of instances per testcase, aka configurations. instance_list = [] for plat in platform_scope: instance = TestInstance(tc, plat, self.outdir) if runnable: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) for t in tc.cases: instance.results[t] = None if runnable and self.duts: for h in self.duts: if h.platform == plat.name: if tc.harness_config.get('fixture') in h.fixtures: instance.run = True if not force_platform and plat.name in exclude_platform: discards[instance] = discards.get(instance, "Platform is excluded on command line.") if (plat.arch == "unit") != (tc.type == "unit"): # Discard silently continue if runnable and not instance.run: discards[instance] = discards.get(instance, "Not runnable on device") if self.integration and tc.integration_platforms and plat.name not in tc.integration_platforms: discards[instance] = discards.get(instance, "Not part of integration platforms") if tc.skip: discards[instance] = discards.get(instance, "Skip filter") if tag_filter and not tc.tags.intersection(tag_filter): discards[instance] = discards.get(instance, "Command line testcase tag filter") if exclude_tag and tc.tags.intersection(exclude_tag): discards[instance] = discards.get(instance, "Command line testcase exclude filter") if testcase_filter and tc_name not in testcase_filter: discards[instance] = discards.get(instance, "Testcase name filter") if arch_filter and plat.arch not in arch_filter: discards[instance] = discards.get(instance, "Command line testcase arch filter") if not force_platform: if tc.arch_allow and plat.arch not in tc.arch_allow: discards[instance] = discards.get(instance, "Not in test case arch allow list") if tc.arch_exclude and plat.arch in tc.arch_exclude: discards[instance] = discards.get(instance, "In test case arch exclude") if tc.platform_exclude and plat.name in tc.platform_exclude: discards[instance] = discards.get(instance, "In test case platform exclude") if tc.toolchain_exclude and toolchain in tc.toolchain_exclude: discards[instance] = discards.get(instance, "In test case toolchain exclude") if platform_filter and plat.name not in platform_filter: discards[instance] = discards.get(instance, "Command line platform filter") if tc.platform_allow and plat.name not in tc.platform_allow: discards[instance] = discards.get(instance, "Not in testcase platform allow list") if tc.toolchain_allow and toolchain not in tc.toolchain_allow: discards[instance] = discards.get(instance, "Not in testcase toolchain allow list") if not plat.env_satisfied: discards[instance] = discards.get(instance, "Environment ({}) not satisfied".format(", ".join(plat.env))) if not force_toolchain \ and toolchain and (toolchain not in plat.supported_toolchains) \ and tc.type != 'unit': discards[instance] = discards.get(instance, "Not supported by the toolchain") if plat.ram < tc.min_ram: discards[instance] = discards.get(instance, "Not enough RAM") if tc.depends_on: dep_intersection = tc.depends_on.intersection(set(plat.supported)) if dep_intersection != set(tc.depends_on): discards[instance] = discards.get(instance, "No hardware support") if plat.flash < tc.min_flash: discards[instance] = discards.get(instance, "Not enough FLASH") if set(plat.ignore_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (exclude_tags)") if plat.only_tags and not set(plat.only_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (only_tags)") # if nothing stopped us until now, it means this configuration # needs to be added. instance_list.append(instance) # no configurations, so jump to next testcase if not instance_list: continue # if twister was launched with no platform options at all, we # take all default platforms if default_platforms and not tc.build_on_all: if tc.platform_allow: a = set(self.default_platforms) b = set(tc.platform_allow) c = a.intersection(b) if c: aa = list(filter(lambda tc: tc.platform.name in c, instance_list)) self.add_instances(aa) else: self.add_instances(instance_list[:1]) else: instances = list(filter(lambda tc: tc.platform.default, instance_list)) if self.integration: instances += list(filter(lambda item: item.platform.name in tc.integration_platforms, \ instance_list)) self.add_instances(instances) elif emulation_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.simulation != 'na', instance_list)): discards[instance] = discards.get(instance, "Not an emulated platform") else: self.add_instances(instance_list) for _, case in self.instances.items(): case.create_overlay(case.platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) self.discards = discards self.selected_platforms = set(p.platform.name for p in self.instances.values()) for instance in self.discards: instance.reason = self.discards[instance] instance.status = "skipped" instance.fill_results_by_status() self.filtered_platforms = set(p.platform.name for p in self.instances.values() if p.status != "skipped" ) return discards def add_instances(self, instance_list): for instance in instance_list: self.instances[instance.name] = instance @staticmethod def calc_one_elf_size(instance): if instance.status not in ["error", "failed", "skipped"]: if instance.platform.type != "native": size_calc = instance.calculate_sizes() instance.metrics["ram_size"] = size_calc.get_ram_size() instance.metrics["rom_size"] = size_calc.get_rom_size() instance.metrics["unrecognized"] = size_calc.unrecognized_sections() else: instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["unrecognized"] = [] instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 def add_tasks_to_queue(self, pipeline, build_only=False, test_only=False): for instance in self.instances.values(): if build_only: instance.run = False if test_only and instance.run: pipeline.put({"op": "run", "test": instance}) else: if instance.status not in ['passed', 'skipped', 'error']: logger.debug(f"adding {instance.name}") instance.status = None pipeline.put({"op": "cmake", "test": instance}) def pipeline_mgr(self, pipeline, done_queue, lock, results): while True: try: task = pipeline.get_nowait() except queue.Empty: break else: test = task['test'] pb = ProjectBuilder(self, test, lsan=self.enable_lsan, asan=self.enable_asan, ubsan=self.enable_ubsan, coverage=self.enable_coverage, extra_args=self.extra_args, device_testing=self.device_testing, cmake_only=self.cmake_only, cleanup=self.cleanup, valgrind=self.enable_valgrind, inline_logs=self.inline_logs, generator=self.generator, generator_cmd=self.generator_cmd, verbose=self.verbose, warnings_as_errors=self.warnings_as_errors, overflow_as_errors=self.overflow_as_errors ) pb.process(pipeline, done_queue, task, lock, results) return True def execute(self, pipeline, done, results): lock = Lock() logger.info("Adding tasks to the queue...") self.add_tasks_to_queue(pipeline, self.build_only, self.test_only) logger.info("Added initial list of jobs to queue") processes = [] for job in range(self.jobs): logger.debug(f"Launch process {job}") p = Process(target=self.pipeline_mgr, args=(pipeline, done, lock, results, )) processes.append(p) p.start() try: for p in processes: p.join() except KeyboardInterrupt: logger.info("Execution interrupted") for p in processes: p.terminate() # FIXME: This needs to move out. if self.enable_size_report and not self.cmake_only: # Parallelize size calculation executor = concurrent.futures.ThreadPoolExecutor(self.jobs) futures = [executor.submit(self.calc_one_elf_size, instance) for instance in self.instances.values()] concurrent.futures.wait(futures) else: for instance in self.instances.values(): instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 instance.metrics["unrecognized"] = [] return results def discard_report(self, filename): try: if not self.discards: raise TwisterRuntimeError("apply_filters() hasn't been run!") except Exception as e: logger.error(str(e)) sys.exit(2) with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "reason"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance, reason in sorted(self.discards.items()): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "reason": reason} cw.writerow(rowdict) def target_report(self, outdir, suffix, append=False): platforms = {inst.platform.name for _, inst in self.instances.items()} for platform in platforms: if suffix: filename = os.path.join(outdir,"{}_{}.xml".format(platform, suffix)) else: filename = os.path.join(outdir,"{}.xml".format(platform)) self.xunit_report(filename, platform, full_report=True, append=append, version=self.version) @staticmethod def process_log(log_file): filtered_string = "" if os.path.exists(log_file): with open(log_file, "rb") as f: log = f.read().decode("utf-8") filtered_string = ''.join(filter(lambda x: x in string.printable, log)) return filtered_string def xunit_report(self, filename, platform=None, full_report=False, append=False, version="NA"): total = 0 fails = passes = errors = skips = 0 if platform: selected = [platform] logger.info(f"Writing target report for {platform}...") else: logger.info(f"Writing xunit report {filename}...") selected = self.selected_platforms if os.path.exists(filename) and append: tree = ET.parse(filename) eleTestsuites = tree.getroot() else: eleTestsuites = ET.Element('testsuites') for p in selected: inst = self.get_platform_instances(p) fails = 0 passes = 0 errors = 0 skips = 0 duration = 0 for _, instance in inst.items(): handler_time = instance.metrics.get('handler_time', 0) duration += handler_time if full_report and instance.run: for k in instance.results.keys(): if instance.results[k] == 'PASS': passes += 1 elif instance.results[k] == 'BLOCK': errors += 1 elif instance.results[k] == 'SKIP' or instance.status in ['skipped']: skips += 1 else: fails += 1 else: if instance.status in ["error", "failed", "timeout"]: if instance.reason in ['build_error', 'handler_crash']: errors += 1 else: fails += 1 elif instance.status == 'skipped': skips += 1 elif instance.status == 'passed': passes += 1 else: if instance.status: logger.error(f"{instance.name}: Unknown status {instance.status}") else: logger.error(f"{instance.name}: No status") total = (errors + passes + fails + skips) # do not produce a report if no tests were actually run (only built) if total == 0: continue run = p eleTestsuite = None # When we re-run the tests, we re-use the results and update only with # the newly run tests. if os.path.exists(filename) and append: ts = eleTestsuites.findall(f'testsuite/[@name="{p}"]') if ts: eleTestsuite = ts[0] eleTestsuite.attrib['failures'] = "%d" % fails eleTestsuite.attrib['errors'] = "%d" % errors eleTestsuite.attrib['skipped'] = "%d" % skips else: logger.info(f"Did not find any existing results for {p}") eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) else: eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) for _, instance in inst.items(): if full_report: tname = os.path.basename(instance.testcase.name) else: tname = instance.testcase.id handler_time = instance.metrics.get('handler_time', 0) if full_report: for k in instance.results.keys(): # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@name="{k}"]'): eleTestsuite.remove(tc) classname = ".".join(tname.split(".")[:2]) eleTestcase = ET.SubElement( eleTestsuite, 'testcase', classname=classname, name="%s" % (k), time="%f" % handler_time) if instance.results[k] in ['FAIL', 'BLOCK'] or \ (not instance.run and instance.status in ["error", "failed", "timeout"]): if instance.results[k] == 'FAIL': el = ET.SubElement( eleTestcase, 'failure', type="failure", message="failed") else: el = ET.SubElement( eleTestcase, 'error', type="failure", message="failed") log_root = os.path.join(self.outdir, instance.platform.name, instance.testcase.name) log_file = os.path.join(log_root, "handler.log") el.text = self.process_log(log_file) elif instance.results[k] == 'PASS' \ or (not instance.run and instance.status in ["passed"]): pass elif instance.results[k] == 'SKIP' or (instance.status in ["skipped"]): el = ET.SubElement(eleTestcase, 'skipped', type="skipped", message=instance.reason) else: el = ET.SubElement( eleTestcase, 'error', type="error", message=f"{instance.reason}") else: if platform: classname = ".".join(instance.testcase.name.split(".")[:2]) else: classname = p + ":" + ".".join(instance.testcase.name.split(".")[:2]) # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@classname="{classname}"][@name="{instance.testcase.name}"]'): eleTestsuite.remove(tc) eleTestcase = ET.SubElement(eleTestsuite, 'testcase', classname=classname, name="%s" % (instance.testcase.name), time="%f" % handler_time) if instance.status in ["error", "failed", "timeout"]: failure = ET.SubElement( eleTestcase, 'failure', type="failure", message=instance.reason) log_root = ("%s/%s/%s" % (self.outdir, instance.platform.name, instance.testcase.name)) bl = os.path.join(log_root, "build.log") hl = os.path.join(log_root, "handler.log") log_file = bl if instance.reason != 'Build error': if os.path.exists(hl): log_file = hl else: log_file = bl failure.text = self.process_log(log_file) elif instance.status == "skipped": ET.SubElement(eleTestcase, 'skipped', type="skipped", message="Skipped") result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) return fails, passes, errors, skips def csv_report(self, filename): with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "status", "extra_args", "handler", "handler_time", "ram_size", "rom_size"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance in self.instances.values(): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "extra_args": " ".join(instance.testcase.extra_args), "handler": instance.platform.simulation} rowdict["status"] = instance.status if instance.status not in ["error", "failed", "timeout"]: if instance.handler: rowdict["handler_time"] = instance.metrics.get("handler_time", 0) ram_size = instance.metrics.get("ram_size", 0) rom_size = instance.metrics.get("rom_size", 0) rowdict["ram_size"] = ram_size rowdict["rom_size"] = rom_size cw.writerow(rowdict) def json_report(self, filename, append=False, version="NA"): logger.info(f"Writing JSON report {filename}") report = {} selected = self.selected_platforms report["environment"] = {"os": os.name, "zephyr_version": version, "toolchain": self.get_toolchain() } json_data = {} if os.path.exists(filename) and append: with open(filename, 'r') as json_file: json_data = json.load(json_file) suites = json_data.get("testsuites", []) if suites: suite = suites[0] testcases = suite.get("testcases", []) else: suite = {} testcases = [] for p in selected: inst = self.get_platform_instances(p) for _, instance in inst.items(): testcase = {} handler_log = os.path.join(instance.build_dir, "handler.log") build_log = os.path.join(instance.build_dir, "build.log") device_log = os.path.join(instance.build_dir, "device.log") handler_time = instance.metrics.get('handler_time', 0) ram_size = instance.metrics.get ("ram_size", 0) rom_size = instance.metrics.get("rom_size",0) for k in instance.results.keys(): testcases = list(filter(lambda d: not (d.get('testcase') == k and d.get('platform') == p), testcases )) testcase = {"testcase": k, "arch": instance.platform.arch, "platform": p, } if instance.results[k] in ["PASS"]: testcase["status"] = "passed" if instance.handler: testcase["execution_time"] = handler_time if ram_size: testcase["ram_size"] = ram_size if rom_size: testcase["rom_size"] = rom_size elif instance.results[k] in ['FAIL', 'BLOCK'] or instance.status in ["error", "failed", "timeout"]: testcase["status"] = "failed" testcase["reason"] = instance.reason testcase["execution_time"] = handler_time if os.path.exists(handler_log): testcase["test_output"] = self.process_log(handler_log) elif os.path.exists(device_log): testcase["device_log"] = self.process_log(device_log) else: testcase["build_log"] = self.process_log(build_log) else: testcase["status"] = "skipped" testcase["reason"] = instance.reason testcases.append(testcase) suites = [ {"testcases": testcases} ] report["testsuites"] = suites with open(filename, "wt") as json_file: json.dump(report, json_file, indent=4, separators=(',',':')) def get_testcase(self, identifier): results = [] for _, tc in self.testcases.items(): for case in tc.cases: if case == identifier: results.append(tc) return results class CoverageTool: """ Base class for every supported coverage tool """ def __init__(self): self.gcov_tool = None self.base_dir = None @staticmethod def factory(tool): if tool == 'lcov': t = Lcov() elif tool == 'gcovr': t = Gcovr() else: logger.error("Unsupported coverage tool specified: {}".format(tool)) return None logger.debug(f"Select {tool} as the coverage tool...") return t @staticmethod def retrieve_gcov_data(intput_file): logger.debug("Working on %s" % intput_file) extracted_coverage_info = {} capture_data = False capture_complete = False with open(intput_file, 'r') as fp: for line in fp.readlines(): if re.search("GCOV_COVERAGE_DUMP_START", line): capture_data = True continue if re.search("GCOV_COVERAGE_DUMP_END", line): capture_complete = True break # Loop until the coverage data is found. if not capture_data: continue if line.startswith("*"): sp = line.split("<") if len(sp) > 1: # Remove the leading delimiter "*" file_name = sp[0][1:] # Remove the trailing new line char hex_dump = sp[1][:-1] else: continue else: continue extracted_coverage_info.update({file_name: hex_dump}) if not capture_data: capture_complete = True return {'complete': capture_complete, 'data': extracted_coverage_info} @staticmethod def create_gcda_files(extracted_coverage_info): logger.debug("Generating gcda files") for filename, hexdump_val in extracted_coverage_info.items(): # if kobject_hash is given for coverage gcovr fails # hence skipping it problem only in gcovr v4.1 if "kobject_hash" in filename: filename = (filename[:-4]) + "gcno" try: os.remove(filename) except Exception: pass continue with open(filename, 'wb') as fp: fp.write(bytes.fromhex(hexdump_val)) def generate(self, outdir): for filename in glob.glob("%s/**/handler.log" % outdir, recursive=True): gcov_data = self.__class__.retrieve_gcov_data(filename) capture_complete = gcov_data['complete'] extracted_coverage_info = gcov_data['data'] if capture_complete: self.__class__.create_gcda_files(extracted_coverage_info) logger.debug("Gcov data captured: {}".format(filename)) else: logger.error("Gcov data capture incomplete: {}".format(filename)) with open(os.path.join(outdir, "coverage.log"), "a") as coveragelog: ret = self._generate(outdir, coveragelog) if ret == 0: logger.info("HTML report generated: {}".format( os.path.join(outdir, "coverage", "index.html"))) class Lcov(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('*' + pattern + '*') def add_ignore_directory(self, pattern): self.ignores.append('*/' + pattern + '/*') def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.info") ztestfile = os.path.join(outdir, "ztest.info") cmd = ["lcov", "--gcov-tool", self.gcov_tool, "--capture", "--directory", outdir, "--rc", "lcov_branch_coverage=1", "--output-file", coveragefile] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--extract", coveragefile, os.path.join(self.base_dir, "tests", "ztest", "*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--remove", ztestfile, os.path.join(self.base_dir, "tests/ztest/test/*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) files = [coveragefile, ztestfile] else: files = [coveragefile] for i in self.ignores: subprocess.call( ["lcov", "--gcov-tool", self.gcov_tool, "--remove", coveragefile, i, "--output-file", coveragefile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) # The --ignore-errors source option is added to avoid it exiting due to # samples/application_development/external_lib/ return subprocess.call(["genhtml", "--legend", "--branch-coverage", "--ignore-errors", "source", "-output-directory", os.path.join(outdir, "coverage")] + files, stdout=coveragelog) class Gcovr(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('.*' + pattern + '.*') def add_ignore_directory(self, pattern): self.ignores.append(".*/" + pattern + '/.*') @staticmethod def _interleave_list(prefix, list): tuple_list = [(prefix, item) for item in list] return [item for sublist in tuple_list for item in sublist] def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.json") ztestfile = os.path.join(outdir, "ztest.json") excludes = Gcovr._interleave_list("-e", self.ignores) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-e", "tests/*"] + excludes + ["--json", "-o", coveragefile, outdir] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) subprocess.call(["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-f", "tests/ztest", "-e", "tests/ztest/test/*", "--json", "-o", ztestfile, outdir], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: files = [coveragefile, ztestfile] else: files = [coveragefile] subdir = os.path.join(outdir, "coverage") os.makedirs(subdir, exist_ok=True) tracefiles = self._interleave_list("--add-tracefile", files) return subprocess.call(["gcovr", "-r", self.base_dir, "--html", "--html-details"] + tracefiles + ["-o", os.path.join(subdir, "index.html")], stdout=coveragelog) class DUT(object): def __init__(self, id=None, serial=None, platform=None, product=None, serial_pty=None, connected=False, pre_script=None, post_script=None, post_flash_script=None, runner=None): self.serial = serial self.platform = platform self.serial_pty = serial_pty self._counter = Value("i", 0) self._available = Value("i", 1) self.connected = connected self.pre_script = pre_script self.id = id self.product = product self.runner = runner self.fixtures = [] self.post_flash_script = post_flash_script self.post_script = post_script self.pre_script = pre_script self.probe_id = None self.notes = None self.match = False @property def available(self): with self._available.get_lock(): return self._available.value @available.setter def available(self, value): with self._available.get_lock(): self._available.value = value @property def counter(self): with self._counter.get_lock(): return self._counter.value @counter.setter def counter(self, value): with self._counter.get_lock(): self._counter.value = value def to_dict(self): d = {} exclude = ['_available', '_counter', 'match'] v = vars(self) for k in v.keys(): if k not in exclude and v[k]: d[k] = v[k] return d def __repr__(self): return f"<{self.platform} ({self.product}) on {self.serial}>" class HardwareMap: schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "hwmap-schema.yaml") manufacturer = [ 'ARM', 'SEGGER', 'MBED', 'STMicroelectronics', 'Atmel Corp.', 'Texas Instruments', 'Silicon Labs', 'NXP Semiconductors', 'Microchip Technology Inc.', 'FTDI', 'Digilent' ] runner_mapping = { 'pyocd': [ 'DAPLink CMSIS-DAP', 'MBED CMSIS-DAP' ], 'jlink': [ 'J-Link', 'J-Link OB' ], 'openocd': [ 'STM32 STLink', '^XDS110.*', 'STLINK-V3' ], 'dediprog': [ 'TTL232R-3V3', 'MCP2200 USB Serial Port Emulator' ] } def __init__(self): self.detected = [] self.duts = [] def add_device(self, serial, platform, pre_script, is_pty): device = DUT(platform=platform, connected=True, pre_script=pre_script) if is_pty: device.serial_pty = serial else: device.serial = serial self.duts.append(device) def load(self, map_file): hwm_schema = scl.yaml_load(self.schema_path) duts = scl.yaml_load_verify(map_file, hwm_schema) for dut in duts: pre_script = dut.get('pre_script') post_script = dut.get('post_script') post_flash_script = dut.get('post_flash_script') platform = dut.get('platform') id = dut.get('id') runner = dut.get('runner') serial = dut.get('serial') product = dut.get('product') fixtures = dut.get('fixtures', []) new_dut = DUT(platform=platform, product=product, runner=runner, id=id, serial=serial, connected=serial is not None, pre_script=pre_script, post_script=post_script, post_flash_script=post_flash_script) new_dut.fixtures = fixtures new_dut.counter = 0 self.duts.append(new_dut) def scan(self, persistent=False): from serial.tools import list_ports if persistent and platform.system() == 'Linux': # On Linux, /dev/serial/by-id provides symlinks to # '/dev/ttyACMx' nodes using names which are unique as # long as manufacturers fill out USB metadata nicely. # # This creates a map from '/dev/ttyACMx' device nodes # to '/dev/serial/by-id/usb-...' symlinks. The symlinks # go into the hardware map because they stay the same # even when the user unplugs / replugs the device. # # Some inexpensive USB/serial adapters don't result # in unique names here, though, so use of this feature # requires explicitly setting persistent=True. by_id = Path('/dev/serial/by-id') def readlink(link): return str((by_id / link).resolve()) persistent_map = {readlink(link): str(link) for link in by_id.iterdir()} else: persistent_map = {} serial_devices = list_ports.comports() logger.info("Scanning connected hardware...") for d in serial_devices: if d.manufacturer in self.manufacturer: # TI XDS110 can have multiple serial devices for a single board # assume endpoint 0 is the serial, skip all others if d.manufacturer == 'Texas Instruments' and not d.location.endswith('0'): continue s_dev = DUT(platform="unknown", id=d.serial_number, serial=persistent_map.get(d.device, d.device), product=d.product, runner='unknown') for runner, _ in self.runner_mapping.items(): products = self.runner_mapping.get(runner) if d.product in products: s_dev.runner = runner continue # Try regex matching for p in products: if re.match(p, d.product): s_dev.runner = runner s_dev.connected = True self.detected.append(s_dev) else: logger.warning("Unsupported device (%s): %s" % (d.manufacturer, d)) def save(self, hwm_file): # use existing map self.detected.sort(key=lambda x: x.serial or '') if os.path.exists(hwm_file): with open(hwm_file, 'r') as yaml_file: hwm = yaml.load(yaml_file, Loader=SafeLoader) if hwm: hwm.sort(key=lambda x: x['serial'] or '') # disconnect everything for h in hwm: h['connected'] = False h['serial'] = None for _detected in self.detected: for h in hwm: if _detected.id == h['id'] and _detected.product == h['product'] and not _detected.match: h['connected'] = True h['serial'] = _detected.serial _detected.match = True new_duts = list(filter(lambda d: not d.match, self.detected)) new = [] for d in new_duts: new.append(d.to_dict()) if hwm: hwm = hwm + new else: hwm = new with open(hwm_file, 'w') as yaml_file: yaml.dump(hwm, yaml_file, Dumper=Dumper, default_flow_style=False) self.load(hwm_file) logger.info("Registered devices:") self.dump() else: # create new file dl = [] for _connected in self.detected: platform = _connected.platform id = _connected.id runner = _connected.runner serial = _connected.serial product = _connected.product d = { 'platform': platform, 'id': id, 'runner': runner, 'serial': serial, 'product': product } dl.append(d) with open(hwm_file, 'w') as yaml_file: yaml.dump(dl, yaml_file, Dumper=Dumper, default_flow_style=False) logger.info("Detected devices:") self.dump(detected=True) def dump(self, filtered=[], header=[], connected_only=False, detected=False): print("") table = [] if detected: to_show = self.detected else: to_show = self.duts if not header: header = ["Platform", "ID", "Serial device"] for p in to_show: platform = p.platform connected = p.connected if filtered and platform not in filtered: continue if not connected_only or connected: table.append([platform, p.id, p.serial]) print(tabulate(table, headers=header, tablefmt="github")) def size_report(sc): logger.info(sc.filename) logger.info("SECTION NAME VMA LMA SIZE HEX SZ TYPE") for i in range(len(sc.sections)): v = sc.sections[i] logger.info("%-17s 0x%08x 0x%08x %8d 0x%05x %-7s" % (v["name"], v["virt_addr"], v["load_addr"], v["size"], v["size"], v["type"])) logger.info("Totals: %d bytes (ROM), %d bytes (RAM)" % (sc.rom_size, sc.ram_size)) logger.info("") def export_tests(filename, tests): with open(filename, "wt") as csvfile: fieldnames = ['section', 'subsection', 'title', 'reference'] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) for test in tests: data = test.split(".") if len(data) > 1: subsec = " ".join(data[1].split("_")).title() rowdict = { "section": data[0].capitalize(), "subsection": subsec, "title": test, "reference": test } cw.writerow(rowdict) else: logger.info("{} can't be exported".format(test))
""" Base model used for products. Stores hierarchical categories as well as individual product level information which includes options. """ import datetime import random import sha from sets import Set from decimal import Decimal from django.conf import settings from django.core import validators, urlresolvers from django.db import models from django.utils.translation import get_language, ugettext_lazy as _ from satchmo.configuration import config_value from satchmo.shop.utils import url_join from satchmo.tax.models import TaxClass from satchmo.thumbnail.field import ImageWithThumbnailField import logging try: from django.utils.safestring import mark_safe except ImportError: mark_safe = lambda s:s log = logging.getLogger('product.models') def normalize_dir(dir_name): if not dir_name.startswith('./'): dir_name = url_join('.', dir_name) if dir_name.endswith("/"): dir_name = dir_name[:-1] return dir_name def upload_dir(): return normalize_dir(config_value('PRODUCT', 'IMAGE_DIR')) def protected_dir(): return normalize_dir(config_value('PRODUCT', 'PROTECTED_DIR')) class Category(models.Model): """ Basic hierarchical category model for storing products """ name = models.CharField(_("Name"), core=True, max_length=200) slug = models.SlugField(prepopulate_from=('name',), help_text=_("Used for URLs")) parent = models.ForeignKey('self', blank=True, null=True, related_name='child') meta = models.TextField(_("Meta Description"), blank=True, null=True, help_text=_("Meta description for this category")) description = models.TextField(_("Description"), blank=True, help_text="Optional") ordering = models.IntegerField(_("Ordering"), default=0, help_text=_("Override alphabetical order in category display")) def _get_mainImage(self): img = False if self.images.count() > 0: img = self.images.order_by('sort')[0] else: if self.parent_id: img = self.parent.main_image if not img: #This should be a "Image Not Found" placeholder image try: img = CategoryImage.objects.filter(cagegory__isnull=True).order_by('sort')[0] except IndexError: import sys print >>sys.stderr, 'Warning: default category image not found - try syncdb' return img main_image = property(_get_mainImage) def translated_description(self, language_code=None): return lookup_translation(self, 'description', language_code) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) def _recurse_for_parents(self, cat_obj): p_list = [] if cat_obj.parent_id: p = cat_obj.parent p_list.append(p) if p != self: more = self._recurse_for_parents(p) p_list.extend(more) if cat_obj == self and p_list: p_list.reverse() return p_list def get_absolute_url(self): parents = self._recurse_for_parents(self) slug_list = [cat.slug for cat in parents] slug_list.append(self.slug) return u'%s/category/%s/' % (settings.SHOP_BASE, u'/'.join(slug_list)) def get_separator(self): return ' :: ' def _parents_repr(self): name_list = [cat.name for cat in self._recurse_for_parents(self)] return self.get_separator().join(name_list) _parents_repr.short_description = "Category parents" def get_url_name(self): # Get all the absolute URLs and names for use in the site navigation. name_list = [] url_list = [] for cat in self._recurse_for_parents(self): name_list.append(cat.translated_name()) url_list.append(cat.get_absolute_url()) name_list.append(self.translated_name()) url_list.append(self.get_absolute_url()) return zip(name_list, url_list) def __unicode__(self): name_list = [cat.name for cat in self._recurse_for_parents(self)] name_list.append(self.name) return self.get_separator().join(name_list) def save(self): parents = self._recurse_for_parents(self) if self in parents: raise validators.ValidationError(_("You must not save a category in itself!")) super(Category, self).save() def _flatten(self, L): """ Taken from a python newsgroup post """ if type(L) != type([]): return [L] if L == []: return L return self._flatten(L[0]) + self._flatten(L[1:]) def _recurse_for_children(self, node): children = [] children.append(node) for child in node.child.all(): if child != self: children_list = self._recurse_for_children(child) children.append(children_list) return children def get_all_children(self): """ Gets a list of all of the children categories. """ children_list = self._recurse_for_children(self) flat_list = self._flatten(children_list[1:]) return flat_list class Admin: list_display = ('name', '_parents_repr') ordering = ['parent', 'ordering', 'name'] class Meta: ordering = ['parent', 'ordering', 'name'] verbose_name = _("Category") verbose_name_plural = _("Categories") class CategoryTranslation(models.Model): """A specific language translation for a `Category`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ category = models.ForeignKey(Category, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Translated Category Name"), max_length=255, core=True) description = models.TextField(_("Description of category"), default='', blank=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Category Translation') verbose_name_plural = _('Category Translations') ordering = ('category', 'name','languagecode') unique_together = ('category', 'languagecode', 'version') def __unicode__(self): return u"CategoryTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.category, self.name) class CategoryImage(models.Model): """ A picture of an item. Can have many pictures associated with an item. Thumbnails are automatically created. """ category = models.ForeignKey(Category, null=True, blank=True, related_name="images", edit_inline=models.TABULAR, num_in_admin=3) picture = ImageWithThumbnailField(verbose_name=_('Picture'), upload_to=upload_dir(), name_field="_filename") #Media root is automatically prepended caption = models.CharField(_("Optional caption"), max_length=100, null=True, blank=True) sort = models.IntegerField(_("Sort Order"), core=True) def translated_caption(self, language_code=None): return lookup_translation(self, 'caption', language_code) def _get_filename(self): if self.category: return '%s-%s' % (self.category.slug, self.id) else: return 'default' _filename = property(_get_filename) def __unicode__(self): if self.category: return u"Image of Category %s" % self.category.slug elif self.caption: return u"Image with caption \"%s\"" % self.caption else: return u"%s" % self.picture class Meta: ordering = ['sort'] unique_together = (('category', 'sort'),) verbose_name = _("Category Image") verbose_name_plural = _("Category Images") class Admin: pass class CategoryImageTranslation(models.Model): """A specific language translation for a `CategoryImage`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ categoryimage = models.ForeignKey(CategoryImage, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) caption = models.CharField(_("Translated Caption"), max_length=255, core=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Category Image Translation') verbose_name_plural = _('Category Image Translations') ordering = ('categoryimage', 'caption','languagecode') unique_together = ('categoryimage', 'languagecode', 'version') def __unicode__(self): return u"CategoryImageTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.categoryimage, self.name) class OptionGroup(models.Model): """ A set of options that can be applied to an item. Examples - Size, Color, Shape, etc """ name = models.CharField(_("Name of Option Group"), max_length=50, core=True, help_text=_("This will be the text displayed on the product page.")) description = models.CharField(_("Detailed Description"), max_length=100, blank=True, help_text=_("Further description of this group (i.e. shirt size vs shoe size).")) sort_order = models.IntegerField(_("Sort Order"), help_text=_("The display order for this group.")) def translated_description(self, language_code=None): return lookup_translation(self, 'description', language_code) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) def __unicode__(self): if self.description: return u"%s - %s" % (self.name, self.description) else: return self.name class Admin: pass class Meta: ordering = ['sort_order', 'name'] verbose_name = _("Option Group") verbose_name_plural = _("Option Groups") class OptionGroupTranslation(models.Model): """A specific language translation for an `OptionGroup`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ optiongroup = models.ForeignKey(OptionGroup, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Translated OptionGroup Name"), max_length=255, core=True) description = models.TextField(_("Description of OptionGroup"), default='', blank=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Option Group Translation') verbose_name_plural = _('Option Groups Translations') ordering = ('optiongroup', 'name','languagecode') unique_together = ('optiongroup', 'languagecode', 'version') def __unicode__(self): return u"OptionGroupTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.optiongroup, self.name) class OptionManager(models.Manager): def from_unique_id(self, str): (og, opt) = str.split('-') group = OptionGroup.objects.get(id=og) return Option.objects.get(optionGroup=og, value=opt) class Option(models.Model): """ These are the actual items in an OptionGroup. If the OptionGroup is Size, then an Option would be Small. """ objects = OptionManager() optionGroup = models.ForeignKey(OptionGroup, edit_inline=models.TABULAR, num_in_admin=5) name = models.CharField(_("Display value"), max_length=50, core=True) value = models.SlugField(_("Stored value"), max_length=50, prepopulate_from=('name',)) price_change = models.DecimalField(_("Price Change"), null=True, blank=True, max_digits=10, decimal_places=2, help_text=_("This is the price differential for this option.")) displayOrder = models.IntegerField(_("Display Order")) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) class Meta: ordering = ('optionGroup', 'displayOrder', 'name') unique_together = (('optionGroup', 'value'),) verbose_name = _("Option Item") verbose_name_plural = _("Option Items") def _get_unique_id(self): return '%s-%s' % (str(self.optionGroup.id), str(self.value),) # optionGroup.id-value unique_id = property(_get_unique_id) def __repr__(self): return u"<Option: %s>" % self.name def __unicode__(self): return u'%s: %s' % (self.optionGroup.name, self.name) class OptionTranslation(models.Model): """A specific language translation for an `Option`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ option = models.ForeignKey(Option, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Translated Category Name"), max_length=255, core=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Option Translation') verbose_name_plural = _('Option Translations') ordering = ('option', 'name','languagecode') unique_together = ('option', 'languagecode', 'version') def __unicode__(self): return u"OptionTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.option, self.name) class ProductManager(models.Manager): def active(self): return self.filter(active=True) class Product(models.Model): """ Root class for all Products """ name = models.CharField(_("Full Name"), max_length=255, help_text=_("This is what the product will be called in the default site language. To add non-default translations, use the Product Translation section below.")) slug = models.SlugField(_("Slug Name"), unique=True, prepopulate_from=('name',), core=True, blank=False) short_description = models.TextField(_("Short description of product"), help_text=_("This should be a 1 or 2 line description in the default site language for use in product listing screens"), max_length=200, default='', blank=True) description = models.TextField(_("Description of product"), help_text=_("This field can contain HTML and should be a few paragraphs in the default site language explaining the background of the product, and anything that would help the potential customer make their purchase."), default='', blank=True) category = models.ManyToManyField(Category, filter_interface=True, blank=True, verbose_name=_("Category")) items_in_stock = models.IntegerField(_("Number in stock"), default=0) meta = models.TextField(_("Meta Description"), max_length=200, blank=True, null=True, help_text=_("Meta description for this product")) date_added = models.DateField(_("Date added"), null=True, blank=True) active = models.BooleanField(_("Is product active?"), default=True, help_text=_("This will determine whether or not this product will appear on the site")) featured = models.BooleanField(_("Featured Item"), default=False, help_text=_("Featured items will show on the front page")) ordering = models.IntegerField(_("Ordering"), default=0, help_text=_("Override alphabetical order in category display")) weight = models.DecimalField(_("Weight"), max_digits=8, decimal_places=2, null=True, blank=True) length = models.DecimalField(_("Length"), max_digits=6, decimal_places=2, null=True, blank=True) width = models.DecimalField(_("Width"), max_digits=6, decimal_places=2, null=True, blank=True) height = models.DecimalField(_("Height"), max_digits=6, decimal_places=2, null=True, blank=True) related_items = models.ManyToManyField('self', blank=True, null=True, verbose_name=_('Related Items'), related_name='related_products') also_purchased = models.ManyToManyField('self', blank=True, null=True, verbose_name=_('Previously Purchased'), related_name='also_products') taxable = models.BooleanField(_("Taxable"), default=False) taxClass = models.ForeignKey(TaxClass, verbose_name=_('Tax Class'), blank=True, null=True, help_text=_("If it is taxable, what kind of tax?")) objects = ProductManager() def _get_mainImage(self): img = False if self.productimage_set.count() > 0: img = self.productimage_set.order_by('sort')[0] else: # try to get a main image by looking at the parent if this has one try: parent = self.productvariation.parent img = parent.product.main_image except ProductVariation.DoesNotExist: pass if not img: #This should be a "Image Not Found" placeholder image try: img = ProductImage.objects.filter(product__isnull=True).order_by('sort')[0] except IndexError: import sys print >>sys.stderr, 'Warning: default product image not found - try syncdb' return img main_image = property(_get_mainImage) def translated_attributes(self, language_code=None): if not language_code: language_code = get_language() q = self.productattribute_set.filter(languagecode__exact = language_code) if q.count() == 0: q = self.productattribute_set.filter(languagecode__isnull = True) return q def translated_description(self, language_code=None): return lookup_translation(self, 'description', language_code) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) def translated_short_description(self, language_code=None): return lookup_translation(self, 'short_description', language_code) def _get_fullPrice(self): """ returns price as a Decimal """ subtype = self.get_subtype_with_attr('unit_price') price = None if subtype: price = subtype.unit_price else: price = self._get_qty_price(1) if not price: price = Decimal("0.00") return price unit_price = property(_get_fullPrice) def get_qty_price(self, qty): """ If QTY_DISCOUNT prices are specified, then return the appropriate discount price for the specified qty. Otherwise, return the unit_price returns price as a Decimal """ subtype = self.get_subtype_with_attr('get_qty_price') if subtype: price = subtype.get_qty_price(qty) else: price = self._get_qty_price(qty) if not price: price = self._get_fullPrice() return price def _get_qty_price(self, qty): """ returns price as a Decimal """ qty_discounts = self.price_set.exclude(expires__isnull=False, expires__lt=datetime.date.today()).filter(quantity__lte=qty) if qty_discounts.count() > 0: # Get the price with the quantity closest to the one specified without going over return Decimal(qty_discounts.order_by('-quantity')[0].price) else: return None def in_stock(self): subtype = self.get_subtype_with_attr('in_stock') if subtype: return subtype.in_stock if self.items_in_stock > 0: return True else: return False; def __unicode__(self): return self.name def get_absolute_url(self): return urlresolvers.reverse('satchmo_product', kwargs={'product_slug': self.slug}) class Admin: list_display = ('slug', 'name', 'unit_price', 'items_in_stock', 'get_subtypes',) list_filter = ('category',) fields = ( (None, {'fields': ('category', 'name', 'slug', 'description', 'short_description', 'date_added', 'active', 'featured', 'items_in_stock','ordering')}), (_('Meta Data'), {'fields': ('meta',), 'classes': 'collapse'}), (_('Item Dimensions'), {'fields': (('length', 'width','height',),'weight'), 'classes': 'collapse'}), (_('Tax'), {'fields':('taxable', 'taxClass'), 'classes': 'collapse'}), (_('Related Products'), {'fields':('related_items','also_purchased'),'classes':'collapse'}), ) search_fields = ['slug', 'name'] class Meta: ordering = ('ordering', 'name',) verbose_name = _("Product") verbose_name_plural = _("Products") def save(self): if not self.id: self.date_added = datetime.date.today() super(Product, self).save() def get_subtypes(self): types = [] for key in config_value('PRODUCT', 'PRODUCT_TYPES'): app, subtype = key.split("::") try: if getattr(self, subtype.lower()): types += [subtype] except models.ObjectDoesNotExist: pass return tuple(types) get_subtypes.short_description = "Product SubTypes" def get_subtype_with_attr(self, attr): for type in self.get_subtypes(): subtype = getattr(self, type.lower()) if hasattr(subtype, attr): return subtype return None def _has_variants(self): subtype = self.get_subtype_with_attr('has_variants') if subtype: return subtype.has_variants return False has_variants = property(_has_variants) def _get_category(self): """ Return the primary category associated with this product """ subtype = self.get_subtype_with_attr('get_category') if subtype: return subtype.get_category return self.category.all()[0] get_category = property(_get_category) def _get_downloadable(self): """ If this Product has any subtypes associated with it that are downloadable, then consider it downloadable """ for prod_type in self.get_subtypes(): subtype = getattr(self, prod_type.lower()) if hasattr(subtype, 'is_downloadable'): return True return False is_downloadable = property(_get_downloadable) def _get_shippable(self): """ If this Product has any subtypes associated with it that are not shippable, then consider the product not shippable. If it is downloadable, then we don't ship it either. """ if self.is_downloadable: return False subtype = self.get_subtype_with_attr('is_shippable') if subtype and not subtype.is_shippable: return False return True is_shippable = property(_get_shippable) class ProductTranslation(models.Model): """A specific language translation for a `Product`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ product = models.ForeignKey('Product', edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Full Name"), max_length=255, core=True) short_description = models.TextField(_("Short description of product"), help_text=_("This should be a 1 or 2 line description for use in product listing screens"), max_length=200, default='', blank=True) description = models.TextField(_("Description of product"), help_text=_("This field can contain HTML and should be a few paragraphs explaining the background of the product, and anything that would help the potential customer make their purchase."), default='', blank=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Product Translation') verbose_name_plural = _('Product Translations') ordering = ('product', 'name','languagecode') unique_together = ('product', 'languagecode', 'version') def __unicode__(self): return u"ProductTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.product, self.name) def _cross_list(sequences): """ Code taken from the Python cookbook v.2 (19.9 - Looping through the cross-product of multiple iterators) This is used to create all the variations associated with an product """ result =[[]] for seq in sequences: result = [sublist+[item] for sublist in result for item in seq] return result def get_all_options(obj): """ Returns all possible combinations of options for this products OptionGroups as a List of Lists. Ex: For OptionGroups Color and Size with Options (Blue, Green) and (Large, Small) you'll get [['Blue', 'Small'], ['Blue', 'Large'], ['Green', 'Small'], ['Green', 'Large']] Note: the actual values will be instances of Option instead of strings """ sublist = [] masterlist = [] #Create a list of all the options & create all combos of the options for opt in obj.option_group.all(): for value in opt.option_set.all(): sublist.append(value) masterlist.append(sublist) sublist = [] return _cross_list(masterlist) class CustomProduct(models.Model): """ Product which must be custom-made or ordered. """ product = models.OneToOneField(Product) downpayment = models.IntegerField(_("Percent Downpayment"), default=20) deferred_shipping = models.BooleanField(_('Deferred Shipping'), help_text=_('Do not charge shipping at checkout for this item.'), default=False) option_group = models.ManyToManyField(OptionGroup, blank=True,) def _is_shippable(self): return not self.deferred_shipping is_shippable = property(fget=_is_shippable) def _get_fullPrice(self): """ returns price as a Decimal """ return self.get_qty_price(1) unit_price = property(_get_fullPrice) def get_qty_price(self, qty): """ If QTY_DISCOUNT prices are specified, then return the appropriate discount price for the specified qty. Otherwise, return the unit_price returns price as a Decimal """ price = self.product._get_qty_price(qty) if not price: price = self.product._get_fullPrice() return price * self.downpayment / 100 def get_full_price(self, qty=1): """ Return the full price, ignoring the deposit. """ price = self.product._get_qty_price(qty) if not price: price = self.product._get_fullPrice() return price full_price = property(fget=get_full_price) def __unicode__(self): return u"CustomProduct: %s" % self.product.name def get_valid_options(self): """ Returns all of the valid options """ return get_all_options(self) class Admin: pass class CustomTextField(models.Model): """ A text field to be filled in by a customer. """ name = models.CharField(_('Custom field name'), max_length=40, core=True) slug = models.SlugField() products = models.ForeignKey(CustomProduct, verbose_name=_('Custom Fields'), edit_inline=models.TABULAR, num_in_admin=3, related_name='custom_text_fields') sort_order = models.IntegerField(_("Sort Order"), help_text=_("The display order for this group.")) price_change = models.DecimalField(_("Price Change"), max_digits=10, decimal_places=2, blank=True, null=True) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) class Meta: ordering = ('sort_order',) class CustomTextFieldTranslation(models.Model): """A specific language translation for a `CustomTextField`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ customtextfield = models.ForeignKey(CustomTextField, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Translated Custom Text Field Name"), max_length=255, core=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('CustomTextField Translation') verbose_name_plural = _('CustomTextField Translations') ordering = ('customtextfield', 'name','languagecode') unique_together = ('customtextfield', 'languagecode', 'version') def __unicode__(self): return u"CustomTextFieldTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.customtextfield, self.name) class ConfigurableProduct(models.Model): """ Product with selectable options. This is a sort of virtual product that is visible to the customer, but isn't actually stocked on a shelf, the specific "shelf" product is determined by the selected options. """ product = models.OneToOneField(Product) option_group = models.ManyToManyField(OptionGroup, blank=True,) create_subs = models.BooleanField(_("Create Variations"), default=False, help_text =_("Create ProductVariations for all this product's options. To use this, you must first add an option, save, then return to this page and select this option.")) def _cross_list(self, sequences): """ Code taken from the Python cookbook v.2 (19.9 - Looping through the cross-product of multiple iterators) This is used to create all the variations associated with an product """ result =[[]] for seq in sequences: result = [sublist+[item] for sublist in result for item in seq] return result def get_all_options(self): """ Returns all possible combinations of options for this products OptionGroups as a List of Lists. Ex: For OptionGroups Color and Size with Options (Blue, Green) and (Large, Small) you'll get [['Blue', 'Small'], ['Blue', 'Large'], ['Green', 'Small'], ['Green', 'Large']] Note: the actual values will be instances of Option instead of strings """ sublist = [] masterlist = [] #Create a list of all the options & create all combos of the options for opt in self.option_group.all(): for value in opt.option_set.all(): sublist.append(value) masterlist.append(sublist) sublist = [] return _cross_list(masterlist) def get_valid_options(self): """ Returns the same output as get_all_options(), but filters out Options that this ConfigurableProduct doesn't have a ProductVariation for. """ opts = get_all_options(self) newopts = [] for a in opts: if self.get_product_count(a): newopts.append(a) return newopts def create_products(self): """ Get a list of all the optiongroups applied to this object Create all combinations of the options and create variations """ combinedlist = self.get_all_options() #Create new ProductVariation for each combo. for options in combinedlist: # Check for an existing ProductVariation. # Simplify this when Django #4464 is fixed. first_option = True pvs = ProductVariation.objects.filter(parent=self) for option in options: query = pvs.filter(options=option) if first_option: first_option = False else: query = query.filter(product__id__in=products) products = [variation.product.id for variation in query] if not products: # There isn't an existing ProductVariation. variant = Product(items_in_stock=0) optnames = [opt.value for opt in options] slug = u'%s_%s' % (self.product.slug, u'_'.join(optnames)) while Product.objects.filter(slug=slug).count(): slug = u'_'.join((slug, unicode(self.product.id))) variant.slug = slug variant.save() pv = ProductVariation(product=variant, parent=self) pv.save() for option in options: pv.options.add(option) variant.name = u'%s (%s)' % ( self.product.name, u'/'.join(optnames)) variant.save() return True def _ensure_option_set(self, options): """ Takes an iterable of Options (or str(Option)) and outputs a Set of str(Option) suitable for comparing to a productvariation.option_values """ if not isinstance(options, Set): optionSet = Set() for opt in options: optionSet.add(opt.unique_id) return optionSet else: return options def get_product_from_options(self, options): """ Accepts an iterable of either Option object or str(Option) objects Returns the product that matches or None """ options = self._ensure_option_set(options) for member in self.productvariation_set.all(): if member.option_values == options: return member.product return None def get_product_count(self, options): options = self._ensure_option_set(options) count = 0 for variant in self.productvariation_set.filter(product__active='1'): if variant.option_values == options: count+=1 return count def save(self): """ Right now this only works if you save the suboptions, then go back and choose to create the variations. """ super(ConfigurableProduct, self).save() # Doesn't work with admin - the manipulator doesn't add the option_group # until after save() is called. if self.create_subs and self.option_group.count(): self.create_products() self.create_subs = False super(ConfigurableProduct, self).save() def get_absolute_url(self): return self.product.get_absolute_url() class Admin: pass def __unicode__(self): return self.product.slug class DownloadableProduct(models.Model): """ This type of Product is a file to be downloaded """ product = models.OneToOneField(Product) file = models.FileField(upload_to=protected_dir()) num_allowed_downloads = models.IntegerField(help_text=_("Number of times link can be accessed.")) expire_minutes = models.IntegerField(help_text=_("Number of minutes the link should remain active.")) active = models.BooleanField(help_text=_("Is this download currently active?"), default=True) is_shippable = False is_downloadable = True def __unicode__(self): return self.product.slug def create_key(self): salt = sha.new(str(random.random())).hexdigest()[:5] download_key = sha.new(salt+self.product.name).hexdigest() return download_key def order_success(self, order, order_item): from satchmo.contact.models import DownloadLink new_link = DownloadLink(downloadable_product=self, order=order, key=self.create_key(), num_attempts=0) new_link.save() class Admin: pass #class BundledProduct(models.Model): # """ # This type of Product is a group of products that are sold as a set # NOTE: This doesn't do anything yet - it's just an example # """ # product = models.OneToOneField(Product) # members = models.ManyToManyField(Product, related_name='parent_productgroup_set') # # class Admin: # pass class ProductVariation(models.Model): """ This is the real Product that is ordered when a customer orders a ConfigurableProduct with the matching Options selected """ product = models.OneToOneField(Product) options = models.ManyToManyField(Option, filter_interface=True, core=True) parent = models.ForeignKey(ConfigurableProduct, core=True) def _get_fullPrice(self): """ Get price based on parent ConfigurableProduct """ if not self.parent.product.unit_price: return None # allow explicit setting of prices. try: qty_discounts = self.price_set.exclude(expires__isnull=False, expires__lt=datetime.date.today()).filter(quantity__lte=1) if qty_discounts.count() > 0: # Get the price with the quantity closest to the one specified without going over return qty_discounts.order_by('-quantity')[0].price except AttributeError: # otherwise calculate from options price_delta = Decimal("0.00") for option in self.options.all(): if option.price_change: price_delta += option.price_change return self.parent.product.unit_price + price_delta unit_price = property(_get_fullPrice) def _get_optionName(self): "Returns the options in a human readable form" if self.options.count() == 0: return self.parent.verbose_name output = self.parent.verbose_name + " ( " numProcessed = 0 # We want the options to be sorted in a consistent manner optionDict = dict([(sub.optionGroup.sort_order, sub) for sub in self.options.all()]) for optionNum in sorted(optionDict.keys()): numProcessed += 1 if numProcessed == self.options.count(): output += optionDict[optionNum].name else: output += optionDict[optionNum].name + "/" output += " )" return output full_name = property(_get_optionName) def _get_optionValues(self): """ Return a set of all the valid options for this variant. A set makes sure we don't have to worry about ordering. """ output = Set() for option in self.options.all(): output.add(option.unique_id) return(output) option_values = property(_get_optionValues) def _has_variants(self): return True has_variants = property(_has_variants) def _get_category(self): """ Return the primary category associated with this product """ return self.parent.product.category.all()[0] get_category = property(_get_category) def _check_optionParents(self): groupList = [] for option in self.options.all(): if option.optionGroup.id in groupList: return(True) else: groupList.append(option.optionGroup.id) return(False) def isValidOption(self, field_data, all_data): raise validators.ValidationError(_("Two options from the same option group can not be applied to an item.")) def save(self): pvs = ProductVariation.objects.filter(parent=self.parent) pvs = pvs.exclude(product=self.product) for pv in pvs: if pv.option_values == self.option_values: return # Don't allow duplicates #Ensure associated Product has a reasonable display name if not self.product.name: options = [] for option in self.options.order_by("optionGroup"): options += [option.name] self.product.name = u'%s (%s)' % (self.parent.product.name, u'/'.join(options)) self.product.save() super(ProductVariation, self).save() def get_absolute_url(self): return self.product.get_absolute_url() class Admin: pass def __unicode__(self): return self.product.slug class ProductAttribute(models.Model): """ Allows arbitrary name/value pairs (as strings) to be attached to a product. This is a very quick and dirty way to add extra info to a product. If you want more structure then this, create your own subtype to add whatever you want to your Products. """ product = models.ForeignKey(Product, edit_inline=models.TABULAR, num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES, null=True) name = models.SlugField(_("Attribute Name"), max_length=100, core=True) value = models.CharField(_("Value"), max_length=255) class Meta: verbose_name = _("Product Attribute") verbose_name_plural = _("Product Attributes") class Price(models.Model): """ A Price! Separating it out lets us have different prices for the same product for different purposes. For example for quantity discounts. The current price should be the one with the earliest expires date, and the highest quantity that's still below the user specified (IE: ordered) quantity, that matches a given product. """ product = models.ForeignKey(Product, edit_inline=models.TABULAR, num_in_admin=2) price = models.DecimalField(_("Price"), max_digits=10, decimal_places=2, core=True) quantity = models.IntegerField(_("Discount Quantity"), default=1, help_text=_("Use this price only for this quantity or higher")) expires = models.DateField(null=True, blank=True) #TODO: add fields here for locale/currency specific pricing def __unicode__(self): return unicode(self.price) def save(self): prices = Price.objects.filter(product=self.product, quantity=self.quantity) ## Jump through some extra hoops to check expires - if there's a better way to handle this field I can't think of it. Expires needs to be able to be set to None in cases where there is no expiration date. if self.expires: prices = prices.filter(expires=self.expires) else: prices = prices.filter(expires__isnull=True) if self.id: prices = prices.exclude(id=self.id) if prices.count(): return #Duplicate Price super(Price, self).save() class Meta: ordering = ['expires', '-quantity'] verbose_name = _("Price") verbose_name_plural = _("Prices") unique_together = (("product", "quantity", "expires"),) class ProductImage(models.Model): """ A picture of an item. Can have many pictures associated with an item. Thumbnails are automatically created. """ product = models.ForeignKey(Product, null=True, blank=True, edit_inline=models.TABULAR, num_in_admin=3) picture = ImageWithThumbnailField(verbose_name=_('Picture'), upload_to=upload_dir(), name_field="_filename") #Media root is automatically prepended caption = models.CharField(_("Optional caption"), max_length=100, null=True, blank=True) sort = models.IntegerField(_("Sort Order"), core=True) def translated_caption(self, language_code=None): return lookup_translation(self, 'caption', language_code) def _get_filename(self): if self.product: return '%s-%s' % (self.product.slug, self.id) else: return 'default' _filename = property(_get_filename) def __unicode__(self): if self.product: return u"Image of Product %s" % self.product.slug elif self.caption: return u"Image with caption \"%s\"" % self.caption else: return u"%s" % self.picture class Meta: ordering = ['sort'] unique_together = (('product', 'sort'),) verbose_name = _("Product Image") verbose_name_plural = _("Product Images") class Admin: pass class ProductImageTranslation(models.Model): """A specific language translation for a `ProductImage`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ productimage = models.ForeignKey(ProductImage, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) caption = models.CharField(_("Translated Caption"), max_length=255, core=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Product Image Translation') verbose_name_plural = _('Product Image Translations') ordering = ('productimage', 'caption','languagecode') unique_together = ('productimage', 'languagecode', 'version') def __unicode__(self): return u"ProductImageTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.productimage, self.name) UNSET = object() def lookup_translation(obj, attr, language_code=None, version=-1): """Get a translated attribute by language. If specific language isn't found, returns the attribute from the base object. """ if not language_code: language_code = get_language() log.debug("looking up translation [%s] %s", language_code.encode('utf-8'), attr.encode('utf-8')) if not hasattr(obj, '_translationcache'): obj._translationcache = {} short_code = language_code pos = language_code.find('_') if pos>-1: short_code = language_code[:pos] else: pos = language_code.find('-') if pos>-1: short_code = language_code[:pos] trans = None has_key = obj._translationcache.has_key(language_code) if has_key: if obj._translationcache[language_code] == None and short_code != language_code: return lookup_translation(obj, attr, short_code) if not has_key: q = obj.translations.filter( languagecode__iexact = language_code) if q.count() == 0: obj._translationcache[language_code] = None if short_code != language_code: return lookup_translation(obj, attr, language_code=short_code, version=version) else: q = obj.translations.filter( languagecode__istartswith = language_code) if q.count()>0: trans = None if version > -1: trans = q.order_by('-version')[0] else: # try to get the requested version, if it is available, # else fallback to the most recent version fallback = None for t in q.order_by('-version'): if not fallback: fallback = t if t.version == version: trans = t break if not trans: trans = fallback obj._translationcache[language_code] = trans if not trans: trans = obj._translationcache[language_code] if not trans: trans = obj log.debug("No such language version, using obj") val = getattr(trans, attr, UNSET) if trans != obj and (val in (None, UNSET)): val = getattr(obj, attr) log.debug("Translated version: %s", val.encode('utf-8')) return mark_safe(val) Correcting productattributes so that languagecodes are completely optional """ Base model used for products. Stores hierarchical categories as well as individual product level information which includes options. """ import datetime import random import sha from decimal import Decimal from django.conf import settings from django.core import validators, urlresolvers from django.db import models from django.db.models import Q from django.utils.translation import get_language, ugettext_lazy as _ from satchmo.configuration import config_value from satchmo.shop.utils import url_join from satchmo.tax.models import TaxClass from satchmo.thumbnail.field import ImageWithThumbnailField from sets import Set import logging try: from django.utils.safestring import mark_safe except ImportError: mark_safe = lambda s:s log = logging.getLogger('product.models') def normalize_dir(dir_name): if not dir_name.startswith('./'): dir_name = url_join('.', dir_name) if dir_name.endswith("/"): dir_name = dir_name[:-1] return dir_name def upload_dir(): return normalize_dir(config_value('PRODUCT', 'IMAGE_DIR')) def protected_dir(): return normalize_dir(config_value('PRODUCT', 'PROTECTED_DIR')) class Category(models.Model): """ Basic hierarchical category model for storing products """ name = models.CharField(_("Name"), core=True, max_length=200) slug = models.SlugField(prepopulate_from=('name',), help_text=_("Used for URLs")) parent = models.ForeignKey('self', blank=True, null=True, related_name='child') meta = models.TextField(_("Meta Description"), blank=True, null=True, help_text=_("Meta description for this category")) description = models.TextField(_("Description"), blank=True, help_text="Optional") ordering = models.IntegerField(_("Ordering"), default=0, help_text=_("Override alphabetical order in category display")) def _get_mainImage(self): img = False if self.images.count() > 0: img = self.images.order_by('sort')[0] else: if self.parent_id: img = self.parent.main_image if not img: #This should be a "Image Not Found" placeholder image try: img = CategoryImage.objects.filter(cagegory__isnull=True).order_by('sort')[0] except IndexError: import sys print >>sys.stderr, 'Warning: default category image not found - try syncdb' return img main_image = property(_get_mainImage) def translated_description(self, language_code=None): return lookup_translation(self, 'description', language_code) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) def _recurse_for_parents(self, cat_obj): p_list = [] if cat_obj.parent_id: p = cat_obj.parent p_list.append(p) if p != self: more = self._recurse_for_parents(p) p_list.extend(more) if cat_obj == self and p_list: p_list.reverse() return p_list def get_absolute_url(self): parents = self._recurse_for_parents(self) slug_list = [cat.slug for cat in parents] slug_list.append(self.slug) return u'%s/category/%s/' % (settings.SHOP_BASE, u'/'.join(slug_list)) def get_separator(self): return ' :: ' def _parents_repr(self): name_list = [cat.name for cat in self._recurse_for_parents(self)] return self.get_separator().join(name_list) _parents_repr.short_description = "Category parents" def get_url_name(self): # Get all the absolute URLs and names for use in the site navigation. name_list = [] url_list = [] for cat in self._recurse_for_parents(self): name_list.append(cat.translated_name()) url_list.append(cat.get_absolute_url()) name_list.append(self.translated_name()) url_list.append(self.get_absolute_url()) return zip(name_list, url_list) def __unicode__(self): name_list = [cat.name for cat in self._recurse_for_parents(self)] name_list.append(self.name) return self.get_separator().join(name_list) def save(self): parents = self._recurse_for_parents(self) if self in parents: raise validators.ValidationError(_("You must not save a category in itself!")) super(Category, self).save() def _flatten(self, L): """ Taken from a python newsgroup post """ if type(L) != type([]): return [L] if L == []: return L return self._flatten(L[0]) + self._flatten(L[1:]) def _recurse_for_children(self, node): children = [] children.append(node) for child in node.child.all(): if child != self: children_list = self._recurse_for_children(child) children.append(children_list) return children def get_all_children(self): """ Gets a list of all of the children categories. """ children_list = self._recurse_for_children(self) flat_list = self._flatten(children_list[1:]) return flat_list class Admin: list_display = ('name', '_parents_repr') ordering = ['parent', 'ordering', 'name'] class Meta: ordering = ['parent', 'ordering', 'name'] verbose_name = _("Category") verbose_name_plural = _("Categories") class CategoryTranslation(models.Model): """A specific language translation for a `Category`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ category = models.ForeignKey(Category, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Translated Category Name"), max_length=255, core=True) description = models.TextField(_("Description of category"), default='', blank=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Category Translation') verbose_name_plural = _('Category Translations') ordering = ('category', 'name','languagecode') unique_together = ('category', 'languagecode', 'version') def __unicode__(self): return u"CategoryTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.category, self.name) class CategoryImage(models.Model): """ A picture of an item. Can have many pictures associated with an item. Thumbnails are automatically created. """ category = models.ForeignKey(Category, null=True, blank=True, related_name="images", edit_inline=models.TABULAR, num_in_admin=3) picture = ImageWithThumbnailField(verbose_name=_('Picture'), upload_to=upload_dir(), name_field="_filename") #Media root is automatically prepended caption = models.CharField(_("Optional caption"), max_length=100, null=True, blank=True) sort = models.IntegerField(_("Sort Order"), core=True) def translated_caption(self, language_code=None): return lookup_translation(self, 'caption', language_code) def _get_filename(self): if self.category: return '%s-%s' % (self.category.slug, self.id) else: return 'default' _filename = property(_get_filename) def __unicode__(self): if self.category: return u"Image of Category %s" % self.category.slug elif self.caption: return u"Image with caption \"%s\"" % self.caption else: return u"%s" % self.picture class Meta: ordering = ['sort'] unique_together = (('category', 'sort'),) verbose_name = _("Category Image") verbose_name_plural = _("Category Images") class Admin: pass class CategoryImageTranslation(models.Model): """A specific language translation for a `CategoryImage`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ categoryimage = models.ForeignKey(CategoryImage, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) caption = models.CharField(_("Translated Caption"), max_length=255, core=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Category Image Translation') verbose_name_plural = _('Category Image Translations') ordering = ('categoryimage', 'caption','languagecode') unique_together = ('categoryimage', 'languagecode', 'version') def __unicode__(self): return u"CategoryImageTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.categoryimage, self.name) class OptionGroup(models.Model): """ A set of options that can be applied to an item. Examples - Size, Color, Shape, etc """ name = models.CharField(_("Name of Option Group"), max_length=50, core=True, help_text=_("This will be the text displayed on the product page.")) description = models.CharField(_("Detailed Description"), max_length=100, blank=True, help_text=_("Further description of this group (i.e. shirt size vs shoe size).")) sort_order = models.IntegerField(_("Sort Order"), help_text=_("The display order for this group.")) def translated_description(self, language_code=None): return lookup_translation(self, 'description', language_code) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) def __unicode__(self): if self.description: return u"%s - %s" % (self.name, self.description) else: return self.name class Admin: pass class Meta: ordering = ['sort_order', 'name'] verbose_name = _("Option Group") verbose_name_plural = _("Option Groups") class OptionGroupTranslation(models.Model): """A specific language translation for an `OptionGroup`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ optiongroup = models.ForeignKey(OptionGroup, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Translated OptionGroup Name"), max_length=255, core=True) description = models.TextField(_("Description of OptionGroup"), default='', blank=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Option Group Translation') verbose_name_plural = _('Option Groups Translations') ordering = ('optiongroup', 'name','languagecode') unique_together = ('optiongroup', 'languagecode', 'version') def __unicode__(self): return u"OptionGroupTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.optiongroup, self.name) class OptionManager(models.Manager): def from_unique_id(self, str): (og, opt) = str.split('-') group = OptionGroup.objects.get(id=og) return Option.objects.get(optionGroup=og, value=opt) class Option(models.Model): """ These are the actual items in an OptionGroup. If the OptionGroup is Size, then an Option would be Small. """ objects = OptionManager() optionGroup = models.ForeignKey(OptionGroup, edit_inline=models.TABULAR, num_in_admin=5) name = models.CharField(_("Display value"), max_length=50, core=True) value = models.SlugField(_("Stored value"), max_length=50, prepopulate_from=('name',)) price_change = models.DecimalField(_("Price Change"), null=True, blank=True, max_digits=10, decimal_places=2, help_text=_("This is the price differential for this option.")) displayOrder = models.IntegerField(_("Display Order")) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) class Meta: ordering = ('optionGroup', 'displayOrder', 'name') unique_together = (('optionGroup', 'value'),) verbose_name = _("Option Item") verbose_name_plural = _("Option Items") def _get_unique_id(self): return '%s-%s' % (str(self.optionGroup.id), str(self.value),) # optionGroup.id-value unique_id = property(_get_unique_id) def __repr__(self): return u"<Option: %s>" % self.name def __unicode__(self): return u'%s: %s' % (self.optionGroup.name, self.name) class OptionTranslation(models.Model): """A specific language translation for an `Option`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ option = models.ForeignKey(Option, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Translated Category Name"), max_length=255, core=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Option Translation') verbose_name_plural = _('Option Translations') ordering = ('option', 'name','languagecode') unique_together = ('option', 'languagecode', 'version') def __unicode__(self): return u"OptionTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.option, self.name) class ProductManager(models.Manager): def active(self): return self.filter(active=True) class Product(models.Model): """ Root class for all Products """ name = models.CharField(_("Full Name"), max_length=255, help_text=_("This is what the product will be called in the default site language. To add non-default translations, use the Product Translation section below.")) slug = models.SlugField(_("Slug Name"), unique=True, prepopulate_from=('name',), core=True, blank=False) short_description = models.TextField(_("Short description of product"), help_text=_("This should be a 1 or 2 line description in the default site language for use in product listing screens"), max_length=200, default='', blank=True) description = models.TextField(_("Description of product"), help_text=_("This field can contain HTML and should be a few paragraphs in the default site language explaining the background of the product, and anything that would help the potential customer make their purchase."), default='', blank=True) category = models.ManyToManyField(Category, filter_interface=True, blank=True, verbose_name=_("Category")) items_in_stock = models.IntegerField(_("Number in stock"), default=0) meta = models.TextField(_("Meta Description"), max_length=200, blank=True, null=True, help_text=_("Meta description for this product")) date_added = models.DateField(_("Date added"), null=True, blank=True) active = models.BooleanField(_("Is product active?"), default=True, help_text=_("This will determine whether or not this product will appear on the site")) featured = models.BooleanField(_("Featured Item"), default=False, help_text=_("Featured items will show on the front page")) ordering = models.IntegerField(_("Ordering"), default=0, help_text=_("Override alphabetical order in category display")) weight = models.DecimalField(_("Weight"), max_digits=8, decimal_places=2, null=True, blank=True) length = models.DecimalField(_("Length"), max_digits=6, decimal_places=2, null=True, blank=True) width = models.DecimalField(_("Width"), max_digits=6, decimal_places=2, null=True, blank=True) height = models.DecimalField(_("Height"), max_digits=6, decimal_places=2, null=True, blank=True) related_items = models.ManyToManyField('self', blank=True, null=True, verbose_name=_('Related Items'), related_name='related_products') also_purchased = models.ManyToManyField('self', blank=True, null=True, verbose_name=_('Previously Purchased'), related_name='also_products') taxable = models.BooleanField(_("Taxable"), default=False) taxClass = models.ForeignKey(TaxClass, verbose_name=_('Tax Class'), blank=True, null=True, help_text=_("If it is taxable, what kind of tax?")) objects = ProductManager() def _get_mainImage(self): img = False if self.productimage_set.count() > 0: img = self.productimage_set.order_by('sort')[0] else: # try to get a main image by looking at the parent if this has one try: parent = self.productvariation.parent img = parent.product.main_image except ProductVariation.DoesNotExist: pass if not img: #This should be a "Image Not Found" placeholder image try: img = ProductImage.objects.filter(product__isnull=True).order_by('sort')[0] except IndexError: import sys print >>sys.stderr, 'Warning: default product image not found - try syncdb' return img main_image = property(_get_mainImage) def translated_attributes(self, language_code=None): if not language_code: language_code = get_language() q = self.productattribute_set.filter(languagecode__exact = language_code) if q.count() == 0: q = self.productattribute_set.filter(Q(languagecode__isnull = True) | Q(languagecode__exact = "")) return q def translated_description(self, language_code=None): return lookup_translation(self, 'description', language_code) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) def translated_short_description(self, language_code=None): return lookup_translation(self, 'short_description', language_code) def _get_fullPrice(self): """ returns price as a Decimal """ subtype = self.get_subtype_with_attr('unit_price') price = None if subtype: price = subtype.unit_price else: price = self._get_qty_price(1) if not price: price = Decimal("0.00") return price unit_price = property(_get_fullPrice) def get_qty_price(self, qty): """ If QTY_DISCOUNT prices are specified, then return the appropriate discount price for the specified qty. Otherwise, return the unit_price returns price as a Decimal """ subtype = self.get_subtype_with_attr('get_qty_price') if subtype: price = subtype.get_qty_price(qty) else: price = self._get_qty_price(qty) if not price: price = self._get_fullPrice() return price def _get_qty_price(self, qty): """ returns price as a Decimal """ qty_discounts = self.price_set.exclude(expires__isnull=False, expires__lt=datetime.date.today()).filter(quantity__lte=qty) if qty_discounts.count() > 0: # Get the price with the quantity closest to the one specified without going over return Decimal(qty_discounts.order_by('-quantity')[0].price) else: return None def in_stock(self): subtype = self.get_subtype_with_attr('in_stock') if subtype: return subtype.in_stock if self.items_in_stock > 0: return True else: return False; def __unicode__(self): return self.name def get_absolute_url(self): return urlresolvers.reverse('satchmo_product', kwargs={'product_slug': self.slug}) class Admin: list_display = ('slug', 'name', 'unit_price', 'items_in_stock', 'get_subtypes',) list_filter = ('category',) fields = ( (None, {'fields': ('category', 'name', 'slug', 'description', 'short_description', 'date_added', 'active', 'featured', 'items_in_stock','ordering')}), (_('Meta Data'), {'fields': ('meta',), 'classes': 'collapse'}), (_('Item Dimensions'), {'fields': (('length', 'width','height',),'weight'), 'classes': 'collapse'}), (_('Tax'), {'fields':('taxable', 'taxClass'), 'classes': 'collapse'}), (_('Related Products'), {'fields':('related_items','also_purchased'),'classes':'collapse'}), ) search_fields = ['slug', 'name'] class Meta: ordering = ('ordering', 'name',) verbose_name = _("Product") verbose_name_plural = _("Products") def save(self): if not self.id: self.date_added = datetime.date.today() super(Product, self).save() def get_subtypes(self): types = [] for key in config_value('PRODUCT', 'PRODUCT_TYPES'): app, subtype = key.split("::") try: if getattr(self, subtype.lower()): types += [subtype] except models.ObjectDoesNotExist: pass return tuple(types) get_subtypes.short_description = "Product SubTypes" def get_subtype_with_attr(self, attr): for type in self.get_subtypes(): subtype = getattr(self, type.lower()) if hasattr(subtype, attr): return subtype return None def _has_variants(self): subtype = self.get_subtype_with_attr('has_variants') if subtype: return subtype.has_variants return False has_variants = property(_has_variants) def _get_category(self): """ Return the primary category associated with this product """ subtype = self.get_subtype_with_attr('get_category') if subtype: return subtype.get_category return self.category.all()[0] get_category = property(_get_category) def _get_downloadable(self): """ If this Product has any subtypes associated with it that are downloadable, then consider it downloadable """ for prod_type in self.get_subtypes(): subtype = getattr(self, prod_type.lower()) if hasattr(subtype, 'is_downloadable'): return True return False is_downloadable = property(_get_downloadable) def _get_shippable(self): """ If this Product has any subtypes associated with it that are not shippable, then consider the product not shippable. If it is downloadable, then we don't ship it either. """ if self.is_downloadable: return False subtype = self.get_subtype_with_attr('is_shippable') if subtype and not subtype.is_shippable: return False return True is_shippable = property(_get_shippable) class ProductTranslation(models.Model): """A specific language translation for a `Product`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ product = models.ForeignKey('Product', edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Full Name"), max_length=255, core=True) short_description = models.TextField(_("Short description of product"), help_text=_("This should be a 1 or 2 line description for use in product listing screens"), max_length=200, default='', blank=True) description = models.TextField(_("Description of product"), help_text=_("This field can contain HTML and should be a few paragraphs explaining the background of the product, and anything that would help the potential customer make their purchase."), default='', blank=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Product Translation') verbose_name_plural = _('Product Translations') ordering = ('product', 'name','languagecode') unique_together = ('product', 'languagecode', 'version') def __unicode__(self): return u"ProductTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.product, self.name) def _cross_list(sequences): """ Code taken from the Python cookbook v.2 (19.9 - Looping through the cross-product of multiple iterators) This is used to create all the variations associated with an product """ result =[[]] for seq in sequences: result = [sublist+[item] for sublist in result for item in seq] return result def get_all_options(obj): """ Returns all possible combinations of options for this products OptionGroups as a List of Lists. Ex: For OptionGroups Color and Size with Options (Blue, Green) and (Large, Small) you'll get [['Blue', 'Small'], ['Blue', 'Large'], ['Green', 'Small'], ['Green', 'Large']] Note: the actual values will be instances of Option instead of strings """ sublist = [] masterlist = [] #Create a list of all the options & create all combos of the options for opt in obj.option_group.all(): for value in opt.option_set.all(): sublist.append(value) masterlist.append(sublist) sublist = [] return _cross_list(masterlist) class CustomProduct(models.Model): """ Product which must be custom-made or ordered. """ product = models.OneToOneField(Product) downpayment = models.IntegerField(_("Percent Downpayment"), default=20) deferred_shipping = models.BooleanField(_('Deferred Shipping'), help_text=_('Do not charge shipping at checkout for this item.'), default=False) option_group = models.ManyToManyField(OptionGroup, blank=True,) def _is_shippable(self): return not self.deferred_shipping is_shippable = property(fget=_is_shippable) def _get_fullPrice(self): """ returns price as a Decimal """ return self.get_qty_price(1) unit_price = property(_get_fullPrice) def get_qty_price(self, qty): """ If QTY_DISCOUNT prices are specified, then return the appropriate discount price for the specified qty. Otherwise, return the unit_price returns price as a Decimal """ price = self.product._get_qty_price(qty) if not price: price = self.product._get_fullPrice() return price * self.downpayment / 100 def get_full_price(self, qty=1): """ Return the full price, ignoring the deposit. """ price = self.product._get_qty_price(qty) if not price: price = self.product._get_fullPrice() return price full_price = property(fget=get_full_price) def __unicode__(self): return u"CustomProduct: %s" % self.product.name def get_valid_options(self): """ Returns all of the valid options """ return get_all_options(self) class Admin: pass class CustomTextField(models.Model): """ A text field to be filled in by a customer. """ name = models.CharField(_('Custom field name'), max_length=40, core=True) slug = models.SlugField() products = models.ForeignKey(CustomProduct, verbose_name=_('Custom Fields'), edit_inline=models.TABULAR, num_in_admin=3, related_name='custom_text_fields') sort_order = models.IntegerField(_("Sort Order"), help_text=_("The display order for this group.")) price_change = models.DecimalField(_("Price Change"), max_digits=10, decimal_places=2, blank=True, null=True) def translated_name(self, language_code=None): return lookup_translation(self, 'name', language_code) class Meta: ordering = ('sort_order',) class CustomTextFieldTranslation(models.Model): """A specific language translation for a `CustomTextField`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ customtextfield = models.ForeignKey(CustomTextField, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) name = models.CharField(_("Translated Custom Text Field Name"), max_length=255, core=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('CustomTextField Translation') verbose_name_plural = _('CustomTextField Translations') ordering = ('customtextfield', 'name','languagecode') unique_together = ('customtextfield', 'languagecode', 'version') def __unicode__(self): return u"CustomTextFieldTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.customtextfield, self.name) class ConfigurableProduct(models.Model): """ Product with selectable options. This is a sort of virtual product that is visible to the customer, but isn't actually stocked on a shelf, the specific "shelf" product is determined by the selected options. """ product = models.OneToOneField(Product) option_group = models.ManyToManyField(OptionGroup, blank=True,) create_subs = models.BooleanField(_("Create Variations"), default=False, help_text =_("Create ProductVariations for all this product's options. To use this, you must first add an option, save, then return to this page and select this option.")) def _cross_list(self, sequences): """ Code taken from the Python cookbook v.2 (19.9 - Looping through the cross-product of multiple iterators) This is used to create all the variations associated with an product """ result =[[]] for seq in sequences: result = [sublist+[item] for sublist in result for item in seq] return result def get_all_options(self): """ Returns all possible combinations of options for this products OptionGroups as a List of Lists. Ex: For OptionGroups Color and Size with Options (Blue, Green) and (Large, Small) you'll get [['Blue', 'Small'], ['Blue', 'Large'], ['Green', 'Small'], ['Green', 'Large']] Note: the actual values will be instances of Option instead of strings """ sublist = [] masterlist = [] #Create a list of all the options & create all combos of the options for opt in self.option_group.all(): for value in opt.option_set.all(): sublist.append(value) masterlist.append(sublist) sublist = [] return _cross_list(masterlist) def get_valid_options(self): """ Returns the same output as get_all_options(), but filters out Options that this ConfigurableProduct doesn't have a ProductVariation for. """ opts = get_all_options(self) newopts = [] for a in opts: if self.get_product_count(a): newopts.append(a) return newopts def create_products(self): """ Get a list of all the optiongroups applied to this object Create all combinations of the options and create variations """ combinedlist = self.get_all_options() #Create new ProductVariation for each combo. for options in combinedlist: # Check for an existing ProductVariation. # Simplify this when Django #4464 is fixed. first_option = True pvs = ProductVariation.objects.filter(parent=self) for option in options: query = pvs.filter(options=option) if first_option: first_option = False else: query = query.filter(product__id__in=products) products = [variation.product.id for variation in query] if not products: # There isn't an existing ProductVariation. variant = Product(items_in_stock=0) optnames = [opt.value for opt in options] slug = u'%s_%s' % (self.product.slug, u'_'.join(optnames)) while Product.objects.filter(slug=slug).count(): slug = u'_'.join((slug, unicode(self.product.id))) variant.slug = slug variant.save() pv = ProductVariation(product=variant, parent=self) pv.save() for option in options: pv.options.add(option) variant.name = u'%s (%s)' % ( self.product.name, u'/'.join(optnames)) variant.save() return True def _ensure_option_set(self, options): """ Takes an iterable of Options (or str(Option)) and outputs a Set of str(Option) suitable for comparing to a productvariation.option_values """ if not isinstance(options, Set): optionSet = Set() for opt in options: optionSet.add(opt.unique_id) return optionSet else: return options def get_product_from_options(self, options): """ Accepts an iterable of either Option object or str(Option) objects Returns the product that matches or None """ options = self._ensure_option_set(options) for member in self.productvariation_set.all(): if member.option_values == options: return member.product return None def get_product_count(self, options): options = self._ensure_option_set(options) count = 0 for variant in self.productvariation_set.filter(product__active='1'): if variant.option_values == options: count+=1 return count def save(self): """ Right now this only works if you save the suboptions, then go back and choose to create the variations. """ super(ConfigurableProduct, self).save() # Doesn't work with admin - the manipulator doesn't add the option_group # until after save() is called. if self.create_subs and self.option_group.count(): self.create_products() self.create_subs = False super(ConfigurableProduct, self).save() def get_absolute_url(self): return self.product.get_absolute_url() class Admin: pass def __unicode__(self): return self.product.slug class DownloadableProduct(models.Model): """ This type of Product is a file to be downloaded """ product = models.OneToOneField(Product) file = models.FileField(upload_to=protected_dir()) num_allowed_downloads = models.IntegerField(help_text=_("Number of times link can be accessed.")) expire_minutes = models.IntegerField(help_text=_("Number of minutes the link should remain active.")) active = models.BooleanField(help_text=_("Is this download currently active?"), default=True) is_shippable = False is_downloadable = True def __unicode__(self): return self.product.slug def create_key(self): salt = sha.new(str(random.random())).hexdigest()[:5] download_key = sha.new(salt+self.product.name).hexdigest() return download_key def order_success(self, order, order_item): from satchmo.contact.models import DownloadLink new_link = DownloadLink(downloadable_product=self, order=order, key=self.create_key(), num_attempts=0) new_link.save() class Admin: pass #class BundledProduct(models.Model): # """ # This type of Product is a group of products that are sold as a set # NOTE: This doesn't do anything yet - it's just an example # """ # product = models.OneToOneField(Product) # members = models.ManyToManyField(Product, related_name='parent_productgroup_set') # # class Admin: # pass class ProductVariation(models.Model): """ This is the real Product that is ordered when a customer orders a ConfigurableProduct with the matching Options selected """ product = models.OneToOneField(Product) options = models.ManyToManyField(Option, filter_interface=True, core=True) parent = models.ForeignKey(ConfigurableProduct, core=True) def _get_fullPrice(self): """ Get price based on parent ConfigurableProduct """ if not self.parent.product.unit_price: return None # allow explicit setting of prices. try: qty_discounts = self.price_set.exclude(expires__isnull=False, expires__lt=datetime.date.today()).filter(quantity__lte=1) if qty_discounts.count() > 0: # Get the price with the quantity closest to the one specified without going over return qty_discounts.order_by('-quantity')[0].price except AttributeError: # otherwise calculate from options price_delta = Decimal("0.00") for option in self.options.all(): if option.price_change: price_delta += option.price_change return self.parent.product.unit_price + price_delta unit_price = property(_get_fullPrice) def _get_optionName(self): "Returns the options in a human readable form" if self.options.count() == 0: return self.parent.verbose_name output = self.parent.verbose_name + " ( " numProcessed = 0 # We want the options to be sorted in a consistent manner optionDict = dict([(sub.optionGroup.sort_order, sub) for sub in self.options.all()]) for optionNum in sorted(optionDict.keys()): numProcessed += 1 if numProcessed == self.options.count(): output += optionDict[optionNum].name else: output += optionDict[optionNum].name + "/" output += " )" return output full_name = property(_get_optionName) def _get_optionValues(self): """ Return a set of all the valid options for this variant. A set makes sure we don't have to worry about ordering. """ output = Set() for option in self.options.all(): output.add(option.unique_id) return(output) option_values = property(_get_optionValues) def _has_variants(self): return True has_variants = property(_has_variants) def _get_category(self): """ Return the primary category associated with this product """ return self.parent.product.category.all()[0] get_category = property(_get_category) def _check_optionParents(self): groupList = [] for option in self.options.all(): if option.optionGroup.id in groupList: return(True) else: groupList.append(option.optionGroup.id) return(False) def isValidOption(self, field_data, all_data): raise validators.ValidationError(_("Two options from the same option group can not be applied to an item.")) def save(self): pvs = ProductVariation.objects.filter(parent=self.parent) pvs = pvs.exclude(product=self.product) for pv in pvs: if pv.option_values == self.option_values: return # Don't allow duplicates #Ensure associated Product has a reasonable display name if not self.product.name: options = [] for option in self.options.order_by("optionGroup"): options += [option.name] self.product.name = u'%s (%s)' % (self.parent.product.name, u'/'.join(options)) self.product.save() super(ProductVariation, self).save() def get_absolute_url(self): return self.product.get_absolute_url() class Admin: pass def __unicode__(self): return self.product.slug class ProductAttribute(models.Model): """ Allows arbitrary name/value pairs (as strings) to be attached to a product. This is a very quick and dirty way to add extra info to a product. If you want more structure then this, create your own subtype to add whatever you want to your Products. """ product = models.ForeignKey(Product, edit_inline=models.TABULAR, num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES, null=True, blank=True) name = models.SlugField(_("Attribute Name"), max_length=100, core=True) value = models.CharField(_("Value"), max_length=255) class Meta: verbose_name = _("Product Attribute") verbose_name_plural = _("Product Attributes") class Price(models.Model): """ A Price! Separating it out lets us have different prices for the same product for different purposes. For example for quantity discounts. The current price should be the one with the earliest expires date, and the highest quantity that's still below the user specified (IE: ordered) quantity, that matches a given product. """ product = models.ForeignKey(Product, edit_inline=models.TABULAR, num_in_admin=2) price = models.DecimalField(_("Price"), max_digits=10, decimal_places=2, core=True) quantity = models.IntegerField(_("Discount Quantity"), default=1, help_text=_("Use this price only for this quantity or higher")) expires = models.DateField(null=True, blank=True) #TODO: add fields here for locale/currency specific pricing def __unicode__(self): return unicode(self.price) def save(self): prices = Price.objects.filter(product=self.product, quantity=self.quantity) ## Jump through some extra hoops to check expires - if there's a better way to handle this field I can't think of it. Expires needs to be able to be set to None in cases where there is no expiration date. if self.expires: prices = prices.filter(expires=self.expires) else: prices = prices.filter(expires__isnull=True) if self.id: prices = prices.exclude(id=self.id) if prices.count(): return #Duplicate Price super(Price, self).save() class Meta: ordering = ['expires', '-quantity'] verbose_name = _("Price") verbose_name_plural = _("Prices") unique_together = (("product", "quantity", "expires"),) class ProductImage(models.Model): """ A picture of an item. Can have many pictures associated with an item. Thumbnails are automatically created. """ product = models.ForeignKey(Product, null=True, blank=True, edit_inline=models.STACKED, num_in_admin=3) picture = ImageWithThumbnailField(verbose_name=_('Picture'), upload_to=upload_dir(), name_field="_filename") #Media root is automatically prepended caption = models.CharField(_("Optional caption"), max_length=100, null=True, blank=True) sort = models.IntegerField(_("Sort Order"), core=True) def translated_caption(self, language_code=None): return lookup_translation(self, 'caption', language_code) def _get_filename(self): if self.product: return '%s-%s' % (self.product.slug, self.id) else: return 'default' _filename = property(_get_filename) def __unicode__(self): if self.product: return u"Image of Product %s" % self.product.slug elif self.caption: return u"Image with caption \"%s\"" % self.caption else: return u"%s" % self.picture class Meta: ordering = ['sort'] unique_together = (('product', 'sort'),) verbose_name = _("Product Image") verbose_name_plural = _("Product Images") class Admin: pass class ProductImageTranslation(models.Model): """A specific language translation for a `ProductImage`. This is intended for all descriptions which are not the default settings.LANGUAGE. """ productimage = models.ForeignKey(ProductImage, edit_inline=models.STACKED, related_name="translations", num_in_admin=1) languagecode = models.CharField(_('language'), max_length=10, choices=settings.LANGUAGES) caption = models.CharField(_("Translated Caption"), max_length=255, core=True) version = models.IntegerField(_('version'), default=1) active = models.BooleanField(_('active'), default=True) class Meta: verbose_name = _('Product Image Translation') verbose_name_plural = _('Product Image Translations') ordering = ('productimage', 'caption','languagecode') unique_together = ('productimage', 'languagecode', 'version') def __unicode__(self): return u"ProductImageTranslation: [%s] (ver #%i) %s Name: %s" % (self.languagecode, self.version, self.productimage, self.name) UNSET = object() def lookup_translation(obj, attr, language_code=None, version=-1): """Get a translated attribute by language. If specific language isn't found, returns the attribute from the base object. """ if not language_code: language_code = get_language() log.debug("looking up translation [%s] %s", language_code.encode('utf-8'), attr.encode('utf-8')) if not hasattr(obj, '_translationcache'): obj._translationcache = {} short_code = language_code pos = language_code.find('_') if pos>-1: short_code = language_code[:pos] else: pos = language_code.find('-') if pos>-1: short_code = language_code[:pos] trans = None has_key = obj._translationcache.has_key(language_code) if has_key: if obj._translationcache[language_code] == None and short_code != language_code: return lookup_translation(obj, attr, short_code) if not has_key: q = obj.translations.filter( languagecode__iexact = language_code) if q.count() == 0: obj._translationcache[language_code] = None if short_code != language_code: return lookup_translation(obj, attr, language_code=short_code, version=version) else: q = obj.translations.filter( languagecode__istartswith = language_code) if q.count()>0: trans = None if version > -1: trans = q.order_by('-version')[0] else: # try to get the requested version, if it is available, # else fallback to the most recent version fallback = None for t in q.order_by('-version'): if not fallback: fallback = t if t.version == version: trans = t break if not trans: trans = fallback obj._translationcache[language_code] = trans if not trans: trans = obj._translationcache[language_code] if not trans: trans = obj log.debug("No such language version, using obj") val = getattr(trans, attr, UNSET) if trans != obj and (val in (None, UNSET)): val = getattr(obj, attr) log.debug("Translated version: %s", val.encode('utf-8')) return mark_safe(val)
"""These settings rely on various environment variables being set """ import os import sys from pathlib import Path from django.db.utils import OperationalError BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split() TEST = 'test' in sys.argv or 'pytest' in sys.argv[0] DEBUG = bool(os.environ.get('DEBUG', False)) SERVER_EMAIL = 'contact@bustimes.org' DEFAULT_FROM_EMAIL = 'bustimes.org <contact@bustimes.org>' if TEST: EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' else: EMAIL_HOST = os.environ.get('EMAIL_HOST', '') EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '') EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_TIMEOUT = 10 INSTALLED_APPS = [ 'accounts', 'busstops', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.sitemaps', 'bustimes', 'disruptions', 'fares', 'vehicles', 'vosa', 'antispam', 'email_obfuscator', 'channels', 'api', 'rest_framework', 'django_filters' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'beeline.middleware.django.HoneyMiddleware', ] SECURE_REFERRER_POLICY = None if DEBUG and 'runserver' in sys.argv: INSTALLED_APPS.append('debug_toolbar') MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'debug_toolbar_force.middleware.ForceDebugToolbarMiddleware', ] # Docker import socket _, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + '1' for ip in ips] + ['127.0.0.1', '10.0.2.2'] ROOT_URLCONF = 'buses.urls' ASGI_APPLICATION = 'vehicles.routing.application' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ.get('DB_NAME', 'bustimes'), 'CONN_MAX_AGE': None, # 'DISABLE_SERVER_SIDE_CURSORS': True, 'OPTIONS': { 'application_name': os.environ.get('APPLICATION_NAME') or ' '.join(sys.argv)[:63], 'connect_timeout': 3 }, 'TEST': { 'SERIALIZE': False } } } TEST_RUNNER = 'django_slowtests.testrunner.DiscoverSlowestTestsRunner' NUM_SLOW_TESTS = 20 AUTH_USER_MODEL = 'accounts.User' LOGIN_REDIRECT_URL = '/vehicles' REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' if os.environ.get('READ_ONLY_DB_HOST'): REPLICA_DATABASES = [] for i, host in enumerate(os.environ['READ_ONLY_DB_HOST'].split()): key = f'read-only-{i}' DATABASES[key] = DATABASES['default'].copy() DATABASES[key]['HOST'] = host REPLICA_DATABASES.append(key) DATABASE_ROUTERS = ['multidb.PinningReplicaRouter'] MIDDLEWARE.append('busstops.middleware.pin_db_middleware') READ_DATABASE = key else: READ_DATABASE = 'default' DATA_UPLOAD_MAX_MEMORY_SIZE = None DATA_UPLOAD_MAX_NUMBER_FIELDS = 2000 REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', REDIS_URL) CELERY_RESULT_BACKEND = CELERY_BROKER_URL CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [CELERY_BROKER_URL], 'expiry': 20 } } } STATIC_URL = '/static/' STATIC_ROOT = os.environ.get('STATIC_ROOT', BASE_DIR.parent / 'bustimes-static') STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' TEMPLATE_MINIFER_STRIP_FUNCTION = 'buses.utils.minify' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'debug': DEBUG or TEST, 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': [('django.template.loaders.cached.Loader', [ 'template_minifier.template.loaders.app_directories.Loader' ])] } } ] if DEBUG: TEMPLATES[0]['OPTIONS']['loaders'] = ['django.template.loaders.app_directories.Loader'] elif TEST: TEMPLATES[0]['OPTIONS']['loaders'] = [('django.template.loaders.cached.Loader', [ 'django.template.loaders.app_directories.Loader' ])] CACHES = {} if TEST: CACHES["default"] = { "BACKEND": "django.core.cache.backends.dummy.DummyCache" } else: CACHES["default"] = { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": REDIS_URL, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } VARNISH_HOST = os.environ.get('VARNISH_HOST') VARNISH_PORT = os.environ.get('VARNISH_PORT') if VARNISH_HOST and VARNISH_PORT: VARNISH = (VARNISH_HOST, int(VARNISH_PORT)) else: VARNISH = None TIME_FORMAT = 'H:i' DATE_FORMAT = 'l j F Y' DATETIME_FORMAT = 'j M H:i' TIME_ZONE = 'Europe/London' USE_TZ = True USE_I18N = False LANGUAGE_CODE = 'en-gb' USE_L10N = False # force use of TIME_FORMAT, DATE_FORMAT etc. Alas, deprecated def before_send(event, hint): if 'exc_info' in hint: exc_type, exc_value, traceback = hint['exc_info'] if isinstance(exc_value, OperationalError): return return event if TEST: pass elif not DEBUG and 'collectstatic' not in sys.argv and 'SENTRY_DSN' in os.environ: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.redis import RedisIntegration from sentry_sdk.integrations.celery import CeleryIntegration sentry_sdk.init( dsn=os.environ['SENTRY_DSN'], integrations=[DjangoIntegration(), RedisIntegration(), CeleryIntegration()], ignore_errors=[KeyboardInterrupt], before_send=before_send ) if not TEST: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, } TFL = { 'app_id': os.environ.get('TFL_APP_ID'), 'app_key': os.environ.get('TFL_APP_KEY') } TFWM = { 'app_id': os.environ.get('TFWM_APP_ID'), 'app_key': os.environ.get('TFWM_APP_KEY') } DATA_DIR = BASE_DIR / 'data' TNDS_DIR = DATA_DIR / 'TNDS' AKISMET_API_KEY = os.environ.get('AKISMET_API_KEY') AKISMET_SITE_URL = 'https://bustimes.org' # see bustimes.management.commands.import_passenger PASSENGER_OPERATORS = [ ('Go Cornwall Bus', 'https://www.gocornwallbus.co.uk/open-data', 'SW', { 'TFCN': 'TFCN', 'TfCN': 'TFCN' }), ('Plymouth Citybus', 'https://www.plymouthbus.co.uk/open-data', 'SW', { 'PLYC': 'PLYC' }), ('Go North West', 'https://www.gonorthwest.co.uk/open-data', 'NW', { 'GONW': 'GONW' }), ('Metrobus', 'https://www.metrobus.co.uk/open-data', 'SE', { 'METR': 'METR' }), ('Nottingham City Transport', 'https://www.nctx.co.uk/open-data', 'EM', { 'NCT': 'NCTR' }), ('Borders Buses', 'https://www.bordersbuses.co.uk/open-data', 'S', { 'PERY': 'BORD', 'BB': 'BORD', '': 'PERY', }), ('morebus', 'https://www.morebus.co.uk/open-data', 'SW', { 'WDBC': 'WDBC', 'DAMY': 'DAMY', }), ('Bluestar', 'https://www.bluestarbus.co.uk/open-data', 'SW', { 'BLUS': 'BLUS', 'UNIL': 'UNIL', }), ('Salisbury Reds', 'https://www.salisburyreds.co.uk/open-data', 'SW', { 'SWWD': 'SWWD', }), ('Southern Vectis', 'https://www.islandbuses.info/open-data', 'SW', { 'SVCT': 'SVCT', }), ('Swindon’s Bus Company', 'https://www.swindonbus.co.uk/open-data', 'SW', { 'TDTR': 'TDTR', 'SWIN': 'TDTR', }), ('Reading Buses', 'https://www.reading-buses.co.uk/open-data', 'SE', { 'RBUS': 'RBUS', }), ('Thames Valley Buses', 'https://www.thamesvalleybuses.com/open-data', 'SE', { 'THVB': 'THVB', 'CTNY': 'CTNY', }), ('Newbury & District', 'https://data.discoverpassenger.com/operator/kennections', 'SE', { 'NADS': 'NADS', }), ('West Coast Motors', 'https://www.westcoastmotors.co.uk/open-data', 'S', { 'WCM': 'WCMO', 'GCB': 'GCTB', # Glasgow Citybus }), ('Cardiff Bus', 'https://www.cardiffbus.com/open-data', 'W', { 'CB': 'CBUS', # 'NB': '', }), ('Yellow Buses', 'https://www.yellowbuses.co.uk/open-data', 'SW', { 'YELL': 'YELL', }), ('Brighton & Hove Buses', 'https://www.buses.co.uk/open-data', 'SE', { 'BH': 'BHBC', }), ('Blackpool Transport', 'https://www.blackpooltransport.com/open-data', 'NW', { 'RR': 'BLAC', }), ('Transdev Blazefield', 'https://www.transdevbus.co.uk/open-data', 'NW', { 'LUI': 'LNUD', 'ROS': 'ROST', 'BPT': 'BPTR', 'KDT': 'KDTR', 'HDT': 'HRGT', 'YCD': 'YCST', 'TPEN': 'TPEN', }), ('Go North East', 'https://www.gonortheast.co.uk/open-data', 'NE', { 'GNE': 'GNEL', }), ('East Yorkshire', 'https://www.eastyorkshirebuses.co.uk/open-data', 'Y', { 'EYMS': 'EYMS', }), ('McGill’s', 'https://data.discoverpassenger.com/operator/mcgills', 'S', { 'MCG': 'MCGL', 'McG': 'MCGL', }), ('Warringtons Own Buses', 'https://www.warringtonsownbuses.co.uk/open-data', 'NW', { 'WOB': 'WBTR', }), ('Newport Bus', 'https://www.newportbus.co.uk/open-data', 'W', { 'NWPT': 'NWPT', }), ] # see bustimes.management.commands.import_bod BOD_OPERATORS = [ ('WMSA', 'EM', {}, False), ('LANT', 'EM', {}, False), ('NWBT', 'NW', {}, False), ('MARS', 'SE', {}, False), ('FBOS', None, { 'FYOR': 'FYOR', # 'FPOT': 'FPOT', # 'FSYO': 'FSYO', # 'FMAN': 'FMAN', # 'FLDS': 'FLDS', # 'FSMR': 'FSMR', 'FHUD': 'FHUD', 'FHAL': 'FHUD', 'FBRA': 'FBRA', # 'FESX': 'FESX', 'FECS': 'FECS', # 'FHDO': 'FHDO', 'FTVA': 'FTVA', # 'FHAM': 'FHAM', # 'FDOR': 'FDOR', 'FCWL': 'FCWL', 'FBRI': 'FBRI', # 'FLEI': 'FLEI', 'RRAR': 'RRAR', 'FBOS': 'FBOS', # 'FWYO': 'FWYO', }, True), # these no longer operate services - this is just to prevent their TNDS data being used: ('PTSG', None, { 'ABUS': 'ABUS', 'PTSG': 'PTSG', }, False), ('TNXB', 'WM', { 'TNXB': 'TNXB', 'TCVW': 'TCVW', }, False), ('UNOE', 'SE', { 'UBN': 'UNOE', 'UNIB': 'UNOE', 'OP': 'UNOE', 'UN': 'UNOE', }, False), ('TBTN', 'EM', { 'BRTB': 'TBTN', }, False), ('KBUS', 'SE', {}, False), ('NIBS', 'SE', {}, False), # ('SESX', 'EA', {}, False), ('STCB', 'EA', {}, False), ('CSVC', 'EA', { 'CS': 'CSVC' }, False), ('HIPK', 'EM', { 'OP': 'HIPK', 'HPB': 'HIPK', }, False), ('HNTS', 'EM', {}, False), # ('SLBS', 'WM', {}, True), ('LODG', 'SE', {}, False), ('FRDS', 'SE', {}, False), ('AVMT', 'SW', {}, False), ('BZCO', 'SW', {}, False), ('C2WI', 'SW', {}, False), ('CNTY', 'SW', {}, False), ('COAC', 'SW', {}, False), ('COTS', 'SW', {}, False), ('CRYC', 'SW', {}, False), ('DTCO', 'SW', {}, False), ('FRMN', 'SW', {}, False), ('FSRV', 'SW', {}, False), ('FTZL', 'SW', {}, False), ('GWIL', 'SW', {}, False), ('HGCO', 'SW', {}, False), ('HOPE', 'SW', {}, False), ('JACK', 'SW', {}, False), ('LTRV', 'SW', {}, False), ('NAKL', 'SW', {}, False), ('OTSS', 'SW', {}, False), ('PULH', 'SW', {}, False), ('RIDL', 'SW', {}, False), ('RSLN', 'SW', {}, False), ('SMST', 'SW', {}, False), ('SWCO', 'SW', {}, False), ('TAWT', 'SW', {}, False), ('TLYH', 'SW', {}, False), ('TOTN', 'SW', {}, False), ('YEOS', 'SW', {}, False), ('SMMC', 'SW', {}, False), ('GYLC', 'SW', {}, False), ('SWAN', 'SW', {}, False), ('CTCO', 'SW', {}, False), ('EBLY', 'SW', {}, False), ('BYCO', 'SW', {}, False), ('NEJH', 'SW', {}, False), ('BNNT', 'SW', {}, False), ('XLBL', 'SW', {}, False), ('NCSL', 'SW', {}, False), ('AMKC', 'SW', {}, False), ('EUTX', 'SW', {}, False), ('ESTW', 'SW', {}, False), ('NABC', 'SW', {}, False), ('QVED', 'SW', {}, False), ('STAC', 'SW', {}, False), ('SWOC', 'SW', {}, False), ('DDLT', 'SW', {}, False), ('CHCB', 'SW', {}, False), ('DJWA', 'SW', {}, False), ('BNSC', 'SW', {}, False), ('MARC', 'SW', {}, False), ('NRTL', 'SW', {}, False), ('PRIC', 'SW', {}, False), ('LIHO', 'SW', {}, False), ('DPCR', 'SW', {}, False), # ('NATX', 'GB', {}, False), ('KETR', 'SE', {}, False), # ('HACO', 'EA', {}, False), # ('PCCO', 'EM', {}, False), ('HCCL', 'NE', { 'HCC': 'WGHC' }, False), ('SPSV', 'SE', {}, False), ('NVTR', 'SE', {}, False), ('LEMN', 'SE', {}, False), ('GOCH', 'SE', { 'GO': 'GOCH' }, False), ('LAKC', 'WM', {}, True), # incomplete ('CBBH', 'EM', { 'CBBH': 'CBBH', 'CBNL': 'CBNL', 'CBL': 'CBNL', }, False), # ('BULL', 'NW', {}, False), ('SELT', 'NW', {}, False), # Selwyns Ticketer ('ROSS', 'Y', {}, False), # Ross Travel Ticketer ('GRYC', 'EM', {}, False), ('CKMR', 'SE', {}, False), # ('A2BR', 'EA', {}, False), ('A2BV', 'NW', {}, False), # ('STNE', 'NE', { # 'STNE': 'STNE', # 'STNT': 'STNT', # }, False), ('LAWS', 'EM', {}, False), ('BMCS', 'SE', {}, False), ('AJCO', 'EA', {}, False), ('LTEA', 'EA', {}, False), ('CPLT', 'EA', {}, False), ('OBUS', 'EA', { 'OURH': 'OURH', 'OBUS': 'OBUS', }, False), ('WNGS', None, { # Rotala Group of Companies 'WINGS': 'WNGS', 'TGM': 'WNGS', # Diamond SE 'NXHH': 'NXHH', # Hotel Hoppa 'DIAM': 'DIAM', # Diamond WM 'GTRI': 'GTRI', # Diamond NW 'PBLT': 'PBLT', # Preston }, False), ('PLNG', 'EA', {}, False), ('SNDR', 'EA', {}, False), ('STOT', 'NW', {}, False), ('CARL', 'SE', {}, False), ('IRVD', 'NW', {}, False), ('FALC', 'SE', {}, False), ('VECT', 'SE', {}, True), ('ACME', 'SE', {}, False), ('Viking Coaches', 'NW', { 'VIKG': 'VIKG' }, False), # Viking (BODS API thinks their operator code is WVIK, but that's a different Viking) ('ALSC', 'NW', {}, False), # Happy Al's ('LCAC', 'NW', {}, False), ('LNNE', 'NW', {}, False), ('RBUS', 'SE', {}, True), # incomplete ('ROOS', 'SW', {}, False), ('SEWR', 'SW', {}, False), ('HRBT', 'SE', {}, False), ('KENS', 'Y', {}, False), ('AWAN', 'SE', {}, False), ('LUCK', 'SW', {}, False), ('GVTR', 'NE', {}, False), ('COTY', 'NE', {}, False), ('LMST', 'WM', {}, False), ('TEXP', 'WM', {}, False), ('BANG', 'WM', {}, False), ('SLVL', 'WM', {}, False), ('JOHS', 'WM', {}, False), ('ENSB', 'SE', {}, True), ('BRYL', 'EM', {}, False), ('MDCL', 'EM', {}, False), ('NDTR', 'EM', {}, False), ('NOCT', 'EM', {}, False), ('RELD', 'Y', {}, False), ('SSSN', 'Y', {}, False), ('KJTR', 'Y', {}, False), ('HCTY', 'Y', { 'HCTY': 'HCTY', # Connexions 'YRRB': 'YRRB', # 'Road Runner' }, False), ('NCTP', None, { 'NCTP': 'NCTP', # CT Plus Bristol (/London) 'POWB': 'POWB', # Powells 'CTPL': 'CTPL', # CT Plus Yorkshire }, False), ('LYNX', 'EA', {}, False), ('IPSW', 'EA', {}, False), ('WNCT', 'EA', {}, False), ('WHIP', 'EA', {}, False), ('SIMO', 'EA', {}, False), ('BEES', 'EA', {}, False), ('GOGO', 'NW', {}, False), ('RBTS', 'EM', {}, False), ('DELA', 'EM', {}, False), ('RLNE', 'SE', {}, False), ('HATT', 'NW', {}, False), ('SULV', 'SE', {}, False), ('WBSV', 'SE', {}, False), ('REDE', 'SE', {}, False), ('GPLM', 'SE', {}, False), ('CLNB', 'SE', {}, False), ('RRTR', 'SE', {}, False), ('RCHC', 'SE', {}, False), ('FCHS', 'NW', {}, False), ('CRSS', 'WM', {}, True), # NN Cresswell ('DAGC', None, { 'DAGC': 'DAGC', 'CRDR': 'CRDR' }, False), # ('Go East Anglia', 'EA', { # 'KCTB': 'KCTB', # 'HEDO': 'HEDO', # 'CHAM': 'CHAM', # }, False), ('DRMC', 'WM', {}, True), ('SARG', 'WM', {}, False), ('AMBS', 'EA', { 'AMBS': 'AMBS', 'SEMM': 'SEMM', }, True), ('RDRT', 'SE', { 'RR': 'RDRT', 'RR1': 'RDRT' }, False), ] # see bustimes.management.commands.import_bod STAGECOACH_OPERATORS = [ ('S', 'sblb', 'Stagecoach Bluebird', ['SBLB']), ('S', 'scfi', 'Stagecoach East Scotland', ['SCFI', 'SCPE', 'SSPH', 'STSY', 'SSTY']), ('S', 'schi', 'Stagecoach Highlands', ['SCHI', 'SCOR', 'SINV']), ('NE', 'scne', 'Stagecoach North East', ['SCNE', 'SCSS', 'SCSU', 'SCTE', 'SCHA']), ('S', 'stws', 'Stagecoach West Scotland', ['STWS', 'SCGS', 'STGS']), ('EM', 'scem', 'Stagecoach East Midlands', ['SCLI', 'SCGH', 'SCGR', 'NFKG']), ('SE', 'scso', 'Stagecoach South', ['SCPY', 'SCHM', 'SCHW', 'SCCO', 'SMSO', 'SCHS', 'SCHN']), ('SE', 'scek', 'Stagecoach South East', ['SCEK', 'SCEB', 'SCHT']), ('Y', 'syrk', 'Stagecoach Yorkshire', ['SYRK', 'YSYC', 'CLTL']), ('NW', 'sccu', 'Stagecoach Cumbria', ['SCCU', 'SCMB', 'SCNW']), ('NW', 'scmn', 'Stagecoach Manchester', ['SCMN', 'SWIG']), ('NW', 'scmy', 'Stagecoach Merseyside', ['SCMY', 'STCR', 'STWR', 'SCLA']), ('SW', 'sdvn', 'Stagecoach South West', ['SDVN', 'SDVN']), ('SE', 'sccm', 'Stagecoach East', ['SCCM', 'SCBD', 'SCPB', 'SCHU']), ('EM', 'scnh', 'Stagecoach Midlands', ['SCNH', 'SCWW']), ('SE', 'scox', 'Stagecoach Oxfordshire', ['SCOX']), ('SW', 'scgl', 'Stagecoach West', ['SCGL', 'SSWN', 'STWD', 'SCCH']), ('W', 'sswl', 'Stagecoach South Wales', ['SSWL']), ('Y', 'tram', 'Stagecoach Supertram', ['SCST']), ] # Some operators' timetables are fetched directly from e.g. # https://opendata.ticketer.com/uk/LYNX/routes_and_timetables/current.zip # rather than via the Bus Open Data site, # because sometimes BODS doesn't detect updates TICKETER_OPERATORS = [ ('EA', ['GOEA', 'KCTB', 'HEDO', 'CHAM'], 'Go East Anglia'), ('EA', ['BDRB'], 'BorderBus'), ('WM', ['DIAM'], 'Diamond Bus'), ('NW', ['GTRI'], 'Diamond Bus North West'), ('NW', ['PBLT'], 'Preston Bus'), ('EA', ['WHIP'], 'Whippet'), ('WM', ['Johnsons', 'JOHS']), ('NE', ['A-Line_Coaches_Tyne_&_Wear', 'ALGC']), ('EA', ['Ipswich_Buses', 'IPSW'], 'Ipswich Buses'), ('EM', ['Notts_and_Derby', 'NDTR'], 'Notts and Derby'), ('Y', ['RELD'], 'Reliance Motor Services'), # ('SW', ['PLYC', 'TFCN'], 'Go South West'), # ('SE', ['METR'], 'Metrobus'), ('SE', ['OXBC', 'CSLB', 'THTR'], 'Oxford Bus Company'), # ('NW', ['GONW'], 'Go North West'), ('W', ['ACYM'], 'Arriva Cymru'), ('NW', ['AMAN', 'ANWE'], 'Arriva North West'), ('NW', ['AMSY'], 'Arriva Merseyside'), ('NE', ['ARDU', 'ANEA'], 'Arriva Durham'), ('NE', ['ANUM'], 'Arriva Northumbria'), ('Y', ['WRAY', 'YTIG'], 'Arriva Yorkshire'), ('WM', ['AMNO'], 'Arriva Midlands North'), ('EM', ['AMID', 'AFCL', 'ADER'], 'Arriva Midlands'), ('SE', ['ARBB', 'ASES', 'GLAR'], 'Arriva Beds & Bucks'), ('SE', ['AMTM', 'ARHE'], 'Arriva Kent Thameside'), ('SE', ['AKSS', 'AMTM'], 'Arriva Kent & Surrey'), ('SE', ['Vectare', 'VECT']), ('EM', ['NOCT'], 'CT4N'), ('WM', ['LMST'], 'LMS Travel'), ('SE', ['ENSB'], 'Ensignbus'), ('EA', ['AMBS'], 'Ambassador Travel'), ('EA', ['WNCT'], 'West Norfolk Community Transport'), ('NW', ['GOGO'], 'Go Goodwins'), ('EM', ['Brylaine', 'BRYL']), ('EM', ['Midland_Classic', 'MDCL']), ('EM', ['RBTS'], 'Roberts Travel'), ('SE', ['Redline_Buses_Ltd', 'RLNE']), ('NW', ['HATT'], 'Hattons'), ('SE', ['Sullivan_Buses', 'SULV']), ('EA', ['Simonds', 'SIMO']), ('NE', ['Coatham_Coaches', 'COTY']), ('Y', ['HCTY'], 'Connexions Buses'), ('Y', ['KJTR'], 'York Pullman'), ('SE', ['WBSV'], 'White Bus'), ('SE', ['REDE'], 'Red Eagle'), ('SE', ['GPLM'], 'Grant Palmer'), ('SE', ['CLNB'], 'Carlone Buses'), ('NW', ['D&G_Bus_Ltd', 'DAGC', 'CRDR']), ('EA', ['Beestons_(Hadleigh)_Ltd', 'BEES']), ('Y', ['Shoreline_Suncruisers', 'SSSN']), ('WM', ['Travel_Express', 'TEXP']), ('WM', ['Banga_Buses', 'BANG']), ('EM', ['DELA'], 'Delaine Buses'), ('SE', ['RCHC'], 'Richmonds Coaches'), ('SE', ['RRTR'], 'Red Rose Travel'), ('NW', ['Finches', 'FCHS']), ('WM', ['Silverline_LandFlight_Limited', 'SLVL']), ('Y', ['POWB', 'CTPL'], 'HCT Group'), ('SW', ['NTCP', 'NCTP'], 'HCT Group'), ] Metrobus nonstandard operator code """These settings rely on various environment variables being set """ import os import sys from pathlib import Path from django.db.utils import OperationalError BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split() TEST = 'test' in sys.argv or 'pytest' in sys.argv[0] DEBUG = bool(os.environ.get('DEBUG', False)) SERVER_EMAIL = 'contact@bustimes.org' DEFAULT_FROM_EMAIL = 'bustimes.org <contact@bustimes.org>' if TEST: EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' else: EMAIL_HOST = os.environ.get('EMAIL_HOST', '') EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '') EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_TIMEOUT = 10 INSTALLED_APPS = [ 'accounts', 'busstops', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.sitemaps', 'bustimes', 'disruptions', 'fares', 'vehicles', 'vosa', 'antispam', 'email_obfuscator', 'channels', 'api', 'rest_framework', 'django_filters' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'beeline.middleware.django.HoneyMiddleware', ] SECURE_REFERRER_POLICY = None if DEBUG and 'runserver' in sys.argv: INSTALLED_APPS.append('debug_toolbar') MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'debug_toolbar_force.middleware.ForceDebugToolbarMiddleware', ] # Docker import socket _, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + '1' for ip in ips] + ['127.0.0.1', '10.0.2.2'] ROOT_URLCONF = 'buses.urls' ASGI_APPLICATION = 'vehicles.routing.application' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ.get('DB_NAME', 'bustimes'), 'CONN_MAX_AGE': None, # 'DISABLE_SERVER_SIDE_CURSORS': True, 'OPTIONS': { 'application_name': os.environ.get('APPLICATION_NAME') or ' '.join(sys.argv)[:63], 'connect_timeout': 3 }, 'TEST': { 'SERIALIZE': False } } } TEST_RUNNER = 'django_slowtests.testrunner.DiscoverSlowestTestsRunner' NUM_SLOW_TESTS = 20 AUTH_USER_MODEL = 'accounts.User' LOGIN_REDIRECT_URL = '/vehicles' REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' if os.environ.get('READ_ONLY_DB_HOST'): REPLICA_DATABASES = [] for i, host in enumerate(os.environ['READ_ONLY_DB_HOST'].split()): key = f'read-only-{i}' DATABASES[key] = DATABASES['default'].copy() DATABASES[key]['HOST'] = host REPLICA_DATABASES.append(key) DATABASE_ROUTERS = ['multidb.PinningReplicaRouter'] MIDDLEWARE.append('busstops.middleware.pin_db_middleware') READ_DATABASE = key else: READ_DATABASE = 'default' DATA_UPLOAD_MAX_MEMORY_SIZE = None DATA_UPLOAD_MAX_NUMBER_FIELDS = 2000 REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', REDIS_URL) CELERY_RESULT_BACKEND = CELERY_BROKER_URL CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [CELERY_BROKER_URL], 'expiry': 20 } } } STATIC_URL = '/static/' STATIC_ROOT = os.environ.get('STATIC_ROOT', BASE_DIR.parent / 'bustimes-static') STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' TEMPLATE_MINIFER_STRIP_FUNCTION = 'buses.utils.minify' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'debug': DEBUG or TEST, 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': [('django.template.loaders.cached.Loader', [ 'template_minifier.template.loaders.app_directories.Loader' ])] } } ] if DEBUG: TEMPLATES[0]['OPTIONS']['loaders'] = ['django.template.loaders.app_directories.Loader'] elif TEST: TEMPLATES[0]['OPTIONS']['loaders'] = [('django.template.loaders.cached.Loader', [ 'django.template.loaders.app_directories.Loader' ])] CACHES = {} if TEST: CACHES["default"] = { "BACKEND": "django.core.cache.backends.dummy.DummyCache" } else: CACHES["default"] = { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": REDIS_URL, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } VARNISH_HOST = os.environ.get('VARNISH_HOST') VARNISH_PORT = os.environ.get('VARNISH_PORT') if VARNISH_HOST and VARNISH_PORT: VARNISH = (VARNISH_HOST, int(VARNISH_PORT)) else: VARNISH = None TIME_FORMAT = 'H:i' DATE_FORMAT = 'l j F Y' DATETIME_FORMAT = 'j M H:i' TIME_ZONE = 'Europe/London' USE_TZ = True USE_I18N = False LANGUAGE_CODE = 'en-gb' USE_L10N = False # force use of TIME_FORMAT, DATE_FORMAT etc. Alas, deprecated def before_send(event, hint): if 'exc_info' in hint: exc_type, exc_value, traceback = hint['exc_info'] if isinstance(exc_value, OperationalError): return return event if TEST: pass elif not DEBUG and 'collectstatic' not in sys.argv and 'SENTRY_DSN' in os.environ: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.redis import RedisIntegration from sentry_sdk.integrations.celery import CeleryIntegration sentry_sdk.init( dsn=os.environ['SENTRY_DSN'], integrations=[DjangoIntegration(), RedisIntegration(), CeleryIntegration()], ignore_errors=[KeyboardInterrupt], before_send=before_send ) if not TEST: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, } TFL = { 'app_id': os.environ.get('TFL_APP_ID'), 'app_key': os.environ.get('TFL_APP_KEY') } TFWM = { 'app_id': os.environ.get('TFWM_APP_ID'), 'app_key': os.environ.get('TFWM_APP_KEY') } DATA_DIR = BASE_DIR / 'data' TNDS_DIR = DATA_DIR / 'TNDS' AKISMET_API_KEY = os.environ.get('AKISMET_API_KEY') AKISMET_SITE_URL = 'https://bustimes.org' # see bustimes.management.commands.import_passenger PASSENGER_OPERATORS = [ ('Go Cornwall Bus', 'https://www.gocornwallbus.co.uk/open-data', 'SW', { 'TFCN': 'TFCN', 'TfCN': 'TFCN' }), ('Plymouth Citybus', 'https://www.plymouthbus.co.uk/open-data', 'SW', { 'PLYC': 'PLYC' }), ('Go North West', 'https://www.gonorthwest.co.uk/open-data', 'NW', { 'GONW': 'GONW' }), ('Metrobus', 'https://www.metrobus.co.uk/open-data', 'SE', { 'MB': 'METR' }), ('Nottingham City Transport', 'https://www.nctx.co.uk/open-data', 'EM', { 'NCT': 'NCTR' }), ('Borders Buses', 'https://www.bordersbuses.co.uk/open-data', 'S', { 'PERY': 'BORD', 'BB': 'BORD', '': 'PERY', }), ('morebus', 'https://www.morebus.co.uk/open-data', 'SW', { 'WDBC': 'WDBC', 'DAMY': 'DAMY', }), ('Bluestar', 'https://www.bluestarbus.co.uk/open-data', 'SW', { 'BLUS': 'BLUS', 'UNIL': 'UNIL', }), ('Salisbury Reds', 'https://www.salisburyreds.co.uk/open-data', 'SW', { 'SWWD': 'SWWD', }), ('Southern Vectis', 'https://www.islandbuses.info/open-data', 'SW', { 'SVCT': 'SVCT', }), ('Swindon’s Bus Company', 'https://www.swindonbus.co.uk/open-data', 'SW', { 'TDTR': 'TDTR', 'SWIN': 'TDTR', }), ('Reading Buses', 'https://www.reading-buses.co.uk/open-data', 'SE', { 'RBUS': 'RBUS', }), ('Thames Valley Buses', 'https://www.thamesvalleybuses.com/open-data', 'SE', { 'THVB': 'THVB', 'CTNY': 'CTNY', }), ('Newbury & District', 'https://data.discoverpassenger.com/operator/kennections', 'SE', { 'NADS': 'NADS', }), ('West Coast Motors', 'https://www.westcoastmotors.co.uk/open-data', 'S', { 'WCM': 'WCMO', 'GCB': 'GCTB', # Glasgow Citybus }), ('Cardiff Bus', 'https://www.cardiffbus.com/open-data', 'W', { 'CB': 'CBUS', # 'NB': '', }), ('Yellow Buses', 'https://www.yellowbuses.co.uk/open-data', 'SW', { 'YELL': 'YELL', }), ('Brighton & Hove Buses', 'https://www.buses.co.uk/open-data', 'SE', { 'BH': 'BHBC', }), ('Blackpool Transport', 'https://www.blackpooltransport.com/open-data', 'NW', { 'RR': 'BLAC', }), ('Transdev Blazefield', 'https://www.transdevbus.co.uk/open-data', 'NW', { 'LUI': 'LNUD', 'ROS': 'ROST', 'BPT': 'BPTR', 'KDT': 'KDTR', 'HDT': 'HRGT', 'YCD': 'YCST', 'TPEN': 'TPEN', }), ('Go North East', 'https://www.gonortheast.co.uk/open-data', 'NE', { 'GNE': 'GNEL', }), ('East Yorkshire', 'https://www.eastyorkshirebuses.co.uk/open-data', 'Y', { 'EYMS': 'EYMS', }), ('McGill’s', 'https://data.discoverpassenger.com/operator/mcgills', 'S', { 'MCG': 'MCGL', 'McG': 'MCGL', }), ('Warringtons Own Buses', 'https://www.warringtonsownbuses.co.uk/open-data', 'NW', { 'WOB': 'WBTR', }), ('Newport Bus', 'https://www.newportbus.co.uk/open-data', 'W', { 'NWPT': 'NWPT', }), ] # see bustimes.management.commands.import_bod BOD_OPERATORS = [ ('WMSA', 'EM', {}, False), ('LANT', 'EM', {}, False), ('NWBT', 'NW', {}, False), ('MARS', 'SE', {}, False), ('FBOS', None, { 'FYOR': 'FYOR', # 'FPOT': 'FPOT', # 'FSYO': 'FSYO', # 'FMAN': 'FMAN', # 'FLDS': 'FLDS', # 'FSMR': 'FSMR', 'FHUD': 'FHUD', 'FHAL': 'FHUD', 'FBRA': 'FBRA', # 'FESX': 'FESX', 'FECS': 'FECS', # 'FHDO': 'FHDO', 'FTVA': 'FTVA', # 'FHAM': 'FHAM', # 'FDOR': 'FDOR', 'FCWL': 'FCWL', 'FBRI': 'FBRI', # 'FLEI': 'FLEI', 'RRAR': 'RRAR', 'FBOS': 'FBOS', # 'FWYO': 'FWYO', }, True), # these no longer operate services - this is just to prevent their TNDS data being used: ('PTSG', None, { 'ABUS': 'ABUS', 'PTSG': 'PTSG', }, False), ('TNXB', 'WM', { 'TNXB': 'TNXB', 'TCVW': 'TCVW', }, False), ('UNOE', 'SE', { 'UBN': 'UNOE', 'UNIB': 'UNOE', 'OP': 'UNOE', 'UN': 'UNOE', }, False), ('TBTN', 'EM', { 'BRTB': 'TBTN', }, False), ('KBUS', 'SE', {}, False), ('NIBS', 'SE', {}, False), # ('SESX', 'EA', {}, False), ('STCB', 'EA', {}, False), ('CSVC', 'EA', { 'CS': 'CSVC' }, False), ('HIPK', 'EM', { 'OP': 'HIPK', 'HPB': 'HIPK', }, False), ('HNTS', 'EM', {}, False), # ('SLBS', 'WM', {}, True), ('LODG', 'SE', {}, False), ('FRDS', 'SE', {}, False), ('AVMT', 'SW', {}, False), ('BZCO', 'SW', {}, False), ('C2WI', 'SW', {}, False), ('CNTY', 'SW', {}, False), ('COAC', 'SW', {}, False), ('COTS', 'SW', {}, False), ('CRYC', 'SW', {}, False), ('DTCO', 'SW', {}, False), ('FRMN', 'SW', {}, False), ('FSRV', 'SW', {}, False), ('FTZL', 'SW', {}, False), ('GWIL', 'SW', {}, False), ('HGCO', 'SW', {}, False), ('HOPE', 'SW', {}, False), ('JACK', 'SW', {}, False), ('LTRV', 'SW', {}, False), ('NAKL', 'SW', {}, False), ('OTSS', 'SW', {}, False), ('PULH', 'SW', {}, False), ('RIDL', 'SW', {}, False), ('RSLN', 'SW', {}, False), ('SMST', 'SW', {}, False), ('SWCO', 'SW', {}, False), ('TAWT', 'SW', {}, False), ('TLYH', 'SW', {}, False), ('TOTN', 'SW', {}, False), ('YEOS', 'SW', {}, False), ('SMMC', 'SW', {}, False), ('GYLC', 'SW', {}, False), ('SWAN', 'SW', {}, False), ('CTCO', 'SW', {}, False), ('EBLY', 'SW', {}, False), ('BYCO', 'SW', {}, False), ('NEJH', 'SW', {}, False), ('BNNT', 'SW', {}, False), ('XLBL', 'SW', {}, False), ('NCSL', 'SW', {}, False), ('AMKC', 'SW', {}, False), ('EUTX', 'SW', {}, False), ('ESTW', 'SW', {}, False), ('NABC', 'SW', {}, False), ('QVED', 'SW', {}, False), ('STAC', 'SW', {}, False), ('SWOC', 'SW', {}, False), ('DDLT', 'SW', {}, False), ('CHCB', 'SW', {}, False), ('DJWA', 'SW', {}, False), ('BNSC', 'SW', {}, False), ('MARC', 'SW', {}, False), ('NRTL', 'SW', {}, False), ('PRIC', 'SW', {}, False), ('LIHO', 'SW', {}, False), ('DPCR', 'SW', {}, False), # ('NATX', 'GB', {}, False), ('KETR', 'SE', {}, False), # ('HACO', 'EA', {}, False), # ('PCCO', 'EM', {}, False), ('HCCL', 'NE', { 'HCC': 'WGHC' }, False), ('SPSV', 'SE', {}, False), ('NVTR', 'SE', {}, False), ('LEMN', 'SE', {}, False), ('GOCH', 'SE', { 'GO': 'GOCH' }, False), ('LAKC', 'WM', {}, True), # incomplete ('CBBH', 'EM', { 'CBBH': 'CBBH', 'CBNL': 'CBNL', 'CBL': 'CBNL', }, False), # ('BULL', 'NW', {}, False), ('SELT', 'NW', {}, False), # Selwyns Ticketer ('ROSS', 'Y', {}, False), # Ross Travel Ticketer ('GRYC', 'EM', {}, False), ('CKMR', 'SE', {}, False), # ('A2BR', 'EA', {}, False), ('A2BV', 'NW', {}, False), # ('STNE', 'NE', { # 'STNE': 'STNE', # 'STNT': 'STNT', # }, False), ('LAWS', 'EM', {}, False), ('BMCS', 'SE', {}, False), ('AJCO', 'EA', {}, False), ('LTEA', 'EA', {}, False), ('CPLT', 'EA', {}, False), ('OBUS', 'EA', { 'OURH': 'OURH', 'OBUS': 'OBUS', }, False), ('WNGS', None, { # Rotala Group of Companies 'WINGS': 'WNGS', 'TGM': 'WNGS', # Diamond SE 'NXHH': 'NXHH', # Hotel Hoppa 'DIAM': 'DIAM', # Diamond WM 'GTRI': 'GTRI', # Diamond NW 'PBLT': 'PBLT', # Preston }, False), ('PLNG', 'EA', {}, False), ('SNDR', 'EA', {}, False), ('STOT', 'NW', {}, False), ('CARL', 'SE', {}, False), ('IRVD', 'NW', {}, False), ('FALC', 'SE', {}, False), ('VECT', 'SE', {}, True), ('ACME', 'SE', {}, False), ('Viking Coaches', 'NW', { 'VIKG': 'VIKG' }, False), # Viking (BODS API thinks their operator code is WVIK, but that's a different Viking) ('ALSC', 'NW', {}, False), # Happy Al's ('LCAC', 'NW', {}, False), ('LNNE', 'NW', {}, False), ('RBUS', 'SE', {}, True), # incomplete ('ROOS', 'SW', {}, False), ('SEWR', 'SW', {}, False), ('HRBT', 'SE', {}, False), ('KENS', 'Y', {}, False), ('AWAN', 'SE', {}, False), ('LUCK', 'SW', {}, False), ('GVTR', 'NE', {}, False), ('COTY', 'NE', {}, False), ('LMST', 'WM', {}, False), ('TEXP', 'WM', {}, False), ('BANG', 'WM', {}, False), ('SLVL', 'WM', {}, False), ('JOHS', 'WM', {}, False), ('ENSB', 'SE', {}, True), ('BRYL', 'EM', {}, False), ('MDCL', 'EM', {}, False), ('NDTR', 'EM', {}, False), ('NOCT', 'EM', {}, False), ('RELD', 'Y', {}, False), ('SSSN', 'Y', {}, False), ('KJTR', 'Y', {}, False), ('HCTY', 'Y', { 'HCTY': 'HCTY', # Connexions 'YRRB': 'YRRB', # 'Road Runner' }, False), ('NCTP', None, { 'NCTP': 'NCTP', # CT Plus Bristol (/London) 'POWB': 'POWB', # Powells 'CTPL': 'CTPL', # CT Plus Yorkshire }, False), ('LYNX', 'EA', {}, False), ('IPSW', 'EA', {}, False), ('WNCT', 'EA', {}, False), ('WHIP', 'EA', {}, False), ('SIMO', 'EA', {}, False), ('BEES', 'EA', {}, False), ('GOGO', 'NW', {}, False), ('RBTS', 'EM', {}, False), ('DELA', 'EM', {}, False), ('RLNE', 'SE', {}, False), ('HATT', 'NW', {}, False), ('SULV', 'SE', {}, False), ('WBSV', 'SE', {}, False), ('REDE', 'SE', {}, False), ('GPLM', 'SE', {}, False), ('CLNB', 'SE', {}, False), ('RRTR', 'SE', {}, False), ('RCHC', 'SE', {}, False), ('FCHS', 'NW', {}, False), ('CRSS', 'WM', {}, True), # NN Cresswell ('DAGC', None, { 'DAGC': 'DAGC', 'CRDR': 'CRDR' }, False), # ('Go East Anglia', 'EA', { # 'KCTB': 'KCTB', # 'HEDO': 'HEDO', # 'CHAM': 'CHAM', # }, False), ('DRMC', 'WM', {}, True), ('SARG', 'WM', {}, False), ('AMBS', 'EA', { 'AMBS': 'AMBS', 'SEMM': 'SEMM', }, True), ('RDRT', 'SE', { 'RR': 'RDRT', 'RR1': 'RDRT' }, False), ] # see bustimes.management.commands.import_bod STAGECOACH_OPERATORS = [ ('S', 'sblb', 'Stagecoach Bluebird', ['SBLB']), ('S', 'scfi', 'Stagecoach East Scotland', ['SCFI', 'SCPE', 'SSPH', 'STSY', 'SSTY']), ('S', 'schi', 'Stagecoach Highlands', ['SCHI', 'SCOR', 'SINV']), ('NE', 'scne', 'Stagecoach North East', ['SCNE', 'SCSS', 'SCSU', 'SCTE', 'SCHA']), ('S', 'stws', 'Stagecoach West Scotland', ['STWS', 'SCGS', 'STGS']), ('EM', 'scem', 'Stagecoach East Midlands', ['SCLI', 'SCGH', 'SCGR', 'NFKG']), ('SE', 'scso', 'Stagecoach South', ['SCPY', 'SCHM', 'SCHW', 'SCCO', 'SMSO', 'SCHS', 'SCHN']), ('SE', 'scek', 'Stagecoach South East', ['SCEK', 'SCEB', 'SCHT']), ('Y', 'syrk', 'Stagecoach Yorkshire', ['SYRK', 'YSYC', 'CLTL']), ('NW', 'sccu', 'Stagecoach Cumbria', ['SCCU', 'SCMB', 'SCNW']), ('NW', 'scmn', 'Stagecoach Manchester', ['SCMN', 'SWIG']), ('NW', 'scmy', 'Stagecoach Merseyside', ['SCMY', 'STCR', 'STWR', 'SCLA']), ('SW', 'sdvn', 'Stagecoach South West', ['SDVN', 'SDVN']), ('SE', 'sccm', 'Stagecoach East', ['SCCM', 'SCBD', 'SCPB', 'SCHU']), ('EM', 'scnh', 'Stagecoach Midlands', ['SCNH', 'SCWW']), ('SE', 'scox', 'Stagecoach Oxfordshire', ['SCOX']), ('SW', 'scgl', 'Stagecoach West', ['SCGL', 'SSWN', 'STWD', 'SCCH']), ('W', 'sswl', 'Stagecoach South Wales', ['SSWL']), ('Y', 'tram', 'Stagecoach Supertram', ['SCST']), ] # Some operators' timetables are fetched directly from e.g. # https://opendata.ticketer.com/uk/LYNX/routes_and_timetables/current.zip # rather than via the Bus Open Data site, # because sometimes BODS doesn't detect updates TICKETER_OPERATORS = [ ('EA', ['GOEA', 'KCTB', 'HEDO', 'CHAM'], 'Go East Anglia'), ('EA', ['BDRB'], 'BorderBus'), ('WM', ['DIAM'], 'Diamond Bus'), ('NW', ['GTRI'], 'Diamond Bus North West'), ('NW', ['PBLT'], 'Preston Bus'), ('EA', ['WHIP'], 'Whippet'), ('WM', ['Johnsons', 'JOHS']), ('NE', ['A-Line_Coaches_Tyne_&_Wear', 'ALGC']), ('EA', ['Ipswich_Buses', 'IPSW'], 'Ipswich Buses'), ('EM', ['Notts_and_Derby', 'NDTR'], 'Notts and Derby'), ('Y', ['RELD'], 'Reliance Motor Services'), # ('SW', ['PLYC', 'TFCN'], 'Go South West'), # ('SE', ['METR'], 'Metrobus'), ('SE', ['OXBC', 'CSLB', 'THTR'], 'Oxford Bus Company'), # ('NW', ['GONW'], 'Go North West'), ('W', ['ACYM'], 'Arriva Cymru'), ('NW', ['AMAN', 'ANWE'], 'Arriva North West'), ('NW', ['AMSY'], 'Arriva Merseyside'), ('NE', ['ARDU', 'ANEA'], 'Arriva Durham'), ('NE', ['ANUM'], 'Arriva Northumbria'), ('Y', ['WRAY', 'YTIG'], 'Arriva Yorkshire'), ('WM', ['AMNO'], 'Arriva Midlands North'), ('EM', ['AMID', 'AFCL', 'ADER'], 'Arriva Midlands'), ('SE', ['ARBB', 'ASES', 'GLAR'], 'Arriva Beds & Bucks'), ('SE', ['AMTM', 'ARHE'], 'Arriva Kent Thameside'), ('SE', ['AKSS', 'AMTM'], 'Arriva Kent & Surrey'), ('SE', ['Vectare', 'VECT']), ('EM', ['NOCT'], 'CT4N'), ('WM', ['LMST'], 'LMS Travel'), ('SE', ['ENSB'], 'Ensignbus'), ('EA', ['AMBS'], 'Ambassador Travel'), ('EA', ['WNCT'], 'West Norfolk Community Transport'), ('NW', ['GOGO'], 'Go Goodwins'), ('EM', ['Brylaine', 'BRYL']), ('EM', ['Midland_Classic', 'MDCL']), ('EM', ['RBTS'], 'Roberts Travel'), ('SE', ['Redline_Buses_Ltd', 'RLNE']), ('NW', ['HATT'], 'Hattons'), ('SE', ['Sullivan_Buses', 'SULV']), ('EA', ['Simonds', 'SIMO']), ('NE', ['Coatham_Coaches', 'COTY']), ('Y', ['HCTY'], 'Connexions Buses'), ('Y', ['KJTR'], 'York Pullman'), ('SE', ['WBSV'], 'White Bus'), ('SE', ['REDE'], 'Red Eagle'), ('SE', ['GPLM'], 'Grant Palmer'), ('SE', ['CLNB'], 'Carlone Buses'), ('NW', ['D&G_Bus_Ltd', 'DAGC', 'CRDR']), ('EA', ['Beestons_(Hadleigh)_Ltd', 'BEES']), ('Y', ['Shoreline_Suncruisers', 'SSSN']), ('WM', ['Travel_Express', 'TEXP']), ('WM', ['Banga_Buses', 'BANG']), ('EM', ['DELA'], 'Delaine Buses'), ('SE', ['RCHC'], 'Richmonds Coaches'), ('SE', ['RRTR'], 'Red Rose Travel'), ('NW', ['Finches', 'FCHS']), ('WM', ['Silverline_LandFlight_Limited', 'SLVL']), ('Y', ['POWB', 'CTPL'], 'HCT Group'), ('SW', ['NTCP', 'NCTP'], 'HCT Group'), ]
#!/usr/bin/env python """ Given an API, load all the forms, count up their non-NA values, and mark their missing/complete status. """ import argparse import pandas as pd import pdb import redcap as rc import sys from load_utils import load_form_with_primary_key from qa_utils import chunked_form_export, get_items_matching_regex import sibispy from sibispy import sibislogger as slog from typing import List def parse_args(input_args: List = None) -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="Verbose operation", action="store_true") parser.add_argument("-p", "--post-to-github", help="Post all issues to GitHub instead of stdout.", action="store_true") parser.add_argument("-a", "--all-forms", action='store_true') parser.add_argument("-f", "--forms", nargs='+') parser.add_argument("-e", "--events", nargs='*') parser.add_argument('-o', '--output', help="File to save the inventory to", default=sys.stdout) parser.add_argument('-s', '--api', help="Source Redcap API to use", default="data_entry") parser.add_argument('-d', '--include-dag', help="Include Redcap Data Access Group for each row", dest="include_dag", action="store_true") args = parser.parse_args(input_args) return args def make_redcap_inventory(api: rc.Project, forms: List, events: List = None, post_to_github: bool = False, include_dag: bool = False, verbose: bool = False) -> pd.DataFrame: # Determine scope meta = api.export_metadata(format='df') all_forms = meta['form_name'].unique().tolist() if forms is not None: all_forms = [form for form in all_forms if form in forms] # always load visit_ignore___yes - if whole visit is ignored, then this # form should be, too (very NCANDA-specific) data = {form: chunked_form_export(api, forms=[form], events=events, include_dag=include_dag, fields=['visit_ignore']) for form in all_forms} final_dfs = [] for form in all_forms: try: form_stats = data[form].apply(get_flag_and_meta, axis=1) except ValueError: continue form_stats['form_name'] = form final_dfs.append(form_stats) return pd.concat(final_dfs, sort=False) # Apply to DF to get all empty records def get_flag_and_meta(row: pd.Series, verbose: bool = True) -> pd.Series: try: columns = row.columns.tolist() except Exception as e: # No columns in a Series columns = row.index.tolist() cols_dag = get_items_matching_regex('redcap_data_access_group', columns) cols_complete = get_items_matching_regex("_complete$", columns) cols_ignore = get_items_matching_regex( "^visit_ignore___yes$|_exclude$", columns) cols_missing = get_items_matching_regex( # "^np_reyo_qc___completed$|^bio_mr_same_as_np_day___yes$|_missing$", "^bio_mr_same_as_np___yes$|_missing$", columns) cols_missing_explanation = get_items_matching_regex( "_missing_why(_other)?$", columns) cols_checklists = get_items_matching_regex('___', columns) # Only keep "normal" checklists that aren't a part of any other things cols_checklists_pure = (set(cols_checklists) - set(cols_ignore) - set(cols_complete) - set(cols_missing)) # after a set operation, preserve order: cols_checklists_pure = [c for c in cols_checklists if c in cols_checklists_pure] all_meta_cols = (cols_complete + cols_ignore + cols_missing + cols_dag + cols_missing_explanation + cols_checklists) result = {} if len(cols_dag) > 0: result.update({'dag': row['redcap_data_access_group']}) # NOTE: This will only work for a Series # NOTE: For a full Data Frame, use df.drop(drop_columns, axis=1).notnull().sum(axis=1) non_nan_count = row.drop(all_meta_cols).notnull().sum() result.update({'non_nan_count': non_nan_count}) # Count checklists properly if cols_checklists_pure: col_val1_count = (row[cols_checklists_pure].isin([1, '1'])).sum() result.update({'non_nan_count': non_nan_count + col_val1_count}) # always take last completeness status, on the assumption that that's the true one # (currently not implementing LSSAGA subparts) if len(cols_complete) > 0: result.update({'complete': row[cols_complete[-1]]}) # There *can* be multiple sort-of exclusion/missingness columns (for one, # we're including visit_ignore___yes on all forms, and some have their own # `exclude` switches) - so we'll just assume that wherever there's at least # one 1 flipped for exclusion, the form is excluded. Same with missingness. # # Taking the max of multiple columns is just a quick way to do that. if cols_ignore: result.update({'exclude': row[cols_ignore].max(skipna=True)}) if cols_missing: result.update({'missing': row[cols_missing].max(skipna=True)}) return pd.Series(result) if __name__ == '__main__': args = parse_args() session = sibispy.Session() if not session.configure(): sys.exit() slog.init_log(verbose=args.verbose, post_to_github=args.post_to_github, github_issue_title='QC: Save content stats by form', github_issue_label='inventory', timerDir=None) # Setting specific constants for this run of QC api = session.connect_server(args.api, timeFlag=True) try: if args.all_forms: forms = None else: forms = args.forms inventory = make_redcap_inventory(api=api, forms=forms, events=args.events, post_to_github=args.post_to_github, include_dag=args.include_dag, verbose=args.verbose) inventory.to_csv(args.output, float_format="%.0f") sys.exit(0) except Exception as e: print(e) if args.verbose: print(sys.exc_info()[0]) sys.exit(1) Inventories: Handle Reyo missingness correctly #!/usr/bin/env python """ Given an API, load all the forms, count up their non-NA values, and mark their missing/complete status. """ import argparse import pandas as pd import pdb import redcap as rc import sys from load_utils import load_form_with_primary_key from qa_utils import chunked_form_export, get_items_matching_regex import sibispy from sibispy import sibislogger as slog from typing import List def parse_args(input_args: List = None) -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="Verbose operation", action="store_true") parser.add_argument("-p", "--post-to-github", help="Post all issues to GitHub instead of stdout.", action="store_true") parser.add_argument("-a", "--all-forms", action='store_true') parser.add_argument("-f", "--forms", nargs='+') parser.add_argument("-e", "--events", nargs='*') parser.add_argument('-o', '--output', help="File to save the inventory to", default=sys.stdout) parser.add_argument('-s', '--api', help="Source Redcap API to use", default="data_entry") parser.add_argument('-d', '--include-dag', help="Include Redcap Data Access Group for each row", dest="include_dag", action="store_true") args = parser.parse_args(input_args) return args def make_redcap_inventory(api: rc.Project, forms: List, events: List = None, post_to_github: bool = False, include_dag: bool = False, verbose: bool = False) -> pd.DataFrame: # Determine scope meta = api.export_metadata(format='df') all_forms = meta['form_name'].unique().tolist() if forms is not None: all_forms = [form for form in all_forms if form in forms] # always load visit_ignore___yes - if whole visit is ignored, then this # form should be, too (very NCANDA-specific) data = {form: chunked_form_export(api, forms=[form], events=events, include_dag=include_dag, fields=['visit_ignore']) for form in all_forms} final_dfs = [] for form in all_forms: try: form_stats = data[form].apply(get_flag_and_meta, axis=1) except ValueError: continue form_stats['form_name'] = form final_dfs.append(form_stats) return pd.concat(final_dfs, sort=False) # Apply to DF to get all empty records def get_flag_and_meta(row: pd.Series, verbose: bool = True) -> pd.Series: try: columns = row.columns.tolist() except Exception as e: # No columns in a Series columns = row.index.tolist() cols_dag = get_items_matching_regex('redcap_data_access_group', columns) cols_complete = get_items_matching_regex( "_complete$|^np_reyo_qc___completed$", columns) cols_ignore = get_items_matching_regex( "^visit_ignore___yes$|_exclude$", columns) cols_missing = get_items_matching_regex( # "^np_reyo_qc___completed$|^bio_mr_same_as_np_day___yes$|_missing$", "^bio_mr_same_as_np___yes$|_missing$", columns) cols_missing_explanation = get_items_matching_regex( "_missing_why(_other)?$", columns) cols_checklists = get_items_matching_regex('___', columns) # Only keep "normal" checklists that aren't a part of any other things cols_checklists_pure = (set(cols_checklists) - set(cols_ignore) - set(cols_complete) - set(cols_missing)) # after a set operation, preserve order: cols_checklists_pure = [c for c in cols_checklists if c in cols_checklists_pure] all_meta_cols = (cols_complete + cols_ignore + cols_missing + cols_dag + cols_missing_explanation + cols_checklists) result = {} if len(cols_dag) > 0: result.update({'dag': row['redcap_data_access_group']}) non_nan_count = row.drop(all_meta_cols).notnull().sum() result.update({'non_nan_count': non_nan_count}) # Count checklists properly if cols_checklists_pure: col_val1_count = (row[cols_checklists_pure].isin([1, '1'])).sum() result.update({'non_nan_count': non_nan_count + col_val1_count}) # There *can* be multiple sort-of exclusion/missingness columns (for one, # we're including visit_ignore___yes on all forms, and some have their own # `exclude` switches) - so we'll just assume that wherever there's at least # one 1 flipped for exclusion, the form is excluded. Same with missingness. # # Taking the max of multiple columns is just a quick way to do that. if cols_ignore: result.update({'exclude': row[cols_ignore].max(skipna=True)}) if cols_missing: result.update({'missing': row[cols_missing].max(skipna=True)}) if len(cols_complete) > 0: if 'np_reyo_qc___completed' in cols_complete: # special case: for Reyo QC, the checklist is a completion status, # so we should consider it, but the form should also be marked # Complete result.update({'complete': row[cols_complete].max(skipna=True)}) else: # take the last completion status, on the assumption that it's the # overall completion (currently not implementing LSSAGA subparts) result.update({'complete': row[cols_complete[-1]]}) return pd.Series(result) if __name__ == '__main__': args = parse_args() session = sibispy.Session() if not session.configure(): sys.exit() slog.init_log(verbose=args.verbose, post_to_github=args.post_to_github, github_issue_title='QC: Save content stats by form', github_issue_label='inventory', timerDir=None) # Setting specific constants for this run of QC api = session.connect_server(args.api, timeFlag=True) try: if args.all_forms: forms = None else: forms = args.forms inventory = make_redcap_inventory(api=api, forms=forms, events=args.events, post_to_github=args.post_to_github, include_dag=args.include_dag, verbose=args.verbose) inventory.to_csv(args.output, float_format="%.0f") sys.exit(0) except Exception as e: print(e) if args.verbose: print(sys.exc_info()[0]) sys.exit(1)
# -*- coding: utf-8 -*- """Main Controller @author: moschlar """ # ## SAUCE - System for AUtomated Code Evaluation ## Copyright (C) 2013 Moritz Schlarb ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU Affero General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU Affero General Public License for more details. ## ## You should have received a copy of the GNU Affero General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. # import os import logging from itertools import chain from tg import config, expose, flash, lurl, request, redirect, app_globals as g, abort, tmpl_context as c from tg.decorators import paginate from tg.i18n import ugettext as _ from tgext.admin.controller import AdminController from docutils.core import publish_string from sauce import model from sauce.lib.base import BaseController from sauce.model import DBSession, NewsItem, Event from sauce.config.admin import SAUCEAdminConfig from sauce.controllers.error import ErrorController from sauce.controllers.submissions import SubmissionsController from sauce.controllers.events import EventsController from sauce.controllers.user import UserController from sauce.controllers.language import LanguagesController from sauce.controllers.debug import DebugController if config.features.get('lti', False): from sauce.controllers.lti import LTIController __all__ = ['RootController'] log = logging.getLogger(__name__) class RootController(BaseController): """ The root controller for the SAUCE application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ admin = AdminController(model, DBSession, SAUCEAdminConfig) error = ErrorController() # OUR CONTROLLERS #assignments = AssignmentsController() submissions = SubmissionsController() events = EventsController() #scores = ScoresController() user = UserController() languages = LanguagesController() debug = DebugController() lti = config.features.get('lti', False) and LTIController() or None @expose('sauce.templates.index') def index(self, *args, **kwargs): """Handle the front-page.""" return dict(page='index') @expose('sauce.templates.about') def about(self, *args, **kwargs): c.side_menu = c.doc_menu return dict(page='about') @expose('sauce.templates.page') def docs(self, arg='', *args, **kwargs): page_title = u'SAUCE Documentation' page_header = u'' if arg: try: f = open(os.path.join(g.loc, 'docs', arg + '.rst')) except IOError: abort(404) else: content = publish_string(f.read(), writer_name='html', settings_overrides={'output_encoding': 'unicode'}) page_title += ' - %s' % arg.capitalize() else: page_header = u'SAUCE Documentation' content = u'<p>In the menu on the left, you find all kinds of documentation about <b>SAUCE</b>.</p>' c.side_menu = c.doc_menu return dict(page='docs', page_title=page_title, page_header=page_header, content=content) @expose('sauce.templates.contact') def contact(self, *args, **kwargs): return dict(page='contact') @expose('sauce.templates.news') @paginate('news', max_items_per_page=65535) def news(self, *args, **kwargs): '''NewsItem listing page''' news_query = NewsItem.query.filter(NewsItem.event == None) if ('manage' not in request.permissions and request.user not in (chain(e.teachers for e in Event.query))): news_query = news_query.filter_by(public=True) return dict(page='news', news=news_query) @expose('sauce.templates.login') def login(self, came_from=lurl('/'), *args, **kwargs): """Start the user login.""" if request.environ.get('repoze.who.identity', None): # Already authenticated through external means or by manual URL access # Clear flash message cookie flash.pop_payload() redirect(came_from) login_counter = request.environ.get('repoze.who.logins', 0) if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=unicode(login_counter), came_from=came_from) @expose() def post_login(self, came_from=lurl('/'), *args, **kwargs): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) user = request.user flash(_('Welcome back, %s!') % user.display_name) redirect(came_from) @expose() def post_logout(self, came_from=lurl('/'), *args, **kwargs): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) redirect(came_from) Update root.py https://github.com/TurboGears/tg2/issues/51#issuecomment-39440086 # -*- coding: utf-8 -*- """Main Controller @author: moschlar """ # ## SAUCE - System for AUtomated Code Evaluation ## Copyright (C) 2013 Moritz Schlarb ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU Affero General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU Affero General Public License for more details. ## ## You should have received a copy of the GNU Affero General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. # import os import logging from itertools import chain from tg import config, expose, flash, lurl, request, redirect, app_globals as g, abort, tmpl_context as c from tg.exceptions import HTTPFound from tg.decorators import paginate from tg.i18n import ugettext as _ from tgext.admin.controller import AdminController from docutils.core import publish_string from sauce import model from sauce.lib.base import BaseController from sauce.model import DBSession, NewsItem, Event from sauce.config.admin import SAUCEAdminConfig from sauce.controllers.error import ErrorController from sauce.controllers.submissions import SubmissionsController from sauce.controllers.events import EventsController from sauce.controllers.user import UserController from sauce.controllers.language import LanguagesController from sauce.controllers.debug import DebugController if config.features.get('lti', False): from sauce.controllers.lti import LTIController __all__ = ['RootController'] log = logging.getLogger(__name__) class RootController(BaseController): """ The root controller for the SAUCE application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ admin = AdminController(model, DBSession, SAUCEAdminConfig) error = ErrorController() # OUR CONTROLLERS #assignments = AssignmentsController() submissions = SubmissionsController() events = EventsController() #scores = ScoresController() user = UserController() languages = LanguagesController() debug = DebugController() lti = config.features.get('lti', False) and LTIController() or None @expose('sauce.templates.index') def index(self, *args, **kwargs): """Handle the front-page.""" return dict(page='index') @expose('sauce.templates.about') def about(self, *args, **kwargs): c.side_menu = c.doc_menu return dict(page='about') @expose('sauce.templates.page') def docs(self, arg='', *args, **kwargs): page_title = u'SAUCE Documentation' page_header = u'' if arg: try: f = open(os.path.join(g.loc, 'docs', arg + '.rst')) except IOError: abort(404) else: content = publish_string(f.read(), writer_name='html', settings_overrides={'output_encoding': 'unicode'}) page_title += ' - %s' % arg.capitalize() else: page_header = u'SAUCE Documentation' content = u'<p>In the menu on the left, you find all kinds of documentation about <b>SAUCE</b>.</p>' c.side_menu = c.doc_menu return dict(page='docs', page_title=page_title, page_header=page_header, content=content) @expose('sauce.templates.contact') def contact(self, *args, **kwargs): return dict(page='contact') @expose('sauce.templates.news') @paginate('news', max_items_per_page=65535) def news(self, *args, **kwargs): '''NewsItem listing page''' news_query = NewsItem.query.filter(NewsItem.event == None) if ('manage' not in request.permissions and request.user not in (chain(e.teachers for e in Event.query))): news_query = news_query.filter_by(public=True) return dict(page='news', news=news_query) @expose('sauce.templates.login') def login(self, came_from=lurl('/'), *args, **kwargs): """Start the user login.""" if request.environ.get('repoze.who.identity', None): # Already authenticated through external means or by manual URL access # Clear flash message cookie flash.pop_payload() redirect(came_from) login_counter = request.environ.get('repoze.who.logins', 0) if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=unicode(login_counter), came_from=came_from) @expose() def post_login(self, came_from=lurl('/'), *args, **kwargs): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) user = request.user flash(_('Welcome back, %s!') % user.display_name) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=str(came_from)) @expose() def post_logout(self, came_from=lurl('/'), *args, **kwargs): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=str(came_from))
# coding=utf-8 """View definitions.""" import os import json from datetime import datetime from django.shortcuts import render, get_object_or_404, redirect from django.db.models import Q from django.http import (HttpResponse, JsonResponse, Http404, HttpResponseBadRequest) from django.utils import timezone from django.views.decorators.csrf import csrf_exempt from django.views.generic.detail import DetailView from django.contrib.gis.geos import Polygon from django.contrib.gis.db.models.functions import Distance from django.core.cache import cache from django.core.mail import EmailMessage from departures import live from .utils import format_gbp, viglink, timetable_from_service, get_files_from_zipfile from .models import (Region, StopPoint, AdminArea, Locality, District, Operator, Service, Note, Journey) from .forms import ContactForm DIR = os.path.dirname(__file__) FIRST_OPERATORS = { 'FABD': 'aberdeen', 'FTVA': 'berkshire-thames-valley', 'FBRA': 'bradford', 'FBRI': 'bristol-bath-and-west', 'FCWL': 'cornwall', 'FESX': 'essex', 'FGLA': 'greater-glasgow', 'FMAN': 'greater-manchester', 'FHAL': 'halifax-calder-valley-huddersfield', 'FLDS': 'leeds', 'FLEI': 'leicester', 'FECS': 'norfolk-suffolk', 'FHAM': 'portsmouth-fareham-gosport', 'FPOT': 'potteries', 'FBOS': 'somerset', 'FCYM': 'south-west-wales', 'FSCE': 'south-east-and-central-scotland', 'FSYO': 'south-yorkshire', 'FSOT': 'southampton', 'FDOR': 'wessex-dorset-south-somerset', 'FSMR': 'worcestershire', 'FYOR': 'york' } def index(request): """The home page with a list of regions""" context = { 'regions': Region.objects.filter(service__current=True).distinct().order_by('name') } return render(request, 'index.html', context) def not_found(request, exception): """Custom 404 handler view""" if (request.resolver_match and request.resolver_match.url_name == 'service-detail'): service_code = request.resolver_match.kwargs.get('pk') service = Service.objects.filter(service_code=service_code).defer('geometry').first() localities = Locality.objects.filter(stoppoint__service=service).distinct() context = { 'service': service, 'localities': localities, } else: context = None response = render(request, '404.html', context) response.status_code = 404 return response def offline(request): """Offline page (for service worker)""" return render(request, 'offline.html') def contact(request): """Contact page with form""" submitted = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['message'][:50].splitlines()[0] body = '\n\n'.join(( form.cleaned_data['message'], form.cleaned_data['referrer'], str(request.META.get('HTTP_USER_AGENT')), str(request.META.get('HTTP_X_REAL_IP')) )) message = EmailMessage( subject, body, '"%s" <%s>' % (form.cleaned_data['name'], 'robot@bustimes.org.uk'), ('contact@bustimes.org.uk',), reply_to=(form.cleaned_data['email'],), ) message.send() submitted = True else: referrer = request.META.get('HTTP_REFERER') form = ContactForm(initial={ 'referrer': referrer }) return render(request, 'contact.html', { 'form': form, 'submitted': submitted }) @csrf_exempt def awin_transaction(request): json_string = request.POST.get('AwinTransactionPush') data = json.loads(json_string) message = '\n'.join('%s: %s' % pair for pair in data.items()) EmailMessage( '💷 {} on a {} transaction'.format(format_gbp(data['commission']), format_gbp(data['transactionAmount'])), message, '%s <%s>' % ('🚌⏰🤖', 'robot@bustimes.org.uk'), ('contact@bustimes.org.uk',) ).send() return HttpResponse() def cookies(request): """Cookie policy""" return render(request, 'cookies.html') def data(request): """Data sources""" return render(request, 'data.html') def hugemap(request): """The biggish JavaScript map""" return render(request, 'map.html') def stops(request): """JSON endpoint accessed by the JavaScript map, listing the active StopPoints within a rectangle, in standard GeoJSON format """ try: bounding_box = Polygon.from_bbox( [request.GET[key] for key in ('xmin', 'ymin', 'xmax', 'ymax')] ) except KeyError: return HttpResponseBadRequest() results = StopPoint.objects.filter( latlong__within=bounding_box, active=True ).select_related('locality').annotate( distance=Distance('latlong', bounding_box.centroid) ).order_by('distance').defer('osm', 'locality__latlong') return JsonResponse({ 'type': 'FeatureCollection', 'features': [{ 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': tuple(stop.latlong) }, 'properties': { 'name': stop.get_qualified_name(), 'url': stop.get_absolute_url(), } } for stop in results] }) class UppercasePrimaryKeyMixin(object): """Normalises the primary key argument to uppercase""" def get_object(self, queryset=None): """Given a pk argument like 'ea' or 'sndr', convert it to 'EA' or 'SNDR', then otherwise behaves like ordinary get_object """ primary_key = self.kwargs.get('pk') if primary_key is not None and not primary_key.isupper(): self.kwargs['pk'] = primary_key.upper() return super(UppercasePrimaryKeyMixin, self).get_object(queryset) class RegionDetailView(UppercasePrimaryKeyMixin, DetailView): """A single region and the administrative areas in it""" model = Region def get_context_data(self, **kwargs): context = super(RegionDetailView, self).get_context_data(**kwargs) context['areas'] = AdminArea.objects.filter(region=self.object).exclude(name='').order_by('name') context['operators'] = Operator.objects.filter( region=self.object, service__current=True ).distinct().order_by('name') return context class AdminAreaDetailView(DetailView): """A single administrative area, and the districts, localities (or stops) in it """ model = AdminArea queryset = model.objects.select_related('region') def get_context_data(self, **kwargs): context = super(AdminAreaDetailView, self).get_context_data(**kwargs) # Districts in this administrative area context['districts'] = District.objects.filter( admin_area=self.object, locality__stoppoint__active=True ).distinct().order_by('name') # Districtless localities in this administrative area context['localities'] = Locality.objects.filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True), admin_area_id=self.object.id, district=None, parent=None ).exclude(name='').defer('latlong').distinct().order_by('name') if not (context['localities'] or context['districts']): context['services'] = sorted(Service.objects.filter(stops__admin_area=self.object, current=True).distinct().defer('geometry'), key=Service.get_order) context['modes'] = {service.mode for service in context['services'] if service.mode} context['breadcrumb'] = [self.object.region] return context def render_to_response(self, context): if 'services' not in context and len(context['districts']) + len(context['localities']) == 1: if not context['localities']: return redirect(context['districts'][0]) return redirect(context['localities'][0]) return super(AdminAreaDetailView, self).render_to_response(context) class DistrictDetailView(DetailView): """A single district, and the localities in it""" model = District queryset = model.objects.select_related('admin_area', 'admin_area__region') def get_context_data(self, **kwargs): context = super(DistrictDetailView, self).get_context_data(**kwargs) context['localities'] = Locality.objects.filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True), district=self.object ).defer('latlong').distinct().order_by('name') context['breadcrumb'] = [self.object.admin_area.region, self.object.admin_area] return context def render_to_response(self, context): if len(context['localities']) == 1: return redirect(context['localities'][0]) return super(DistrictDetailView, self).render_to_response(context) class LocalityDetailView(UppercasePrimaryKeyMixin, DetailView): """A single locality, its children (if any), and the stops in it""" model = Locality queryset = model.objects.select_related( 'admin_area', 'admin_area__region', 'district', 'parent' ) def get_context_data(self, **kwargs): context = super(LocalityDetailView, self).get_context_data(**kwargs) context['localities'] = Locality.objects.filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True), parent=self.object, ).defer('latlong').distinct().order_by('name') context['stops'] = StopPoint.objects.filter( locality=self.object, active=True ).defer('osm').order_by('common_name') if not (context['localities'] or context['stops']): raise Http404() elif context['stops']: context['services'] = sorted(Service.objects.filter( stops__locality=self.object, current=True ).defer('geometry').distinct(), key=Service.get_order) context['modes'] = {service.mode for service in context['services'] if service.mode} context['breadcrumb'] = (crumb for crumb in [ self.object.admin_area.region, self.object.admin_area, self.object.district, self.object.parent ] if crumb is not None) return context class StopPointDetailView(UppercasePrimaryKeyMixin, DetailView): """A stop, other stops in the same area, and the services servicing it""" model = StopPoint queryset = model.objects.select_related('admin_area', 'admin_area__region', 'locality', 'locality__parent', 'locality__district').defer('osm') def get_context_data(self, **kwargs): context = super(StopPointDetailView, self).get_context_data(**kwargs) context['services'] = sorted(Service.objects.filter( stops=self.object, current=True ).defer('geometry').distinct(), key=Service.get_order) if not (self.object.active or context['services']): raise Http404() departures = cache.get(self.object.atco_code) if not departures: bot = self.request.META.get('HTTP_X_BOT') departures, max_age = live.get_departures( self.object, context['services'], bot ) if hasattr(departures['departures'], 'get_departures'): departures['departures'] = departures['departures'].get_departures() if not bot: cache.set(self.object.atco_code, departures, max_age) context.update(departures) if context['departures']: context['live'] = any(item.get('live') for item in context['departures']) text = ', '.join(part for part in ( 'on ' + self.object.street if self.object.street else None, 'near ' + self.object.crossing if self.object.crossing else None, 'near ' + self.object.landmark if self.object.landmark else None, ) if part is not None) if text: context['text'] = text[0].upper() + text[1:] context['modes'] = {service.mode for service in context['services'] if service.mode} if self.object.stop_area_id is not None: context['nearby'] = StopPoint.objects.filter(stop_area=self.object.stop_area_id) else: context['nearby'] = StopPoint.objects.filter(common_name=self.object.common_name, locality=self.object.locality, town=self.object.town) context['nearby'] = context['nearby'].filter(active=True).exclude( pk=self.object.pk ).order_by('atco_code').defer('osm') context['breadcrumb'] = (crumb for crumb in ( self.object.admin_area and self.object.admin_area.region, self.object.admin_area, self.object.locality and self.object.locality.district, self.object.locality and self.object.locality.parent, self.object.locality, ) if crumb is not None) return context def stop_json(_, pk): stop = get_object_or_404(StopPoint, atco_code=pk) return JsonResponse({ 'atco_code': stop.atco_code, 'naptan_code': stop.naptan_code, 'common_name': stop.common_name, 'landmark': stop.landmark, 'street': stop.street, 'crossing': stop.crossing, 'indicator': stop.indicator, 'latlong': tuple(stop.latlong), 'stop_area': stop.stop_area_id, 'locality': stop.locality_id, 'suburb': stop.suburb, 'town': stop.town, 'locality_centre': stop.locality_centre, 'live_sources': tuple(stop.live_sources.values_list('name', flat=True)), 'heading': stop.heading, 'bearing': stop.bearing, 'stop_type': stop.stop_type, 'bus_stop_type': stop.bus_stop_type, 'timing_status': stop.timing_status, 'admin_area': stop.admin_area_id, 'active': stop.active, }, safe=False) class OperatorDetailView(UppercasePrimaryKeyMixin, DetailView): "An operator and the services it operates" model = Operator queryset = model.objects.select_related('region') def get_context_data(self, **kwargs): context = super(OperatorDetailView, self).get_context_data(**kwargs) context['notes'] = Note.objects.filter(operators=self.object) context['services'] = sorted(Service.objects.filter(operator=self.object, current=True).defer('geometry'), key=Service.get_order) if not context['services']: raise Http404() context['modes'] = {service.mode for service in context['services'] if service.mode} context['breadcrumb'] = [self.object.region] return context class ServiceDetailView(DetailView): "A service and the stops it stops at" model = Service queryset = model.objects.select_related('region').prefetch_related('operator') def get_context_data(self, **kwargs): context = super(ServiceDetailView, self).get_context_data(**kwargs) if not self.object.current: return context context['operators'] = self.object.operator.all() context['notes'] = Note.objects.filter(Q(operators__in=context['operators']) | Q(services=self.object)) context['links'] = [] if self.object.show_timetable or self.object.region_id in {'NI', 'UL', 'CO', 'LE', 'MU'}: date = self.request.GET.get('date') if date: try: date = datetime.strptime(date, '%Y-%m-%d').date() except ValueError: date = None if not date: next_usage = Journey.objects.filter(service=self.object) next_usage = next_usage.filter(datetime__gte=timezone.now()).order_by('datetime').first() if next_usage: date = next_usage.datetime.date() context['timetables'] = timetable_from_service(self.object, date) if not context.get('timetables'): context['stopusages'] = self.object.stopusage_set.all().select_related( 'stop__locality' ).defer('stop__osm', 'stop__locality__latlong').order_by('direction', 'order') context['has_minor_stops'] = any(s.timing_status == 'OTH' for s in context['stopusages']) else: stops_dict = {stop.pk: stop for stop in self.object.stops.all().select_related( 'locality').defer('osm', 'latlong', 'locality__latlong')} for table in context['timetables']: table.groupings = [grouping for grouping in table.groupings if grouping.rows and grouping.rows[0].times] for grouping in table.groupings: grouping.rows = [row for row in grouping.rows if any(row.times)] for row in grouping.rows: row.part.stop.stop = stops_dict.get(row.part.stop.atco_code) if bool(context['operators']): operator = context['operators'] context['breadcrumb'] = (self.object.region, context['operators'][0]) if self.object.is_megabus(): context['links'].append({ 'url': 'https://www.awin1.com/awclick.php?mid=2678&id=242611&clickref=links&clickref2=' + self.object.pk, 'text': 'Buy tickets from megabus.com' }) else: for operator in context['operators']: if operator.pk in {'NATX', 'NXSH', 'NXAP', 'NXHH'}: context['links'].append({ 'url': viglink('http://www.nationalexpress.com', 'https://bustimes.org.uk/services/' + self.object.pk), 'text': 'Buy tickets from National Express' }) elif operator.url.startswith('http'): context['links'].append({ 'url': operator.url, 'text': '%s website' % operator.name }) else: context['breadcrumb'] = (self.object.region,) traveline_url = self.object.get_traveline_url() if traveline_url: if self.object.net == 'tfl': traveline_text = 'Transport for London' elif self.object.region_id == 'S': traveline_text = 'Traveline Scotland' elif self.object.region_id == 'Y': traveline_text = 'Yorkshire Travel' else: traveline_text = 'Traveline' context['links'].append({ 'url': traveline_url, 'text': 'Timetable on the %s website' % traveline_text }) return context def render_to_response(self, context): if not self.object.current: alternative = Service.objects.filter( description=self.object.description, current=True ).defer('geometry').first() or Service.objects.filter( line_name=self.object.line_name, stopusage__stop_id__in=self.object.stopusage_set.values_list('stop_id', flat=True), current=True ).defer('geometry').first() if alternative is not None: return redirect(alternative) raise Http404() response = super(ServiceDetailView, self).render_to_response(context) response['Link'] = '<https://bustimes.org.uk{}>; rel="canonical"'.format(self.object.get_absolute_url()) return response def service_xml(_, pk): service = get_object_or_404(Service, service_code=pk) bodies = (xml_file.read().decode() for xml_file in get_files_from_zipfile(service)) return HttpResponse(bodies, content_type='text/plain') Let FlixBus/Ouibus and UppercasePrimaryKeyMixin coexist peacefully # coding=utf-8 """View definitions.""" import os import json from datetime import datetime from django.shortcuts import render, get_object_or_404, redirect from django.db.models import Q from django.http import (HttpResponse, JsonResponse, Http404, HttpResponseBadRequest) from django.utils import timezone from django.views.decorators.csrf import csrf_exempt from django.views.generic.detail import DetailView from django.contrib.gis.geos import Polygon from django.contrib.gis.db.models.functions import Distance from django.core.cache import cache from django.core.mail import EmailMessage from departures import live from .utils import format_gbp, viglink, timetable_from_service, get_files_from_zipfile from .models import (Region, StopPoint, AdminArea, Locality, District, Operator, Service, Note, Journey) from .forms import ContactForm DIR = os.path.dirname(__file__) FIRST_OPERATORS = { 'FABD': 'aberdeen', 'FTVA': 'berkshire-thames-valley', 'FBRA': 'bradford', 'FBRI': 'bristol-bath-and-west', 'FCWL': 'cornwall', 'FESX': 'essex', 'FGLA': 'greater-glasgow', 'FMAN': 'greater-manchester', 'FHAL': 'halifax-calder-valley-huddersfield', 'FLDS': 'leeds', 'FLEI': 'leicester', 'FECS': 'norfolk-suffolk', 'FHAM': 'portsmouth-fareham-gosport', 'FPOT': 'potteries', 'FBOS': 'somerset', 'FCYM': 'south-west-wales', 'FSCE': 'south-east-and-central-scotland', 'FSYO': 'south-yorkshire', 'FSOT': 'southampton', 'FDOR': 'wessex-dorset-south-somerset', 'FSMR': 'worcestershire', 'FYOR': 'york' } def index(request): """The home page with a list of regions""" context = { 'regions': Region.objects.filter(service__current=True).distinct().order_by('name') } return render(request, 'index.html', context) def not_found(request, exception): """Custom 404 handler view""" if (request.resolver_match and request.resolver_match.url_name == 'service-detail'): service_code = request.resolver_match.kwargs.get('pk') service = Service.objects.filter(service_code=service_code).defer('geometry').first() localities = Locality.objects.filter(stoppoint__service=service).distinct() context = { 'service': service, 'localities': localities, } else: context = None response = render(request, '404.html', context) response.status_code = 404 return response def offline(request): """Offline page (for service worker)""" return render(request, 'offline.html') def contact(request): """Contact page with form""" submitted = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['message'][:50].splitlines()[0] body = '\n\n'.join(( form.cleaned_data['message'], form.cleaned_data['referrer'], str(request.META.get('HTTP_USER_AGENT')), str(request.META.get('HTTP_X_REAL_IP')) )) message = EmailMessage( subject, body, '"%s" <%s>' % (form.cleaned_data['name'], 'robot@bustimes.org.uk'), ('contact@bustimes.org.uk',), reply_to=(form.cleaned_data['email'],), ) message.send() submitted = True else: referrer = request.META.get('HTTP_REFERER') form = ContactForm(initial={ 'referrer': referrer }) return render(request, 'contact.html', { 'form': form, 'submitted': submitted }) @csrf_exempt def awin_transaction(request): json_string = request.POST.get('AwinTransactionPush') data = json.loads(json_string) message = '\n'.join('%s: %s' % pair for pair in data.items()) EmailMessage( '💷 {} on a {} transaction'.format(format_gbp(data['commission']), format_gbp(data['transactionAmount'])), message, '%s <%s>' % ('🚌⏰🤖', 'robot@bustimes.org.uk'), ('contact@bustimes.org.uk',) ).send() return HttpResponse() def cookies(request): """Cookie policy""" return render(request, 'cookies.html') def data(request): """Data sources""" return render(request, 'data.html') def hugemap(request): """The biggish JavaScript map""" return render(request, 'map.html') def stops(request): """JSON endpoint accessed by the JavaScript map, listing the active StopPoints within a rectangle, in standard GeoJSON format """ try: bounding_box = Polygon.from_bbox( [request.GET[key] for key in ('xmin', 'ymin', 'xmax', 'ymax')] ) except KeyError: return HttpResponseBadRequest() results = StopPoint.objects.filter( latlong__within=bounding_box, active=True ).select_related('locality').annotate( distance=Distance('latlong', bounding_box.centroid) ).order_by('distance').defer('osm', 'locality__latlong') return JsonResponse({ 'type': 'FeatureCollection', 'features': [{ 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': tuple(stop.latlong) }, 'properties': { 'name': stop.get_qualified_name(), 'url': stop.get_absolute_url(), } } for stop in results] }) class UppercasePrimaryKeyMixin(object): """Normalises the primary key argument to uppercase""" def get_object(self, queryset=None): """Given a pk argument like 'ea' or 'sndr', convert it to 'EA' or 'SNDR', then otherwise behaves like ordinary get_object """ primary_key = self.kwargs.get('pk') if primary_key is not None and '-' not in primary_key and not primary_key.isupper(): self.kwargs['pk'] = primary_key.upper() return super(UppercasePrimaryKeyMixin, self).get_object(queryset) class RegionDetailView(UppercasePrimaryKeyMixin, DetailView): """A single region and the administrative areas in it""" model = Region def get_context_data(self, **kwargs): context = super(RegionDetailView, self).get_context_data(**kwargs) context['areas'] = AdminArea.objects.filter(region=self.object).exclude(name='').order_by('name') context['operators'] = Operator.objects.filter( region=self.object, service__current=True ).distinct().order_by('name') return context class AdminAreaDetailView(DetailView): """A single administrative area, and the districts, localities (or stops) in it """ model = AdminArea queryset = model.objects.select_related('region') def get_context_data(self, **kwargs): context = super(AdminAreaDetailView, self).get_context_data(**kwargs) # Districts in this administrative area context['districts'] = District.objects.filter( admin_area=self.object, locality__stoppoint__active=True ).distinct().order_by('name') # Districtless localities in this administrative area context['localities'] = Locality.objects.filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True), admin_area_id=self.object.id, district=None, parent=None ).exclude(name='').defer('latlong').distinct().order_by('name') if not (context['localities'] or context['districts']): context['services'] = sorted(Service.objects.filter(stops__admin_area=self.object, current=True).distinct().defer('geometry'), key=Service.get_order) context['modes'] = {service.mode for service in context['services'] if service.mode} context['breadcrumb'] = [self.object.region] return context def render_to_response(self, context): if 'services' not in context and len(context['districts']) + len(context['localities']) == 1: if not context['localities']: return redirect(context['districts'][0]) return redirect(context['localities'][0]) return super(AdminAreaDetailView, self).render_to_response(context) class DistrictDetailView(DetailView): """A single district, and the localities in it""" model = District queryset = model.objects.select_related('admin_area', 'admin_area__region') def get_context_data(self, **kwargs): context = super(DistrictDetailView, self).get_context_data(**kwargs) context['localities'] = Locality.objects.filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True), district=self.object ).defer('latlong').distinct().order_by('name') context['breadcrumb'] = [self.object.admin_area.region, self.object.admin_area] return context def render_to_response(self, context): if len(context['localities']) == 1: return redirect(context['localities'][0]) return super(DistrictDetailView, self).render_to_response(context) class LocalityDetailView(UppercasePrimaryKeyMixin, DetailView): """A single locality, its children (if any), and the stops in it""" model = Locality queryset = model.objects.select_related( 'admin_area', 'admin_area__region', 'district', 'parent' ) def get_context_data(self, **kwargs): context = super(LocalityDetailView, self).get_context_data(**kwargs) context['localities'] = Locality.objects.filter( Q(stoppoint__active=True) | Q(locality__stoppoint__active=True), parent=self.object, ).defer('latlong').distinct().order_by('name') context['stops'] = StopPoint.objects.filter( locality=self.object, active=True ).defer('osm').order_by('common_name') if not (context['localities'] or context['stops']): raise Http404() elif context['stops']: context['services'] = sorted(Service.objects.filter( stops__locality=self.object, current=True ).defer('geometry').distinct(), key=Service.get_order) context['modes'] = {service.mode for service in context['services'] if service.mode} context['breadcrumb'] = (crumb for crumb in [ self.object.admin_area.region, self.object.admin_area, self.object.district, self.object.parent ] if crumb is not None) return context class StopPointDetailView(UppercasePrimaryKeyMixin, DetailView): """A stop, other stops in the same area, and the services servicing it""" model = StopPoint queryset = model.objects.select_related('admin_area', 'admin_area__region', 'locality', 'locality__parent', 'locality__district').defer('osm') def get_context_data(self, **kwargs): context = super(StopPointDetailView, self).get_context_data(**kwargs) context['services'] = sorted(Service.objects.filter( stops=self.object, current=True ).defer('geometry').distinct(), key=Service.get_order) if not (self.object.active or context['services']): raise Http404() departures = cache.get(self.object.atco_code) if not departures: bot = self.request.META.get('HTTP_X_BOT') departures, max_age = live.get_departures( self.object, context['services'], bot ) if hasattr(departures['departures'], 'get_departures'): departures['departures'] = departures['departures'].get_departures() if not bot: cache.set(self.object.atco_code, departures, max_age) context.update(departures) if context['departures']: context['live'] = any(item.get('live') for item in context['departures']) text = ', '.join(part for part in ( 'on ' + self.object.street if self.object.street else None, 'near ' + self.object.crossing if self.object.crossing else None, 'near ' + self.object.landmark if self.object.landmark else None, ) if part is not None) if text: context['text'] = text[0].upper() + text[1:] context['modes'] = {service.mode for service in context['services'] if service.mode} if self.object.stop_area_id is not None: context['nearby'] = StopPoint.objects.filter(stop_area=self.object.stop_area_id) else: context['nearby'] = StopPoint.objects.filter(common_name=self.object.common_name, locality=self.object.locality, town=self.object.town) context['nearby'] = context['nearby'].filter(active=True).exclude( pk=self.object.pk ).order_by('atco_code').defer('osm') context['breadcrumb'] = (crumb for crumb in ( self.object.admin_area and self.object.admin_area.region, self.object.admin_area, self.object.locality and self.object.locality.district, self.object.locality and self.object.locality.parent, self.object.locality, ) if crumb is not None) return context def stop_json(_, pk): stop = get_object_or_404(StopPoint, atco_code=pk) return JsonResponse({ 'atco_code': stop.atco_code, 'naptan_code': stop.naptan_code, 'common_name': stop.common_name, 'landmark': stop.landmark, 'street': stop.street, 'crossing': stop.crossing, 'indicator': stop.indicator, 'latlong': tuple(stop.latlong), 'stop_area': stop.stop_area_id, 'locality': stop.locality_id, 'suburb': stop.suburb, 'town': stop.town, 'locality_centre': stop.locality_centre, 'live_sources': tuple(stop.live_sources.values_list('name', flat=True)), 'heading': stop.heading, 'bearing': stop.bearing, 'stop_type': stop.stop_type, 'bus_stop_type': stop.bus_stop_type, 'timing_status': stop.timing_status, 'admin_area': stop.admin_area_id, 'active': stop.active, }, safe=False) class OperatorDetailView(UppercasePrimaryKeyMixin, DetailView): "An operator and the services it operates" model = Operator queryset = model.objects.select_related('region') def get_context_data(self, **kwargs): context = super(OperatorDetailView, self).get_context_data(**kwargs) context['notes'] = Note.objects.filter(operators=self.object) context['services'] = sorted(Service.objects.filter(operator=self.object, current=True).defer('geometry'), key=Service.get_order) if not context['services']: raise Http404() context['modes'] = {service.mode for service in context['services'] if service.mode} context['breadcrumb'] = [self.object.region] return context class ServiceDetailView(DetailView): "A service and the stops it stops at" model = Service queryset = model.objects.select_related('region').prefetch_related('operator') def get_context_data(self, **kwargs): context = super(ServiceDetailView, self).get_context_data(**kwargs) if not self.object.current: return context context['operators'] = self.object.operator.all() context['notes'] = Note.objects.filter(Q(operators__in=context['operators']) | Q(services=self.object)) context['links'] = [] if self.object.show_timetable or self.object.region_id in {'NI', 'UL', 'CO', 'LE', 'MU'}: date = self.request.GET.get('date') if date: try: date = datetime.strptime(date, '%Y-%m-%d').date() except ValueError: date = None if not date: next_usage = Journey.objects.filter(service=self.object) next_usage = next_usage.filter(datetime__gte=timezone.now()).order_by('datetime').first() if next_usage: date = next_usage.datetime.date() context['timetables'] = timetable_from_service(self.object, date) if not context.get('timetables'): context['stopusages'] = self.object.stopusage_set.all().select_related( 'stop__locality' ).defer('stop__osm', 'stop__locality__latlong').order_by('direction', 'order') context['has_minor_stops'] = any(s.timing_status == 'OTH' for s in context['stopusages']) else: stops_dict = {stop.pk: stop for stop in self.object.stops.all().select_related( 'locality').defer('osm', 'latlong', 'locality__latlong')} for table in context['timetables']: table.groupings = [grouping for grouping in table.groupings if grouping.rows and grouping.rows[0].times] for grouping in table.groupings: grouping.rows = [row for row in grouping.rows if any(row.times)] for row in grouping.rows: row.part.stop.stop = stops_dict.get(row.part.stop.atco_code) if bool(context['operators']): operator = context['operators'] context['breadcrumb'] = (self.object.region, context['operators'][0]) if self.object.is_megabus(): context['links'].append({ 'url': 'https://www.awin1.com/awclick.php?mid=2678&id=242611&clickref=links&clickref2=' + self.object.pk, 'text': 'Buy tickets from megabus.com' }) else: for operator in context['operators']: if operator.pk in {'NATX', 'NXSH', 'NXAP', 'NXHH'}: context['links'].append({ 'url': viglink('http://www.nationalexpress.com', 'https://bustimes.org.uk/services/' + self.object.pk), 'text': 'Buy tickets from National Express' }) elif operator.url.startswith('http'): context['links'].append({ 'url': operator.url, 'text': '%s website' % operator.name }) else: context['breadcrumb'] = (self.object.region,) traveline_url = self.object.get_traveline_url() if traveline_url: if self.object.net == 'tfl': traveline_text = 'Transport for London' elif self.object.region_id == 'S': traveline_text = 'Traveline Scotland' elif self.object.region_id == 'Y': traveline_text = 'Yorkshire Travel' else: traveline_text = 'Traveline' context['links'].append({ 'url': traveline_url, 'text': 'Timetable on the %s website' % traveline_text }) return context def render_to_response(self, context): if not self.object.current: alternative = Service.objects.filter( description=self.object.description, current=True ).defer('geometry').first() or Service.objects.filter( line_name=self.object.line_name, stopusage__stop_id__in=self.object.stopusage_set.values_list('stop_id', flat=True), current=True ).defer('geometry').first() if alternative is not None: return redirect(alternative) raise Http404() response = super(ServiceDetailView, self).render_to_response(context) response['Link'] = '<https://bustimes.org.uk{}>; rel="canonical"'.format(self.object.get_absolute_url()) return response def service_xml(_, pk): service = get_object_or_404(Service, service_code=pk) bodies = (xml_file.read().decode() for xml_file in get_files_from_zipfile(service)) return HttpResponse(bodies, content_type='text/plain')
BUG: fixed bug related to smooth function call
from __future__ import unicode_literals import logging import rest_framework.status as status from rest_framework.generics import GenericAPIView from rest_framework.parsers import JSONParser from rest_framework.response import Response from job.models import JobType from queue.models import Queue import util.rest as rest_util from util.rest import BadParameter logger = logging.getLogger(__name__) class QueueScaleHelloView(GenericAPIView): """This view is the endpoint for queuing new Scale Hello jobs.""" parser_classes = (JSONParser,) #queryset = Job.objects.all() def post(self, request): """Creates and queues the specified number of Scale Hello jobs :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user """ num = rest_util.parse_int(request, 'num') if num < 1: raise BadParameter('num must be at least 1') # TODO: in the future, send command message to do this asynchronously job_type = JobType.objects.get(name='scale-hello', version='1.0') for _ in xrange(num): Queue.objects.queue_new_job_for_user(job_type, {}) return Response(status=status.HTTP_202_ACCEPTED) Bug fix for new diagnostic view from __future__ import unicode_literals import logging import rest_framework.status as status from rest_framework.generics import GenericAPIView from rest_framework.parsers import JSONParser from rest_framework.response import Response from job.models import JobType from queue.models import Queue from queue.serializers import QueueStatusSerializer import util.rest as rest_util from util.rest import BadParameter logger = logging.getLogger(__name__) class QueueScaleHelloView(GenericAPIView): """This view is the endpoint for queuing new Scale Hello jobs.""" parser_classes = (JSONParser,) queryset = Queue.objects.all() serializer_class = QueueStatusSerializer def post(self, request): """Creates and queues the specified number of Scale Hello jobs :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user """ num = rest_util.parse_int(request, 'num') if num < 1: raise BadParameter('num must be at least 1') # TODO: in the future, send command message to do this asynchronously job_type = JobType.objects.get(name='scale-hello', version='1.0') for _ in xrange(num): Queue.objects.queue_new_job_for_user(job_type, {}) return Response(status=status.HTTP_202_ACCEPTED)
import os import zipfile from django.conf import settings from django.db.models import Prefetch from django.views.generic.detail import DetailView from django.http import FileResponse, Http404, HttpResponse from django.utils import timezone from busstops.models import Service from vehicles.siri_one_shot import siri_one_shot, Poorly from .models import Route, Trip class ServiceDebugView(DetailView): model = Service queryset = model.objects.prefetch_related( Prefetch( 'route_set__trip_set', queryset=Trip.objects.prefetch_related('calendar__calendardate_set').order_by('calendar', 'inbound') ) ) template_name = 'service_debug.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) now = timezone.localtime() context['codes'] = self.object.servicecode_set.all() for code in context['codes']: if code.scheme.endswith(' SIRI'): try: code.siri_one_shot = siri_one_shot(code, now, False) except Poorly: code.siri_one_shot = 'Poorly' context['breadcrumb'] = [self.object] return context def route_xml(request, source, code): route = Route.objects.filter(source=source, code__startswith=code).select_related('source').first() if not route: raise Http404 if 'tnds' in route.source.url: path = os.path.join(settings.TNDS_DIR, f'{route.source}.zip') with zipfile.ZipFile(path) as archive: return FileResponse(archive.open(code), content_type='text/xml') if '/' in code: path = code.split('/')[0] with zipfile.ZipFile(os.path.join(settings.DATA_DIR, path)) as archive: code = code[len(path) + 1:] return FileResponse(archive.open(code), content_type='text/xml') path = os.path.join(settings.DATA_DIR, code) if code.endswith('.zip'): with zipfile.ZipFile(os.path.join(settings.DATA_DIR, path)) as archive: return HttpResponse('\n'.join(archive.namelist()), content_type='text/plain') return FileResponse(open(path, 'rb'), content_type='text/xml') catch SiriSource.DoesNotExist import os import zipfile from django.conf import settings from django.db.models import Prefetch from django.views.generic.detail import DetailView from django.http import FileResponse, Http404, HttpResponse from django.utils import timezone from busstops.models import Service, SIRISource from vehicles.siri_one_shot import siri_one_shot, Poorly from .models import Route, Trip class ServiceDebugView(DetailView): model = Service queryset = model.objects.prefetch_related( Prefetch( 'route_set__trip_set', queryset=Trip.objects.prefetch_related('calendar__calendardate_set').order_by('calendar', 'inbound') ) ) template_name = 'service_debug.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) now = timezone.localtime() context['codes'] = self.object.servicecode_set.all() for code in context['codes']: if code.scheme.endswith(' SIRI'): try: code.siri_one_shot = siri_one_shot(code, now, False) except SIRISource.DoesNotExist: pass except Poorly: code.siri_one_shot = 'Poorly' context['breadcrumb'] = [self.object] return context def route_xml(request, source, code): route = Route.objects.filter(source=source, code__startswith=code).select_related('source').first() if not route: raise Http404 if 'tnds' in route.source.url: path = os.path.join(settings.TNDS_DIR, f'{route.source}.zip') with zipfile.ZipFile(path) as archive: return FileResponse(archive.open(code), content_type='text/xml') if '/' in code: path = code.split('/')[0] with zipfile.ZipFile(os.path.join(settings.DATA_DIR, path)) as archive: code = code[len(path) + 1:] return FileResponse(archive.open(code), content_type='text/xml') path = os.path.join(settings.DATA_DIR, code) if code.endswith('.zip'): with zipfile.ZipFile(os.path.join(settings.DATA_DIR, path)) as archive: return HttpResponse('\n'.join(archive.namelist()), content_type='text/plain') return FileResponse(open(path, 'rb'), content_type='text/xml')
# coding=utf-8 from __future__ import unicode_literals import datetime import traceback import uuid from multiprocessing.pool import Pool from unittest.case import TestCase import six from eventsourcing.contrib.suffixtrees.application import SuffixTreeApplicationWithPythonObjects, \ SuffixTreeApplicationWithCassandra, AbstractSuffixTreeApplication from eventsourcing.contrib.suffixtrees.domain.model.generalizedsuffixtree import GeneralizedSuffixTree, \ SuffixTreeEdge, SuffixTreeNode, STRING_ID_END from eventsourcing.tests.suffix_tree_text import LONG_TEXT, LONG_TEXT_CONT from eventsourcing.tests.test_stored_event_repository_cassandra import CassandraTestCase class GeneralizedSuffixTreeTestCase(TestCase): def setUp(self): super(GeneralizedSuffixTreeTestCase, self).setUp() self.app = SuffixTreeApplicationWithPythonObjects() def tearDown(self): self.app.close() super(GeneralizedSuffixTreeTestCase, self).tearDown() def add_string_to_suffix_tree(self, string, string_id, suffix_tree): print("Adding string to suffix tree: {}".format(repr(string[:100]))) started = datetime.datetime.now() suffix_tree.add_string(string, string_id=string_id) print(" - added string in: {}".format(datetime.datetime.now() - started)) class TestGeneralizedSuffixTreeFast(GeneralizedSuffixTreeTestCase): def test_empty_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('', '1', st) self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) def test_add_prefix_of_previous(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('aba', '1', st) self.add_string_to_suffix_tree('a', '2', st) # Check the string ID is returned. result_ids = self.app.find_string_ids('a', st.id) self.assertEqual(result_ids, {'1', '2'}) def test_given_add_duplicate_when_query_with_suffix_then_results_have_both(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('ab', '1', st) self.add_string_to_suffix_tree('ab', '2', st) # Check the string ID is returned. result_ids = self.app.find_string_ids('b', st.id) self.assertEqual(result_ids, {'1', '2'}) def test_extended_copy_of_previous_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('a', '1', st) self.add_string_to_suffix_tree('ab', '2', st) # Check the common prefix can be found. result_ids = self.app.find_string_ids('a', st.id) self.assertEqual(result_ids, {'1', '2'}) # Check the string ID is returned. result_ids = self.app.find_string_ids('ab', st.id) self.assertEqual(result_ids, {'2'}) def test_trucated_copy_of_previous_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('1a', '2', st) self.add_string_to_suffix_tree('1ab', '1', st) # Check the common prefix can be found. result_ids = self.app.find_string_ids('a', st.id) self.assertEqual(result_ids, {'1', '2'}) # Check the string ID is returned. result_ids = self.app.find_string_ids('ab', st.id) self.assertEqual(result_ids, {'1'}) # Check the string ID is returned. result_ids = self.app.find_string_ids('b', st.id) self.assertEqual(result_ids, {'1'}) def test_extended_copy_of_longer_previous_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('ab', '1', st) self.add_string_to_suffix_tree('abc', '2', st) # Check the common prefix can be found. result_ids = self.app.find_string_ids('a', st.id) self.assertEqual(result_ids, {'1', '2'}) # Check the common prefix can be found. result_ids = self.app.find_string_ids('ab', st.id) self.assertEqual(result_ids, {'1', '2'}) # Check the extention can be found. result_ids = self.app.find_string_ids('c', st.id) self.assertEqual(result_ids, {'2'}) # Check the extended string can be found. result_ids = self.app.find_string_ids('abc', st.id) self.assertEqual(result_ids, {'2'}) def test_non_repeating_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) string_id = '1' string = 'abc' self.add_string_to_suffix_tree(string, string_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings are in the tree. edge, ln = self.app.find_substring_edge('abc', st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string + STRING_ID_END) # self.assertEqual(edge.label, string + string_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string_id) # Check the string ID is returned. result_ids = self.app.find_string_ids(string, st.id) self.assertEqual(result_ids, {string_id}) def test_repeating_string(self): st = self.app.register_new_suffix_tree() self.add_string_to_suffix_tree("aaa", '1', st) edge, ln = self.app.find_substring_edge('a', st.id) # self.assertEqual(edge.label, 'a') edge, ln = self.app.find_substring_edge('aa', st.id) # self.assertEqual(edge.label, 'a') edge, ln = self.app.find_substring_edge('aaa', st.id) # self.assertEqual(edge.label, 'a1' + STRING_ID_END) edge, ln = self.app.find_substring_edge('b', st.id) self.assertEqual(edge, None) self.assertTrue(self.app.has_substring('a', st.id)) self.assertTrue(self.app.has_substring('aa', st.id)) self.assertTrue(self.app.has_substring('aaa', st.id)) self.assertFalse(self.app.has_substring('aaaa', st.id)) self.assertFalse(self.app.has_substring('b', st.id)) # case sensitive by default self.assertFalse(self.app.has_substring('A', st.id)) # Check ID is returned. self.assertEqual(self.app.find_string_ids('a', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('aa', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('aaa', st.id), {'1'}) def test_two_identical_strings(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) string1_id = '1' string1 = 'abc' string2_id = '2' string2 = 'abc' self.add_string_to_suffix_tree(string1, string1_id, st) self.add_string_to_suffix_tree(string2, string2_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings of string1 are in the tree. edge, ln = self.app.find_substring_edge(string1, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string1 + STRING_ID_END) # self.assertEqual(edge.label, string1 + string1_id + STRING_ID_END) # self.assertEqual(edge.label, string1 + string1_id ) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node doesn't have a string ID. # self.assertEqual(node.string_id, None) # Check both IDs are returned. result_ids = self.app.find_string_ids(string1, st.id) self.assertEqual(result_ids, {string1_id, string2_id}, (result_ids)) def test_two_non_repeating_strings(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) string1_id = '1' string1 = 'abc' string2_id = '2' string2 = 'def' self.add_string_to_suffix_tree(string1, string1_id, st) self.add_string_to_suffix_tree(string2, string2_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings of string1 are in the tree. edge, ln = self.app.find_substring_edge(string1, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string1 + STRING_ID_END) # self.assertEqual(edge.label, string1 + string1_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string1_id) # Check the string1 ID is returned. result_ids = self.app.find_string_ids(string1, st.id) self.assertEqual(result_ids, {string1_id}) # Check substrings of string2 are in the tree. edge, ln = self.app.find_substring_edge(string2, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string2 + STRING_ID_END) # self.assertEqual(edge.label, string2 + string2_id+ STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string2_id) # Check the string2 ID is returned. result_ids = self.app.find_string_ids(string2, st.id) self.assertEqual(result_ids, {string2_id}) def test_common_prefix_two_non_repeating_strings_with(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) common_prefix = 'z' string1_id = '1' string1 = common_prefix + 'abc' string2_id = '2' string2 = common_prefix + 'def' self.add_string_to_suffix_tree(string1, string1_id, st) self.add_string_to_suffix_tree(string2, string2_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings of string1 are in the tree. edge, ln = self.app.find_substring_edge(string1, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string1[1:] + STRING_ID_END) # self.assertEqual(edge.label, string1[1:] + string1_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string1_id) # Check the string1 ID is returned. result_ids = self.app.find_string_ids(string1, st.id) self.assertEqual(result_ids, {string1_id}) # Check substrings of string2 are in the tree. edge, ln = self.app.find_substring_edge(string2, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string2[1:] + STRING_ID_END) # self.assertEqual(edge.label, string2[1:] + string2_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string2_id) # Check the string2 ID is returned. result_ids = self.app.find_string_ids(string2, st.id) self.assertEqual(result_ids, {string2_id}) # Check common prefix is in the tree. edge, ln = self.app.find_substring_edge(common_prefix, st.id) assert isinstance(edge, SuffixTreeEdge) self.assertEqual(edge.label, common_prefix) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, None) # Check both IDs are returned. result_ids = self.app.find_string_ids(common_prefix, st.id) self.assertEqual(result_ids, {string1_id, string2_id}) def test_common_suffix_two_non_repeating_strings_with(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) common_suffix = 'z' string1_id = '1' string1 = 'abc' + common_suffix string2_id = '2' string2 = 'def' + common_suffix self.add_string_to_suffix_tree(string1, string1_id, st) self.add_string_to_suffix_tree(string2, string2_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings of string1 are in the tree. edge, ln = self.app.find_substring_edge(string1, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string1 + STRING_ID_END) # self.assertEqual(edge.label, string1 + string1_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string1_id) # Check the string1 ID is returned. result_ids = self.app.find_string_ids(string1, st.id) self.assertEqual(result_ids, {string1_id}) # Check substrings of string2 are in the tree. edge, ln = self.app.find_substring_edge(string2, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string2 + STRING_ID_END) # self.assertEqual(edge.label, string2 + string2_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string2_id) # Check the string2 ID is returned. result_ids = self.app.find_string_ids(string2, st.id) self.assertEqual(result_ids, {string2_id}) # Check common suffix is in the tree. edge, ln = self.app.find_substring_edge(common_suffix, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, common_suffix + STRING_ID_END) # self.assertEqual(edge.label, common_suffix) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node doesn't have a string ID. # self.assertEqual(node.string_id, None) # Check both IDs are returned. result_ids = self.app.find_string_ids(common_suffix, st.id) self.assertEqual(result_ids, {string1_id, string2_id}) def test_mississippi(self): st = self.app.register_new_suffix_tree() self.add_string_to_suffix_tree("mississippi", "$", st) self.add_string_to_suffix_tree("mudpie", "#", st) self.add_string_to_suffix_tree("ball", "%", st) self.add_string_to_suffix_tree("ball", "&", st) # # Check there isn't an 'a'. self.assertEqual(self.app.find_substring_edge('j', st.id), (None, None)) # Check 'm'. edge, ln = self.app.find_substring_edge('m', st.id) # self.assertEqual(edge.label, 'm') self.assertEqual(self.app.find_string_ids('m', st.id), {'$', '#'}) # Check 'mi'. edge, ln = self.app.find_substring_edge('mi', st.id) # self.assertEqual(edge.label, 'ississippi' + STRING_ID_END) self.assertEqual(self.app.find_string_ids('mi', st.id), {'$'}) # Check 'mu'. edge, ln = self.app.find_substring_edge('mu', st.id) # self.assertEqual(edge.label, 'udpie' + STRING_ID_END) self.assertEqual(self.app.find_string_ids('mu', st.id), {'#'}) # Check 'missi'. edge, ln = self.app.find_substring_edge('missi', st.id) self.assertEqual(edge.label, 'ississippi$' + STRING_ID_END) # Check 'issi'. edge, ln = self.app.find_substring_edge('issi', st.id) self.assertEqual(edge.label, 'ssi') # Check 'is'. edge, ln = self.app.find_substring_edge('is', st.id) self.assertEqual(edge.label, 'ssi') # Check 'si'. edge, ln = self.app.find_substring_edge('si', st.id) self.assertEqual(edge.label, 'i') # Check 'issip'. edge, ln = self.app.find_substring_edge('issip', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'ssip'. edge, ln = self.app.find_substring_edge('ssip', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'sip'. edge, ln = self.app.find_substring_edge('sip', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'ip'. edge, ln = self.app.find_substring_edge('ip', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'i'. edge, ln = self.app.find_substring_edge('i', st.id) self.assertEqual(edge.label, 'i') # Check 'ippi'. edge, ln = self.app.find_substring_edge('ippi$', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'mudpie'. edge, ln = self.app.find_substring_edge('mudpie', st.id) self.assertEqual(edge.label, 'udpie#' + STRING_ID_END) # Check 'ball'. edge, ln = self.app.find_substring_edge('ball', st.id) self.assertEqual(edge.label, 'ball') # Check ID is returned. self.assertEqual(self.app.find_string_ids('mi', st.id), {'$'}) self.assertEqual(self.app.find_string_ids('si', st.id), {'$'}) self.assertEqual(self.app.find_string_ids('pp', st.id), {'$'}) self.assertEqual(self.app.find_string_ids('mu', st.id), {'#'}) self.assertEqual(self.app.find_string_ids('m', st.id), {'$','#'}) self.assertEqual(self.app.find_string_ids('b', st.id), {'%','&'}) def test_colours(self): st = self.app.register_new_suffix_tree() self.add_string_to_suffix_tree("blue", "$", st) self.add_string_to_suffix_tree("red", "#", st) # Check 'b'. edge, ln = self.app.find_substring_edge('b', st.id) self.assertEqual(edge.label, 'blue$' + STRING_ID_END) # Check 'l'. edge, ln = self.app.find_substring_edge('l', st.id) self.assertEqual(edge.label, 'lue$' + STRING_ID_END) # Check 'u'. edge, ln = self.app.find_substring_edge('u', st.id) self.assertEqual(edge.label, 'ue$' + STRING_ID_END) # Check 'e'. edge, ln = self.app.find_substring_edge('e', st.id) self.assertEqual(edge.label, 'e') # Check 'ue'. edge, ln = self.app.find_substring_edge('ue', st.id) self.assertEqual(edge.label, 'ue$' + STRING_ID_END) # Check 'lue'. edge, ln = self.app.find_substring_edge('lue', st.id) self.assertEqual(edge.label, 'lue$' + STRING_ID_END) # Check 'blue'. edge, ln = self.app.find_substring_edge('blue', st.id) self.assertEqual(edge.label, 'blue$' + STRING_ID_END) # Check 're'. edge, ln = self.app.find_substring_edge('re', st.id) self.assertEqual(edge.label, 'red#' + STRING_ID_END) # Check 'ed'. edge, ln = self.app.find_substring_edge('ed', st.id) self.assertEqual(edge.label, 'd#' + STRING_ID_END) # Check 'red'. edge, ln = self.app.find_substring_edge('red', st.id) self.assertEqual(edge.label, 'red#' + STRING_ID_END) def test_find_string_ids(self): # This test is the first to involve the children of nodes. st = self.app.register_new_suffix_tree() string1_id = uuid.uuid4().hex string2_id = uuid.uuid4().hex string3_id = uuid.uuid4().hex # string4_id = uuid.uuid4().hex self.add_string_to_suffix_tree("blue", string1_id, st) self.add_string_to_suffix_tree("red", string2_id, st) self.add_string_to_suffix_tree("blues", string3_id, st) strings = self.app.find_string_ids('$', st.id) assert not strings, strings strings = self.app.find_string_ids('0', st.id) assert not strings, strings strings = self.app.find_string_ids('1', st.id) assert not strings, strings strings = self.app.find_string_ids('2', st.id) assert not strings, strings strings = self.app.find_string_ids('3', st.id) assert not strings, strings strings = self.app.find_string_ids('4', st.id) assert not strings, strings strings = self.app.find_string_ids('5', st.id) assert not strings, strings strings = self.app.find_string_ids('6', st.id) assert not strings, strings strings = self.app.find_string_ids('7', st.id) assert not strings, strings # Find 'b'. strings = self.app.find_string_ids('b', st.id) self.assertIn(string1_id, strings) self.assertNotIn(string2_id, strings) # Find 'e'. strings = self.app.find_string_ids('e', st.id) self.assertEqual(len(strings), 3) self.assertIn(string1_id, strings, (string1_id, string2_id, string3_id, strings)) self.assertIn(string2_id, strings, (string1_id, string2_id, string3_id, strings)) self.assertIn(string3_id, strings, (string1_id, string2_id, string3_id, strings)) # Find 'e' - limit 1. strings = self.app.find_string_ids('e', st.id, limit=1) self.assertEqual(len(strings), 1) # Find 'e' - limit 2. strings = self.app.find_string_ids('e', st.id, limit=2) self.assertEqual(len(strings), 2) # Find 'r'. strings = self.app.find_string_ids('r', st.id) self.assertNotIn(string1_id, strings) self.assertIn(string2_id, strings) # Find 'd'. strings = self.app.find_string_ids('d', st.id) self.assertNotIn(string1_id, strings) self.assertIn(string2_id, strings) # Find 's'. strings = self.app.find_string_ids('s', st.id) self.assertNotIn(string1_id, strings) self.assertNotIn(string2_id, strings) self.assertIn(string3_id, strings) def test_add_string_to_suffixtree_from_repo(self): # Check adding strings after getting the tree from the repo. st = self.app.register_new_suffix_tree() st = self.app.get_suffix_tree(st.id) self.add_string_to_suffix_tree('blue', '1', st) st = self.app.get_suffix_tree(st.id) self.add_string_to_suffix_tree('green', '2', st) st = self.app.get_suffix_tree(st.id) self.add_string_to_suffix_tree('yellow', '3', st) st = self.app.get_suffix_tree(st.id) strings_ids = self.app.find_string_ids('e', st.id) self.assertEqual(3, len(strings_ids), strings_ids) self.assertEqual(['1', '2', '3'], sorted(strings_ids)) def test_remove_string_from_suffixtree(self): st = self.app.register_new_suffix_tree() # Add 'blue' and 'green'. self.add_string_to_suffix_tree('blue', '1', st) self.add_string_to_suffix_tree('green', '2', st) strings_ids = self.app.find_string_ids('b', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('l', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('u', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('r', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('g', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('e', st.id) self.assertEqual(2, len(strings_ids)) # Remove 'blue'. st.remove_string('blue', '1') strings_ids = self.app.find_string_ids('b', st.id) self.assertEqual(0, len(strings_ids)) strings_ids = self.app.find_string_ids('l', st.id) self.assertEqual(0, len(strings_ids)) strings_ids = self.app.find_string_ids('u', st.id) self.assertEqual(0, len(strings_ids)) strings_ids = self.app.find_string_ids('r', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('g', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('e', st.id) self.assertEqual(1, len(strings_ids), strings_ids) # Add 'blue' again. self.add_string_to_suffix_tree('blue', '1', st) strings_ids = self.app.find_string_ids('b', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('l', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('u', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('r', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('g', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('e', st.id) self.assertEqual(2, len(strings_ids)) class TestGeneralizedSuffixTreeSlow(GeneralizedSuffixTreeTestCase): def test_long_string(self): st = self.app.register_new_suffix_tree() self.add_string_to_suffix_tree(LONG_TEXT[:12000], '1', st) self.assertEqual(self.app.find_string_ids('Ukkonen', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('Optimal', st.id), {'1'}) self.assertFalse(self.app.find_string_ids('ukkonen', st.id)) self.add_string_to_suffix_tree(LONG_TEXT_CONT[:1000], '2', st) self.assertEqual(self.app.find_string_ids('Burrows-Wheeler', st.id), {'2'}) self.assertEqual(self.app.find_string_ids('suffix', st.id), {'1', '2'}) def ___test_split_long_string(self): # Split the long string into separate strings, and make some IDs. list_of_strings = [w for w in LONG_TEXT[:1000].split(' ') if w] print("Long string split into words: {}".format(list_of_strings)) string_ids = {} for string in list_of_strings: string_id = uuid.uuid4().hex string_ids[string_id] = string # Build the suffix tree. st = self.app.register_new_suffix_tree() for string_id, string in string_ids.items(): self.add_string_to_suffix_tree(string, string_id, st) # Check the suffix tree. for string_id, string in string_ids.items(): self.assertIn(string_id, self.app.find_string_ids(string, st.id), (string, string_id)) # Build the suffix tree. # - this time, get the suffix tree afresh from the repo each time st = self.app.register_new_suffix_tree() for string_id, string in string_ids.items(): st = self.app.get_suffix_tree(st.id) self.add_string_to_suffix_tree(string, string_id, st) # Check the suffix tree. for string_id, string in string_ids.items(): self.assertIn(string_id, self.app.find_string_ids(string, st.id)) def test_case_insensitivity(self): st = self.app.register_new_suffix_tree(case_insensitive=True) self.add_string_to_suffix_tree(LONG_TEXT[:12000], '1', st) self.assertEqual(self.app.find_string_ids('ukkonen', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('Optimal', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('burrows-wheeler', st.id), set()) self.add_string_to_suffix_tree(LONG_TEXT_CONT[:1000], '2', st) self.assertEqual(self.app.find_string_ids('ukkonen', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('Optimal', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('burrows-wheeler', st.id), {'2'}) class TestMultiprocessingWithGeneralizedSuffixTree(CassandraTestCase): def setUp(self): super(TestMultiprocessingWithGeneralizedSuffixTree, self).setUp() self.app = None def tearDown(self): super(TestMultiprocessingWithGeneralizedSuffixTree, self).tearDown() if self.app is not None: self.app.close() # Todo: Fix this - adding strings in a random order sometimes breaks (perhaps a dict is causing indeterminate order). # def test_words(self): # self.check_words() def ___test_sorted_words(self): self.check_words(is_sorted=True) # Todo: Fix this - adding strings in a reversed sorted order always fails. Not sure why all substrings of 'ree' fail. The suffix is obviously not moving along in the same way as it does when the nodes are added. Perhaps it needs to add the IDs when explicit match is made, and then move the first char along by one? Not sure so trace it out? # # # Check for errors. # > self.assertFalse(errors, "\n".join(errors)) # E AssertionError: ["Not found: substring ''e'' from string ''tree''", "Not found: substring ''e'' from string ''tree''", "Not found: substring ''ee'' from string ''tree''", "Not found: substring ''r'' from string ''tree''", "Not found: substring ''re'' from string ''tree''", "Not found: substring ''ree'' from string ''tree''"] is not false : Not found: substring ''e'' from string ''tree'' # E Not found: substring ''e'' from string ''tree'' # E Not found: substring ''ee'' from string ''tree'' # E Not found: substring ''r'' from string ''tree'' # E Not found: substring ''re'' from string ''tree'' # E Not found: substring ''ree'' from string ''tree'' # def test_reversed_words(self): # self.check_words(is_reversed=True) def check_words(self, is_sorted=False, is_reversed=False): # Split the long string into separate strings, and make some IDs. words = list([w for w in LONG_TEXT[:100].split(' ') if w]) print("Adding words: {}".format(words)) # Avoid adding the same string twice (or a prefix of a previous string). # - because it's a current problem unless we append string IDs, which makes things too slow # words = set(words) # words = [w for w in words if 0 != sum([x.startswith(w) for x in words if x != w])] assert words # Make a string ID for each string. strings = {} for string in words: string_id = uuid.uuid4().hex strings[string_id] = string # Create a new suffix tree. self.app = SuffixTreeApplicationWithCassandra() st = self.app.register_new_suffix_tree() assert st.id in self.app.suffix_tree_repo # Close the app, so the pool doesn't inherit it. self.app.close() # Start the pool. pool = Pool(initializer=pool_initializer, processes=1) words = [[s, sid, st.id] for sid, s in strings.items() if s] if is_sorted: words = sorted(words) if is_reversed: words = reversed(words) results = pool.map(add_string_to_suffix_tree, words) for result in results: if isinstance(result, Exception): print(result.args[0][1]) raise result # Creat the app again. self.app = SuffixTreeApplicationWithCassandra() errors = [] # Check the suffix tree returns string ID for all substrings of string. for string_id, string in strings.items(): # Check all prefixes and suffixes. substrings = sorted(list(get_all_substrings(string))) print("") print("Checking for all substrings of string '{}': {}".format(repr(string), " ".join([repr(s) for s in substrings]))) for substring in substrings: results = self.app.find_string_ids(substring, st.id) if string_id not in results: msg = "Not found: substring '{}' from string '{}'".format(repr(substring), repr(string)) print(msg) errors.append(msg) # Check for errors. self.assertFalse(errors, "\n".join(errors)) def get_all_substrings(s): length = len(s) return (s[i:j] for i in six.moves.xrange(length) for j in six.moves.xrange(i + 1, length + 1)) worker_app = None def pool_initializer(): global worker_app worker_app = SuffixTreeApplicationWithCassandra() def add_string_to_suffix_tree(args): # random.seed() string, string_id, suffix_tree_id = args print("") print("Adding string to suffix tree: {}: {}".format(string_id, repr(string[:100]))) try: assert isinstance(worker_app, AbstractSuffixTreeApplication) suffix_tree = worker_app.get_suffix_tree(suffix_tree_id) assert isinstance(suffix_tree, GeneralizedSuffixTree) started = datetime.datetime.now() suffix_tree.add_string(string, string_id) print(" - added string in: {}".format(datetime.datetime.now() - started)) except Exception as e: msg = traceback.format_exc() print(" - failed to add string: {}".format(msg)) return Exception((e, msg, string, string_id)) return string_id if __name__ == "__main__": pass Removed unnecessary "if __name__ == '__main__'" block. # coding=utf-8 from __future__ import unicode_literals import datetime import traceback import uuid from multiprocessing.pool import Pool from unittest.case import TestCase import six from eventsourcing.contrib.suffixtrees.application import SuffixTreeApplicationWithPythonObjects, \ SuffixTreeApplicationWithCassandra, AbstractSuffixTreeApplication from eventsourcing.contrib.suffixtrees.domain.model.generalizedsuffixtree import GeneralizedSuffixTree, \ SuffixTreeEdge, SuffixTreeNode, STRING_ID_END from eventsourcing.tests.suffix_tree_text import LONG_TEXT, LONG_TEXT_CONT from eventsourcing.tests.test_stored_event_repository_cassandra import CassandraTestCase class GeneralizedSuffixTreeTestCase(TestCase): def setUp(self): super(GeneralizedSuffixTreeTestCase, self).setUp() self.app = SuffixTreeApplicationWithPythonObjects() def tearDown(self): self.app.close() super(GeneralizedSuffixTreeTestCase, self).tearDown() def add_string_to_suffix_tree(self, string, string_id, suffix_tree): print("Adding string to suffix tree: {}".format(repr(string[:100]))) started = datetime.datetime.now() suffix_tree.add_string(string, string_id=string_id) print(" - added string in: {}".format(datetime.datetime.now() - started)) class TestGeneralizedSuffixTreeFast(GeneralizedSuffixTreeTestCase): def test_empty_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('', '1', st) self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) def test_add_prefix_of_previous(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('aba', '1', st) self.add_string_to_suffix_tree('a', '2', st) # Check the string ID is returned. result_ids = self.app.find_string_ids('a', st.id) self.assertEqual(result_ids, {'1', '2'}) def test_given_add_duplicate_when_query_with_suffix_then_results_have_both(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('ab', '1', st) self.add_string_to_suffix_tree('ab', '2', st) # Check the string ID is returned. result_ids = self.app.find_string_ids('b', st.id) self.assertEqual(result_ids, {'1', '2'}) def test_extended_copy_of_previous_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('a', '1', st) self.add_string_to_suffix_tree('ab', '2', st) # Check the common prefix can be found. result_ids = self.app.find_string_ids('a', st.id) self.assertEqual(result_ids, {'1', '2'}) # Check the string ID is returned. result_ids = self.app.find_string_ids('ab', st.id) self.assertEqual(result_ids, {'2'}) def test_trucated_copy_of_previous_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('1a', '2', st) self.add_string_to_suffix_tree('1ab', '1', st) # Check the common prefix can be found. result_ids = self.app.find_string_ids('a', st.id) self.assertEqual(result_ids, {'1', '2'}) # Check the string ID is returned. result_ids = self.app.find_string_ids('ab', st.id) self.assertEqual(result_ids, {'1'}) # Check the string ID is returned. result_ids = self.app.find_string_ids('b', st.id) self.assertEqual(result_ids, {'1'}) def test_extended_copy_of_longer_previous_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) self.add_string_to_suffix_tree('ab', '1', st) self.add_string_to_suffix_tree('abc', '2', st) # Check the common prefix can be found. result_ids = self.app.find_string_ids('a', st.id) self.assertEqual(result_ids, {'1', '2'}) # Check the common prefix can be found. result_ids = self.app.find_string_ids('ab', st.id) self.assertEqual(result_ids, {'1', '2'}) # Check the extention can be found. result_ids = self.app.find_string_ids('c', st.id) self.assertEqual(result_ids, {'2'}) # Check the extended string can be found. result_ids = self.app.find_string_ids('abc', st.id) self.assertEqual(result_ids, {'2'}) def test_non_repeating_string(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) string_id = '1' string = 'abc' self.add_string_to_suffix_tree(string, string_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings are in the tree. edge, ln = self.app.find_substring_edge('abc', st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string + STRING_ID_END) # self.assertEqual(edge.label, string + string_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string_id) # Check the string ID is returned. result_ids = self.app.find_string_ids(string, st.id) self.assertEqual(result_ids, {string_id}) def test_repeating_string(self): st = self.app.register_new_suffix_tree() self.add_string_to_suffix_tree("aaa", '1', st) edge, ln = self.app.find_substring_edge('a', st.id) # self.assertEqual(edge.label, 'a') edge, ln = self.app.find_substring_edge('aa', st.id) # self.assertEqual(edge.label, 'a') edge, ln = self.app.find_substring_edge('aaa', st.id) # self.assertEqual(edge.label, 'a1' + STRING_ID_END) edge, ln = self.app.find_substring_edge('b', st.id) self.assertEqual(edge, None) self.assertTrue(self.app.has_substring('a', st.id)) self.assertTrue(self.app.has_substring('aa', st.id)) self.assertTrue(self.app.has_substring('aaa', st.id)) self.assertFalse(self.app.has_substring('aaaa', st.id)) self.assertFalse(self.app.has_substring('b', st.id)) # case sensitive by default self.assertFalse(self.app.has_substring('A', st.id)) # Check ID is returned. self.assertEqual(self.app.find_string_ids('a', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('aa', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('aaa', st.id), {'1'}) def test_two_identical_strings(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) string1_id = '1' string1 = 'abc' string2_id = '2' string2 = 'abc' self.add_string_to_suffix_tree(string1, string1_id, st) self.add_string_to_suffix_tree(string2, string2_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings of string1 are in the tree. edge, ln = self.app.find_substring_edge(string1, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string1 + STRING_ID_END) # self.assertEqual(edge.label, string1 + string1_id + STRING_ID_END) # self.assertEqual(edge.label, string1 + string1_id ) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node doesn't have a string ID. # self.assertEqual(node.string_id, None) # Check both IDs are returned. result_ids = self.app.find_string_ids(string1, st.id) self.assertEqual(result_ids, {string1_id, string2_id}, (result_ids)) def test_two_non_repeating_strings(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) string1_id = '1' string1 = 'abc' string2_id = '2' string2 = 'def' self.add_string_to_suffix_tree(string1, string1_id, st) self.add_string_to_suffix_tree(string2, string2_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings of string1 are in the tree. edge, ln = self.app.find_substring_edge(string1, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string1 + STRING_ID_END) # self.assertEqual(edge.label, string1 + string1_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string1_id) # Check the string1 ID is returned. result_ids = self.app.find_string_ids(string1, st.id) self.assertEqual(result_ids, {string1_id}) # Check substrings of string2 are in the tree. edge, ln = self.app.find_substring_edge(string2, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string2 + STRING_ID_END) # self.assertEqual(edge.label, string2 + string2_id+ STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string2_id) # Check the string2 ID is returned. result_ids = self.app.find_string_ids(string2, st.id) self.assertEqual(result_ids, {string2_id}) def test_common_prefix_two_non_repeating_strings_with(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) common_prefix = 'z' string1_id = '1' string1 = common_prefix + 'abc' string2_id = '2' string2 = common_prefix + 'def' self.add_string_to_suffix_tree(string1, string1_id, st) self.add_string_to_suffix_tree(string2, string2_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings of string1 are in the tree. edge, ln = self.app.find_substring_edge(string1, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string1[1:] + STRING_ID_END) # self.assertEqual(edge.label, string1[1:] + string1_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string1_id) # Check the string1 ID is returned. result_ids = self.app.find_string_ids(string1, st.id) self.assertEqual(result_ids, {string1_id}) # Check substrings of string2 are in the tree. edge, ln = self.app.find_substring_edge(string2, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string2[1:] + STRING_ID_END) # self.assertEqual(edge.label, string2[1:] + string2_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string2_id) # Check the string2 ID is returned. result_ids = self.app.find_string_ids(string2, st.id) self.assertEqual(result_ids, {string2_id}) # Check common prefix is in the tree. edge, ln = self.app.find_substring_edge(common_prefix, st.id) assert isinstance(edge, SuffixTreeEdge) self.assertEqual(edge.label, common_prefix) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, None) # Check both IDs are returned. result_ids = self.app.find_string_ids(common_prefix, st.id) self.assertEqual(result_ids, {string1_id, string2_id}) def test_common_suffix_two_non_repeating_strings_with(self): st = self.app.register_new_suffix_tree() assert isinstance(st, GeneralizedSuffixTree) common_suffix = 'z' string1_id = '1' string1 = 'abc' + common_suffix string2_id = '2' string2 = 'def' + common_suffix self.add_string_to_suffix_tree(string1, string1_id, st) self.add_string_to_suffix_tree(string2, string2_id, st) # Check various non-substrings aren't in the tree. self.assertEqual(self.app.find_substring_edge('not there', st.id), (None, None)) self.assertEqual(self.app.find_substring_edge('', st.id), (None, None)) self.assertFalse(self.app.has_substring('not there', st.id)) self.assertFalse(self.app.has_substring('', st.id)) # Check substrings of string1 are in the tree. edge, ln = self.app.find_substring_edge(string1, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string1 + STRING_ID_END) # self.assertEqual(edge.label, string1 + string1_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string1_id) # Check the string1 ID is returned. result_ids = self.app.find_string_ids(string1, st.id) self.assertEqual(result_ids, {string1_id}) # Check substrings of string2 are in the tree. edge, ln = self.app.find_substring_edge(string2, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, string2 + STRING_ID_END) # self.assertEqual(edge.label, string2 + string2_id + STRING_ID_END) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node has a string ID. self.assertEqual(node.string_id, string2_id) # Check the string2 ID is returned. result_ids = self.app.find_string_ids(string2, st.id) self.assertEqual(result_ids, {string2_id}) # Check common suffix is in the tree. edge, ln = self.app.find_substring_edge(common_suffix, st.id) assert isinstance(edge, SuffixTreeEdge) # self.assertEqual(edge.label, common_suffix + STRING_ID_END) # self.assertEqual(edge.label, common_suffix) # Check the edge has a node. node = self.app.node_repo[edge.dest_node_id] assert isinstance(node, SuffixTreeNode) # Check the node doesn't have a string ID. # self.assertEqual(node.string_id, None) # Check both IDs are returned. result_ids = self.app.find_string_ids(common_suffix, st.id) self.assertEqual(result_ids, {string1_id, string2_id}) def test_mississippi(self): st = self.app.register_new_suffix_tree() self.add_string_to_suffix_tree("mississippi", "$", st) self.add_string_to_suffix_tree("mudpie", "#", st) self.add_string_to_suffix_tree("ball", "%", st) self.add_string_to_suffix_tree("ball", "&", st) # # Check there isn't an 'a'. self.assertEqual(self.app.find_substring_edge('j', st.id), (None, None)) # Check 'm'. edge, ln = self.app.find_substring_edge('m', st.id) # self.assertEqual(edge.label, 'm') self.assertEqual(self.app.find_string_ids('m', st.id), {'$', '#'}) # Check 'mi'. edge, ln = self.app.find_substring_edge('mi', st.id) # self.assertEqual(edge.label, 'ississippi' + STRING_ID_END) self.assertEqual(self.app.find_string_ids('mi', st.id), {'$'}) # Check 'mu'. edge, ln = self.app.find_substring_edge('mu', st.id) # self.assertEqual(edge.label, 'udpie' + STRING_ID_END) self.assertEqual(self.app.find_string_ids('mu', st.id), {'#'}) # Check 'missi'. edge, ln = self.app.find_substring_edge('missi', st.id) self.assertEqual(edge.label, 'ississippi$' + STRING_ID_END) # Check 'issi'. edge, ln = self.app.find_substring_edge('issi', st.id) self.assertEqual(edge.label, 'ssi') # Check 'is'. edge, ln = self.app.find_substring_edge('is', st.id) self.assertEqual(edge.label, 'ssi') # Check 'si'. edge, ln = self.app.find_substring_edge('si', st.id) self.assertEqual(edge.label, 'i') # Check 'issip'. edge, ln = self.app.find_substring_edge('issip', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'ssip'. edge, ln = self.app.find_substring_edge('ssip', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'sip'. edge, ln = self.app.find_substring_edge('sip', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'ip'. edge, ln = self.app.find_substring_edge('ip', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'i'. edge, ln = self.app.find_substring_edge('i', st.id) self.assertEqual(edge.label, 'i') # Check 'ippi'. edge, ln = self.app.find_substring_edge('ippi$', st.id) self.assertEqual(edge.label, 'ppi$' + STRING_ID_END) # Check 'mudpie'. edge, ln = self.app.find_substring_edge('mudpie', st.id) self.assertEqual(edge.label, 'udpie#' + STRING_ID_END) # Check 'ball'. edge, ln = self.app.find_substring_edge('ball', st.id) self.assertEqual(edge.label, 'ball') # Check ID is returned. self.assertEqual(self.app.find_string_ids('mi', st.id), {'$'}) self.assertEqual(self.app.find_string_ids('si', st.id), {'$'}) self.assertEqual(self.app.find_string_ids('pp', st.id), {'$'}) self.assertEqual(self.app.find_string_ids('mu', st.id), {'#'}) self.assertEqual(self.app.find_string_ids('m', st.id), {'$','#'}) self.assertEqual(self.app.find_string_ids('b', st.id), {'%','&'}) def test_colours(self): st = self.app.register_new_suffix_tree() self.add_string_to_suffix_tree("blue", "$", st) self.add_string_to_suffix_tree("red", "#", st) # Check 'b'. edge, ln = self.app.find_substring_edge('b', st.id) self.assertEqual(edge.label, 'blue$' + STRING_ID_END) # Check 'l'. edge, ln = self.app.find_substring_edge('l', st.id) self.assertEqual(edge.label, 'lue$' + STRING_ID_END) # Check 'u'. edge, ln = self.app.find_substring_edge('u', st.id) self.assertEqual(edge.label, 'ue$' + STRING_ID_END) # Check 'e'. edge, ln = self.app.find_substring_edge('e', st.id) self.assertEqual(edge.label, 'e') # Check 'ue'. edge, ln = self.app.find_substring_edge('ue', st.id) self.assertEqual(edge.label, 'ue$' + STRING_ID_END) # Check 'lue'. edge, ln = self.app.find_substring_edge('lue', st.id) self.assertEqual(edge.label, 'lue$' + STRING_ID_END) # Check 'blue'. edge, ln = self.app.find_substring_edge('blue', st.id) self.assertEqual(edge.label, 'blue$' + STRING_ID_END) # Check 're'. edge, ln = self.app.find_substring_edge('re', st.id) self.assertEqual(edge.label, 'red#' + STRING_ID_END) # Check 'ed'. edge, ln = self.app.find_substring_edge('ed', st.id) self.assertEqual(edge.label, 'd#' + STRING_ID_END) # Check 'red'. edge, ln = self.app.find_substring_edge('red', st.id) self.assertEqual(edge.label, 'red#' + STRING_ID_END) def test_find_string_ids(self): # This test is the first to involve the children of nodes. st = self.app.register_new_suffix_tree() string1_id = uuid.uuid4().hex string2_id = uuid.uuid4().hex string3_id = uuid.uuid4().hex # string4_id = uuid.uuid4().hex self.add_string_to_suffix_tree("blue", string1_id, st) self.add_string_to_suffix_tree("red", string2_id, st) self.add_string_to_suffix_tree("blues", string3_id, st) strings = self.app.find_string_ids('$', st.id) assert not strings, strings strings = self.app.find_string_ids('0', st.id) assert not strings, strings strings = self.app.find_string_ids('1', st.id) assert not strings, strings strings = self.app.find_string_ids('2', st.id) assert not strings, strings strings = self.app.find_string_ids('3', st.id) assert not strings, strings strings = self.app.find_string_ids('4', st.id) assert not strings, strings strings = self.app.find_string_ids('5', st.id) assert not strings, strings strings = self.app.find_string_ids('6', st.id) assert not strings, strings strings = self.app.find_string_ids('7', st.id) assert not strings, strings # Find 'b'. strings = self.app.find_string_ids('b', st.id) self.assertIn(string1_id, strings) self.assertNotIn(string2_id, strings) # Find 'e'. strings = self.app.find_string_ids('e', st.id) self.assertEqual(len(strings), 3) self.assertIn(string1_id, strings, (string1_id, string2_id, string3_id, strings)) self.assertIn(string2_id, strings, (string1_id, string2_id, string3_id, strings)) self.assertIn(string3_id, strings, (string1_id, string2_id, string3_id, strings)) # Find 'e' - limit 1. strings = self.app.find_string_ids('e', st.id, limit=1) self.assertEqual(len(strings), 1) # Find 'e' - limit 2. strings = self.app.find_string_ids('e', st.id, limit=2) self.assertEqual(len(strings), 2) # Find 'r'. strings = self.app.find_string_ids('r', st.id) self.assertNotIn(string1_id, strings) self.assertIn(string2_id, strings) # Find 'd'. strings = self.app.find_string_ids('d', st.id) self.assertNotIn(string1_id, strings) self.assertIn(string2_id, strings) # Find 's'. strings = self.app.find_string_ids('s', st.id) self.assertNotIn(string1_id, strings) self.assertNotIn(string2_id, strings) self.assertIn(string3_id, strings) def test_add_string_to_suffixtree_from_repo(self): # Check adding strings after getting the tree from the repo. st = self.app.register_new_suffix_tree() st = self.app.get_suffix_tree(st.id) self.add_string_to_suffix_tree('blue', '1', st) st = self.app.get_suffix_tree(st.id) self.add_string_to_suffix_tree('green', '2', st) st = self.app.get_suffix_tree(st.id) self.add_string_to_suffix_tree('yellow', '3', st) st = self.app.get_suffix_tree(st.id) strings_ids = self.app.find_string_ids('e', st.id) self.assertEqual(3, len(strings_ids), strings_ids) self.assertEqual(['1', '2', '3'], sorted(strings_ids)) def test_remove_string_from_suffixtree(self): st = self.app.register_new_suffix_tree() # Add 'blue' and 'green'. self.add_string_to_suffix_tree('blue', '1', st) self.add_string_to_suffix_tree('green', '2', st) strings_ids = self.app.find_string_ids('b', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('l', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('u', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('r', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('g', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('e', st.id) self.assertEqual(2, len(strings_ids)) # Remove 'blue'. st.remove_string('blue', '1') strings_ids = self.app.find_string_ids('b', st.id) self.assertEqual(0, len(strings_ids)) strings_ids = self.app.find_string_ids('l', st.id) self.assertEqual(0, len(strings_ids)) strings_ids = self.app.find_string_ids('u', st.id) self.assertEqual(0, len(strings_ids)) strings_ids = self.app.find_string_ids('r', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('g', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('e', st.id) self.assertEqual(1, len(strings_ids), strings_ids) # Add 'blue' again. self.add_string_to_suffix_tree('blue', '1', st) strings_ids = self.app.find_string_ids('b', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('l', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('u', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('r', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('g', st.id) self.assertEqual(1, len(strings_ids)) strings_ids = self.app.find_string_ids('e', st.id) self.assertEqual(2, len(strings_ids)) class TestGeneralizedSuffixTreeSlow(GeneralizedSuffixTreeTestCase): def test_long_string(self): st = self.app.register_new_suffix_tree() self.add_string_to_suffix_tree(LONG_TEXT[:12000], '1', st) self.assertEqual(self.app.find_string_ids('Ukkonen', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('Optimal', st.id), {'1'}) self.assertFalse(self.app.find_string_ids('ukkonen', st.id)) self.add_string_to_suffix_tree(LONG_TEXT_CONT[:1000], '2', st) self.assertEqual(self.app.find_string_ids('Burrows-Wheeler', st.id), {'2'}) self.assertEqual(self.app.find_string_ids('suffix', st.id), {'1', '2'}) def ___test_split_long_string(self): # Split the long string into separate strings, and make some IDs. list_of_strings = [w for w in LONG_TEXT[:1000].split(' ') if w] print("Long string split into words: {}".format(list_of_strings)) string_ids = {} for string in list_of_strings: string_id = uuid.uuid4().hex string_ids[string_id] = string # Build the suffix tree. st = self.app.register_new_suffix_tree() for string_id, string in string_ids.items(): self.add_string_to_suffix_tree(string, string_id, st) # Check the suffix tree. for string_id, string in string_ids.items(): self.assertIn(string_id, self.app.find_string_ids(string, st.id), (string, string_id)) # Build the suffix tree. # - this time, get the suffix tree afresh from the repo each time st = self.app.register_new_suffix_tree() for string_id, string in string_ids.items(): st = self.app.get_suffix_tree(st.id) self.add_string_to_suffix_tree(string, string_id, st) # Check the suffix tree. for string_id, string in string_ids.items(): self.assertIn(string_id, self.app.find_string_ids(string, st.id)) def test_case_insensitivity(self): st = self.app.register_new_suffix_tree(case_insensitive=True) self.add_string_to_suffix_tree(LONG_TEXT[:12000], '1', st) self.assertEqual(self.app.find_string_ids('ukkonen', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('Optimal', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('burrows-wheeler', st.id), set()) self.add_string_to_suffix_tree(LONG_TEXT_CONT[:1000], '2', st) self.assertEqual(self.app.find_string_ids('ukkonen', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('Optimal', st.id), {'1'}) self.assertEqual(self.app.find_string_ids('burrows-wheeler', st.id), {'2'}) class TestMultiprocessingWithGeneralizedSuffixTree(CassandraTestCase): def setUp(self): super(TestMultiprocessingWithGeneralizedSuffixTree, self).setUp() self.app = None def tearDown(self): super(TestMultiprocessingWithGeneralizedSuffixTree, self).tearDown() if self.app is not None: self.app.close() # Todo: Fix this - adding strings in a random order sometimes breaks (perhaps a dict is causing indeterminate order). # def test_words(self): # self.check_words() def ___test_sorted_words(self): self.check_words(is_sorted=True) # Todo: Fix this - adding strings in a reversed sorted order always fails. Not sure why all substrings of 'ree' fail. The suffix is obviously not moving along in the same way as it does when the nodes are added. Perhaps it needs to add the IDs when explicit match is made, and then move the first char along by one? Not sure so trace it out? # # # Check for errors. # > self.assertFalse(errors, "\n".join(errors)) # E AssertionError: ["Not found: substring ''e'' from string ''tree''", "Not found: substring ''e'' from string ''tree''", "Not found: substring ''ee'' from string ''tree''", "Not found: substring ''r'' from string ''tree''", "Not found: substring ''re'' from string ''tree''", "Not found: substring ''ree'' from string ''tree''"] is not false : Not found: substring ''e'' from string ''tree'' # E Not found: substring ''e'' from string ''tree'' # E Not found: substring ''ee'' from string ''tree'' # E Not found: substring ''r'' from string ''tree'' # E Not found: substring ''re'' from string ''tree'' # E Not found: substring ''ree'' from string ''tree'' # def test_reversed_words(self): # self.check_words(is_reversed=True) def check_words(self, is_sorted=False, is_reversed=False): # Split the long string into separate strings, and make some IDs. words = list([w for w in LONG_TEXT[:100].split(' ') if w]) print("Adding words: {}".format(words)) # Avoid adding the same string twice (or a prefix of a previous string). # - because it's a current problem unless we append string IDs, which makes things too slow # words = set(words) # words = [w for w in words if 0 != sum([x.startswith(w) for x in words if x != w])] assert words # Make a string ID for each string. strings = {} for string in words: string_id = uuid.uuid4().hex strings[string_id] = string # Create a new suffix tree. self.app = SuffixTreeApplicationWithCassandra() st = self.app.register_new_suffix_tree() assert st.id in self.app.suffix_tree_repo # Close the app, so the pool doesn't inherit it. self.app.close() # Start the pool. pool = Pool(initializer=pool_initializer, processes=1) words = [[s, sid, st.id] for sid, s in strings.items() if s] if is_sorted: words = sorted(words) if is_reversed: words = reversed(words) results = pool.map(add_string_to_suffix_tree, words) for result in results: if isinstance(result, Exception): print(result.args[0][1]) raise result # Creat the app again. self.app = SuffixTreeApplicationWithCassandra() errors = [] # Check the suffix tree returns string ID for all substrings of string. for string_id, string in strings.items(): # Check all prefixes and suffixes. substrings = sorted(list(get_all_substrings(string))) print("") print("Checking for all substrings of string '{}': {}".format(repr(string), " ".join([repr(s) for s in substrings]))) for substring in substrings: results = self.app.find_string_ids(substring, st.id) if string_id not in results: msg = "Not found: substring '{}' from string '{}'".format(repr(substring), repr(string)) print(msg) errors.append(msg) # Check for errors. self.assertFalse(errors, "\n".join(errors)) def get_all_substrings(s): length = len(s) return (s[i:j] for i in six.moves.xrange(length) for j in six.moves.xrange(i + 1, length + 1)) worker_app = None def pool_initializer(): global worker_app worker_app = SuffixTreeApplicationWithCassandra() def add_string_to_suffix_tree(args): # random.seed() string, string_id, suffix_tree_id = args print("") print("Adding string to suffix tree: {}: {}".format(string_id, repr(string[:100]))) try: assert isinstance(worker_app, AbstractSuffixTreeApplication) suffix_tree = worker_app.get_suffix_tree(suffix_tree_id) assert isinstance(suffix_tree, GeneralizedSuffixTree) started = datetime.datetime.now() suffix_tree.add_string(string, string_id) print(" - added string in: {}".format(datetime.datetime.now() - started)) except Exception as e: msg = traceback.format_exc() print(" - failed to add string: {}".format(msg)) return Exception((e, msg, string, string_id)) return string_id
#!/usr/bin/env python ######################################################################################### # # Perform various types of processing from the spinal cord segmentation (e.g. extract centerline, compute CSA, etc.). # (extract_centerline) extract the spinal cord centerline from the segmentation. Output file is an image in the same # space as the segmentation. # # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Author: Benjamin De Leener, Julien Touati, Gabriel Mangeat # Created: 2014-05-24 # # About the license: see the file LICENSE.TXT ######################################################################################### # TODO: flag to remove temp files (r) # DEFAULT PARAMETERS class param: ## The constructor def __init__(self): self.debug = 0 self.verbose = 1 # verbose self.step = 1 # step of discretized plane in mm default is min(x_scale,y_scale) self.remove_temp_files = 1 import re import math import sys import getopt import os import commands import numpy as np import time import sct_utils as sct from sct_nurbs import NURBS import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.misc import imsave,imread import scipy.ndimage as ndi from matplotlib.pyplot import imshow, gray, show import scipy from numpy.linalg import eig, inv import Image try: import nibabel except ImportError: print '--- nibabel not installed! Exit program. ---' sys.exit(2) # MAIN # ========================================================================================== def main(): # Initialization path_script = os.path.dirname(__file__) fsloutput = 'export FSLOUTPUTTYPE=NIFTI; ' # for faster processing, all outputs are in NIFTI # THIS DOES NOT WORK IN MY LAPTOP: path_sct = os.environ['SCT_DIR'] # path to spinal cord toolbox #path_sct = path_script[:-8] # TODO: make it cleaner! status, path_sct = commands.getstatusoutput('echo $SCT_DIR') fname_segmentation = '' name_process = '' processes = ['extract_centerline','compute_CSA'] method_CSA = ['counting_ortho_plane','counting_z_plane','ellipse_ortho_plane','ellipse_z_plane'] name_method = '' volume_output = 0 verbose = param.verbose start_time = time.time() remove_temp_files = param.remove_temp_files # Parameters for debug mode if param.debug: fname_segmentation = path_sct+'/testing/data/errsm_23/t2/t2_segmentation_PropSeg.nii' verbose = 1 remove_temp_files = 0 # Check input parameters try: opts, args = getopt.getopt(sys.argv[1:],'hi:p:m:b:v:') except getopt.GetoptError: usage() for opt, arg in opts : if opt == '-h': usage() elif opt in ("-i"): fname_segmentation = arg elif opt in ("-p"): name_process = arg elif opt in("-m"): name_method = arg elif opt in('-b'): volume_output = int(arg) elif opt in ('-v'): verbose = int(arg) # display usage if a mandatory argument is not provided if fname_segmentation == '' or name_process == '': usage() # display usage if the requested process is not available if name_process not in processes: usage() # display usage if incorrect method if name_process == 'compute_CSA' and (name_method not in method_CSA): usage() # display usage if no method provided if name_process=='compute_CSA' and method_CSA == '': usage() # check existence of input files sct.check_file_exist(fname_segmentation) # print arguments print '\nCheck parameters:' print '.. segmentation file: '+fname_segmentation if name_process == 'extract_centerline': extract_centerline(fname_segmentation) if name_process == 'compute_CSA' : compute_CSA(fname_segmentation,name_method,volume_output,verbose) # display elapsed time elapsed_time = time.time() - start_time print '\nFinished! Elapsed time: '+str(int(round(elapsed_time)))+'s' # End of Main # EXTRACT_CENTERLINE # ========================================================================================== def extract_centerline(fname_segmentation): # Extract path, file and extension path_data, file_data, ext_data = sct.extract_fname(fname_segmentation) # create temporary folder path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") sct.run('mkdir '+path_tmp) # copy files into tmp folder sct.run('cp '+fname_segmentation+' '+path_tmp) # go to tmp folder os.chdir(path_tmp) remove_temp_files = param.remove_temp_files # Change orientation of the input segmentation into RPI print '\nOrient segmentation image to RPI orientation...' fname_segmentation_orient = 'tmp.segmentation_rpi' + ext_data sct.run('sct_orientation -i ' + file_data+ext_data + ' -o ' + fname_segmentation_orient + ' -orientation RPI') # Extract orientation of the input segmentation status,sct_orientation_output = sct.run('sct_orientation -i ' + file_data+ext_data + ' -get') orientation = sct_orientation_output[-3:] print '\nOrientation of segmentation image: ' + orientation # Get size of data print '\nGet dimensions data...' nx, ny, nz, nt, px, py, pz, pt = sct.get_dimension(fname_segmentation_orient) print '.. '+str(nx)+' x '+str(ny)+' y '+str(nz)+' z '+str(nt) print '\nOpen segmentation volume...' file = nibabel.load(fname_segmentation_orient) data = file.get_data() hdr = file.get_header() # Extract min and max index in Z direction X, Y, Z = (data>0).nonzero() min_z_index, max_z_index = min(Z), max(Z) x_centerline = [0 for i in range(0,max_z_index-min_z_index+1)] y_centerline = [0 for i in range(0,max_z_index-min_z_index+1)] z_centerline = [iz for iz in range(min_z_index, max_z_index+1)] # Extract segmentation points and average per slice for iz in range(min_z_index, max_z_index+1): x_seg, y_seg = (data[:,:,iz]>0).nonzero() x_centerline[iz-min_z_index] = np.mean(x_seg) y_centerline[iz-min_z_index] = np.mean(y_seg) for k in range(len(X)): data[X[k],Y[k],Z[k]] = 0 # Fit the centerline points with splines and return the new fitted coordinates x_centerline_fit, y_centerline_fit,x_centerline_deriv,y_centerline_deriv,z_centerline_deriv = b_spline_centerline(x_centerline,y_centerline,z_centerline) # Create an image with the centerline for iz in range(min_z_index, max_z_index+1): data[round(x_centerline_fit[iz-min_z_index]),round(y_centerline_fit[iz-min_z_index]),iz] = 1 # Write the centerline image in RPI orientation hdr.set_data_dtype('uint8') # set imagetype to uint8 print '\nWrite NIFTI volumes...' img = nibabel.Nifti1Image(data, None, hdr) nibabel.save(img, 'tmp.centerline.nii') sct.generate_output_file('tmp.centerline.nii','./',file_data+'_centerline',ext_data) del data # come back to parent folder os.chdir('..') # Change orientation of the output centerline into input orientation print '\nOrient centerline image to input orientation: ' + orientation fname_segmentation_orient = 'tmp.segmentation_rpi' + ext_data sct.run('sct_orientation -i ' + path_tmp+'/'+file_data+'_centerline'+ext_data + ' -o ' + file_data+'_centerline'+ext_data + ' -orientation ' + orientation) # Remove temporary files if remove_temp_files == 1 : print('\nRemove temporary files...') sct.run('rm -rf '+path_tmp) # to view results print '\nTo view results, type:' print 'fslview '+file_data+'_centerline &\n' # End of extract_centerline # COMPUTE_CSA # ========================================================================================== def compute_CSA(fname_segmentation,name_method,volume_output,verbose): # Extract path, file and extension path_data_seg, file_data_seg, ext_data_seg = sct.extract_fname(fname_segmentation) # create temporary folder path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") sct.run('mkdir '+path_tmp) # copy files into tmp folder sct.run('cp '+fname_segmentation+' '+path_tmp) # go to tmp folder os.chdir(path_tmp) # initialize parameters remove_temp_files = param.remove_temp_files step = param.step # Change orientation of the input segmentation into RPI print '\nOrient segmentation image to RPI orientation...' fname_segmentation_orient = 'tmp.segmentation_rpi' + ext_data_seg sct.run('sct_orientation -i ' + file_data_seg + ext_data_seg + ' -o ' + fname_segmentation_orient + ' -orientation RPI') # Get size of data print '\nGet dimensions data...' nx, ny, nz, nt, px, py, pz, pt = sct.get_dimension(fname_segmentation_orient) print '.. '+str(nx)+' x '+str(ny)+' y '+str(nz)+' z '+str(nt) print '\nOpen segmentation volume...' file_seg = nibabel.load(fname_segmentation_orient) data_seg = file_seg.get_data() hdr_seg = file_seg.get_header() # Get mm scales of the volume x_scale=hdr_seg['pixdim'][1] y_scale=hdr_seg['pixdim'][2] z_scale=hdr_seg['pixdim'][3] # Extract min and max index in Z direction X, Y, Z = (data_seg>0).nonzero() coords_seg = np.array([str([X[i],Y[i],Z[i]]) for i in xrange(0,len(Z))]) #don't know why but finding strings in array of array of strings is WAY faster than doing the same with integers #coords_seg = [[X[i],Y[i],Z[i]] for i in range(0,len(Z))] #don't know why but finding strings in array of array of strings is WAY faster than doing the same with integers min_z_index, max_z_index = min(Z), max(Z) Xp,Yp = (data_seg[:,:,0]>=0).nonzero() # X and Y range x_centerline = [0 for i in xrange(0,max_z_index-min_z_index+1)] y_centerline = [0 for i in xrange(0,max_z_index-min_z_index+1)] z_centerline = [iz for iz in xrange(min_z_index, max_z_index+1)] # Extract segmentation points and average per slice for iz in xrange(min_z_index, max_z_index+1): x_seg, y_seg = (data_seg[:,:,iz]>0).nonzero() x_centerline[iz-min_z_index] = np.mean(x_seg) y_centerline[iz-min_z_index] = np.mean(y_seg) # ### First Method : counting voxel in orthogonal plane + fitting ellipse in orthogonal plane # Fit the centerline points with spline and return the new fitted coordinates x_centerline_fit, y_centerline_fit,x_centerline_deriv,y_centerline_deriv,z_centerline_deriv = b_spline_centerline(x_centerline,y_centerline,z_centerline) # 3D plot of the fit # fig=plt.figure() # ax=Axes3D(fig) # ax.plot(x_centerline,y_centerline,z_centerline,zdir='z') # ax.plot(x_centerline_fit,y_centerline_fit,z_centerline,zdir='z') # plt.show() # Defining cartesian basis vectors x=np.array([1,0,0]) y=np.array([0,1,0]) z=np.array([0,0,1]) # Creating folder in which JPG files will be stored sct.run('mkdir JPG_Results') # Computing CSA print('\nComputing CSA...') # Empty arrays in which CSA for each z slice will be stored sections_ortho_counting = [0 for i in xrange(0,max_z_index-min_z_index+1)] sections_ortho_ellipse = [0 for i in xrange(0,max_z_index-min_z_index+1)] sections_z_ellipse = [0 for i in xrange(0,max_z_index-min_z_index+1)] sections_z_counting = [0 for i in xrange(0,max_z_index-min_z_index+1)] for iz in xrange(0, len(z_centerline)): # Equation of the the plane which is orthogonal to the spline at z=iz a = x_centerline_deriv[iz] b = y_centerline_deriv[iz] c = z_centerline_deriv[iz] #vector normal to the plane normal=normalize(np.array([a,b,c])) # angle between normal vector and z angle = np.arccos(np.dot(normal,z)) if name_method == 'counting_ortho_plane' or name_method == 'ellipse_ortho_plane': x_center = x_centerline_fit[iz] y_center = y_centerline_fit[iz] z_center = z_centerline[iz] # use of x in order to get orientation of each plane, basis_1 is in the plane ax+by+cz+d=0 basis_1 = normalize(np.cross(normal,x)) basis_2 = normalize(np.cross(normal,basis_1)) # maximum dimension of the tilted plane. Try multiply numerator by sqrt(2) ? max_diameter = (max([(max(X)-min(X))*x_scale,(max(Y)-min(Y))*y_scale]))/(np.cos(angle)) # Forcing the step to be the min of x and y scale (default value is 1 mm) step = min([x_scale,y_scale]) # discretized plane which will be filled with 0/1 plane_seg = np.zeros((int(max_diameter/step),int(max_diameter/step))) # how the plane will be skimmed through plane_grid = np.linspace(-int(max_diameter/2),int(max_diameter/2),int(max_diameter/step)) # we go through the plane for i_b1 in plane_grid : for i_b2 in plane_grid : point = np.array([x_center*x_scale,y_center*y_scale,z_center*z_scale]) + i_b1*basis_1 +i_b2*basis_2 # to which voxel belongs each point of the plane coord_voxel = str([ int(point[0]/x_scale), int(point[1]/y_scale), int(point[2]/z_scale)]) #coord_voxel = [ int(point[0]/x_scale), int(point[1]/y_scale), int(point[2]/z_scale)] if (coord_voxel in coords_seg) is True : # if this voxel is 1 plane_seg[int((plane_grid==i_b1).nonzero()[0])][int((plane_grid==i_b2).nonzero()[0])] = 1 # number of voxels that are in the intersection of each plane and the nonzeros values of segmentation, times the area of one cell of the discretized plane if name_method == 'counting_ortho_plane': sections_ortho_counting[iz] = len((plane_seg>0).nonzero()[0])*step*step if verbose ==1 and name_method == 'counting_ortho_plane' : print('\nsection ' + str(sections_ortho_counting[iz])) if name_method == 'ellipse_ortho_plane' : os.chdir('JPG_Results') imsave('plane_ortho_' + str(iz) + '.jpg', plane_seg) # Tresholded gradient image mag = edge_detection('plane_ortho_' + str(iz) + '.jpg') #Coordinates of the contour x_contour,y_contour = (mag>0).nonzero() x_contour = x_contour*step y_contour = y_contour*step #Fitting an ellipse fit = Ellipse_fit(x_contour,y_contour) # Semi-minor axis, semi-major axis a_ellipse, b_ellipse = ellipse_dim(fit) #Section = pi*a*b sections_ortho_ellipse[iz] = a_ellipse*b_ellipse*np.pi if verbose == 1 and name_method == 'ellipse_ortho_plane': print('\nsection ' + str(sections_ortho_ellipse[iz])) os.chdir('..') if name_method == 'counting_z_plane' or name_method == 'ellipse_z_plane': # getting the segmentation for each z plane x_seg, y_seg = (data_seg[:,:,iz+min_z_index]>0).nonzero() seg = [[x_seg[i],y_seg[i]] for i in range(0,len(x_seg))] plane=np.zeros((max(Xp),max(Yp))) for i in seg: # filling the plane with 0 and 1 regarding to the segmentation plane[i[0] - 1][i[1] - 1] = 1 if name_method == 'counting_z_plane' : sections_z_counting[iz] = len((plane>0).nonzero()[0])*x_scale*y_scale*np.cos(angle) if verbose == 1 and name_method == 'counting_z_plane': print('\nsection ' + str(sections_z_counting[iz])) if name_method == 'ellipse_z_plane': os.chdir('JPG_Results') imsave('plane_z_' + str(iz) + '.jpg', plane) # Tresholded gradient image mag = edge_detection('plane_z_' + str(iz) + '.jpg') x_contour,y_contour = (mag>0).nonzero() x_contour = x_contour*x_scale y_contour = y_contour*y_scale # Fitting an ellipse fit = Ellipse_fit(x_contour,y_contour) a_ellipse, b_ellipse = ellipse_dim(fit) sections_z_ellipse[iz] = a_ellipse*b_ellipse*np.pi*np.cos(angle) if verbose == 1 and name_method == 'ellipse_z_plane': print('\nsection ' + str(sections_z_ellipse[iz])) os.chdir('..') # come back to parent folder os.chdir('..') # Creating output text file if name_method == 'counting_ortho_plane' : print('\nGenerating output text file...\n') file_results = open('Cross_Section_Area_ortho_counting.txt','w') file_results.write('List of Cross Section Areas for each z slice\n') for i in range(min_z_index, max_z_index+1): file_results.write('\nz = ' + str(i*z_scale) + ' mm -> CSA = ' + str(sections_ortho_counting[i-min_z_index]) + ' mm^2') file_results.close() if name_method == 'ellipse_ortho_plane' : print('\nGenerating output text file...\n') file_results = open('Cross_Section_Area_ortho_ellipse.txt','w') file_results.write('List of Cross Section Areas for each z slice\n') for i in range(min_z_index, max_z_index+1): file_results.write('\nz = ' + str(i*z_scale) + ' mm -> CSA = ' + str(sections_ortho_ellipse[i-min_z_index]) + ' mm^2') file_results.close() if name_method == 'ellipse_z_plane' : print('\nGenerating output text file...\n') file_results = open('Cross_Section_Area_z_ellipse.txt','w') file_results.write('List of Cross Section Areas for each z slice\n') for i in range(min_z_index, max_z_index+1): file_results.write('\nz = ' + str(i*z_scale) + ' mm -> CSA = ' + str(sections_z_ellipse[i-min_z_index]) + ' mm^2') file_results.close() if name_method == 'counting_z_plane' : print('\nGenerating output text file...\n') file_results = open('Cross_Section_Area_z_counting.txt','w') file_results.write('List of Cross Section Areas for each z slice\n') for i in range(min_z_index, max_z_index+1): file_results.write('\nz = ' + str(i*z_scale) + ' mm -> CSA = ' + str(sections_z_counting[i-min_z_index]) + ' mm^2') file_results.close() # if name_method == 'counting_z_plane': # fig=plt.figure() # plt.plot(z_centerline*z_scale,sections_z_counting) # plt.show() # if name_method == 'counting_ortho_plane': # fig=plt.figure() # plt.plot(z_centerline*z_scale,sections_ortho_counting) # plt.show() # if name_method == 'ellipse_z_plane': # fig=plt.figure() # plt.plot(z_centerline*z_scale,sections_z_ellipse) # plt.show() # if name_method == 'ellipse_ortho_plane': # fig=plt.figure() # plt.plot(z_centerline*z_scale,sections_ortho_ellipse) # plt.show() # if volume_output == 1 : # Extract orientation of the input segmentation status,sct_orientation_output = sct.run('sct_orientation -i '+file_data_seg+ext_data_seg + ' -get') orientation = sct_orientation_output[-3:] for iz in range(0,len(z_centerline)): x_seg, y_seg = (data_seg[:,:,iz]>0).nonzero() seg = [[x_seg[i],y_seg[i]] for i in range(0,len(x_seg))] for i in seg : if name_method == 'counting_ortho_plane': data_seg[i[0],i[1],iz] = sections_ortho_counting[iz] if name_method == 'counting_z_plane': data_seg[i[0],i[1],iz] = sections_z_counting[iz] if name_method == 'ellipse_ortho_plane': data_seg[i[0],i[1],iz] = sections_ortho_ellipse[iz] if name_method == 'ellipse_z_plane': data_seg[i[0],i[1],iz] = sections_z_ellipse[iz] hdr_seg.set_data_dtype('uint8') # set imagetype to uint8 print '\nWrite NIFTI volumes...' img = nibabel.Nifti1Image(data_seg, None, hdr_seg) file_name = path_tmp+'/'+file_data_seg+'_CSA_slices_rpi'+ext_data_seg nibabel.save(img,file_name) print '.. File created:' + file_name # Change orientation of the output centerline into input orientation print '\nOrient image to input orientation: ' sct.run('sct_orientation -i '+path_tmp+'/'+file_data_seg+'_CSA_slices_rpi'+ext_data_seg + ' -o ' + file_data_seg+'_CSA_slices'+ext_data_seg + ' -orientation ' + orientation) del data_seg # Remove temporary files if remove_temp_files == 1 : print('\nRemove temporary files...') sct.run('rm -rf '+path_tmp) # End of compute_CSA #======================================================================================================================= # B-Spline fitting #======================================================================================================================= def b_spline_centerline(x_centerline,y_centerline,z_centerline): print '\nFitting centerline using B-spline approximation...' points = [[x_centerline[n],y_centerline[n],z_centerline[n]] for n in range(len(x_centerline))] nurbs = NURBS(3,3000,points) # BE very careful with the spline order that you choose : if order is too high ( > 4 or 5) you need to set a higher number of Control Points (cf sct_nurbs ). For the third argument (number of points), give at least len(z_centerline)+500 or higher P = nurbs.getCourbe3D() x_centerline_fit=P[0] y_centerline_fit=P[1] Q = nurbs.getCourbe3D_deriv() x_centerline_deriv=Q[0] y_centerline_deriv=Q[1] z_centerline_deriv=Q[2] return x_centerline_fit, y_centerline_fit,x_centerline_deriv,y_centerline_deriv,z_centerline_deriv #======================================================================================================================= # Normalization #======================================================================================================================= def normalize(vect): norm=np.linalg.norm(vect) return vect/norm #======================================================================================================================= # Ellipse fitting for a set of data #======================================================================================================================= #http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html def Ellipse_fit(x,y): x = x[:,np.newaxis] y = y[:,np.newaxis] D = np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x))) S = np.dot(D.T,D) C = np.zeros([6,6]) C[0,2] = C[2,0] = 2 C[1,1] = -1 E, V = eig(np.dot(inv(S), C)) n = np.argmax(np.abs(E)) a = V[:,n] return a #======================================================================================================================= # Getting a and b parameter for fitted ellipse #======================================================================================================================= def ellipse_dim(a): b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0] up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g) down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a)) down2=(b*b-a*c)*( (a-c)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a)) res1=np.sqrt(up/down1) res2=np.sqrt(up/down2) return np.array([res1, res2]) #======================================================================================================================= # Detect edges of an image #======================================================================================================================= def edge_detection(f) : #sigma = 1.0 img = Image.open(f) #grayscale imgdata = np.array(img, dtype = float) G = imgdata #G = ndi.filters.gaussian_filter(imgdata, sigma) gradx = np.array(G, dtype = float) grady = np.array(G, dtype = float) mask_x = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) mask_y = np.array([[1,2,1],[0,0,0],[-1,-2,-1]]) width = img.size[1] height = img.size[0] for i in range(1, width-1): for j in range(1, height-1): px = np.sum(mask_x*G[(i-1):(i+1)+1,(j-1):(j+1)+1]) py = np.sum(mask_y*G[(i-1):(i+1)+1,(j-1):(j+1)+1]) gradx[i][j] = px grady[i][j] = py mag = scipy.hypot(gradx,grady) treshold = np.max(mag)*0.9 for i in range(width): for j in range(height): if mag[i][j]>treshold: mag[i][j]=1 else: mag[i][j] = 0 return mag # Print usage # ========================================================================================== def usage(): print '\n' \ ''+os.path.basename(__file__)+'\n' \ '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' \ 'Part of the Spinal Cord Toolbox <https://sourceforge.net/projects/spinalcordtoolbox>\n' \ '\n'\ 'DESCRIPTION\n' \ ' This function performs various types of processing from the spinal cord segmentation, e.g.,\n' \ ' extract centerline, compute cross-sectional area (CSA).\n' \ '\n' \ 'USAGE\n' \ ' '+os.path.basename(__file__)+' -i <segmentation> -p <process>\n' \ '\n' \ 'MANDATORY ARGUMENTS\n' \ ' -i <segmentation> spinal cord segmentation (e.g., use sct_segmentation_propagation)\n' \ ' -p <process> type of process to be performed {extract_centerline}, {compute_CSA}\n' \ ' -m <method_CSA> if process is "compute_CSA", the following methods are available:\n' \ ' counting_ortho_plane: resample planes orthogonal to centerline and count\n' \ ' pixels in each plane.\n' \ ' counting_z_plane: count pixels in each slice and then geometrically\n' \ ' adjust using centerline orientation.\n' \ ' ellipse_ortho_plane: same process as counting_ortho_plane, but fit\n' \ ' ellipse instead of counting pixels.\n' \ ' ellipse_z_plane: same process as counting_z_plane, but fit ellipse\n' \ ' instead of counting pixels.\n' \ '\n' \ 'OPTIONAL ARGUMENTS\n' \ ' -v <0,1> verbose. Default='+str(param.verbose)+'.\n' \ ' -b <0,1> outputs a volume in which each slice\'s value is equal to the CSA in\n' \ ' mm^2. Default = 0\n' \ '\n' \ 'EXAMPLE\n' \ ' sct_process_segmentation.py -i binary_segmentation.nii.gz -p compute_CSA -m counting_z_plane\n' # exit program sys.exit(2) # START PROGRAM # ========================================================================================= if __name__ == "__main__": # initialize parameters param = param() # call main function main() BUG : bug using -b flag fixed #!/usr/bin/env python ######################################################################################### # # Perform various types of processing from the spinal cord segmentation (e.g. extract centerline, compute CSA, etc.). # (extract_centerline) extract the spinal cord centerline from the segmentation. Output file is an image in the same # space as the segmentation. # # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Author: Benjamin De Leener, Julien Touati, Gabriel Mangeat # Created: 2014-05-24 # # About the license: see the file LICENSE.TXT ######################################################################################### # TODO: flag to remove temp files (r) # DEFAULT PARAMETERS class param: ## The constructor def __init__(self): self.debug = 0 self.verbose = 1 # verbose self.step = 1 # step of discretized plane in mm default is min(x_scale,y_scale) self.remove_temp_files = 1 import re import math import sys import getopt import os import commands import numpy as np import time import sct_utils as sct from sct_nurbs import NURBS import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.misc import imsave,imread import scipy.ndimage as ndi from matplotlib.pyplot import imshow, gray, show import scipy from numpy.linalg import eig, inv import Image try: import nibabel except ImportError: print '--- nibabel not installed! Exit program. ---' sys.exit(2) # MAIN # ========================================================================================== def main(): # Initialization path_script = os.path.dirname(__file__) fsloutput = 'export FSLOUTPUTTYPE=NIFTI; ' # for faster processing, all outputs are in NIFTI # THIS DOES NOT WORK IN MY LAPTOP: path_sct = os.environ['SCT_DIR'] # path to spinal cord toolbox #path_sct = path_script[:-8] # TODO: make it cleaner! status, path_sct = commands.getstatusoutput('echo $SCT_DIR') fname_segmentation = '' name_process = '' processes = ['extract_centerline','compute_CSA'] method_CSA = ['counting_ortho_plane','counting_z_plane','ellipse_ortho_plane','ellipse_z_plane'] name_method = '' volume_output = 0 verbose = param.verbose start_time = time.time() remove_temp_files = param.remove_temp_files # Parameters for debug mode if param.debug: fname_segmentation = path_sct+'/testing/data/errsm_23/t2/t2_segmentation_PropSeg.nii' verbose = 1 remove_temp_files = 0 # Check input parameters try: opts, args = getopt.getopt(sys.argv[1:],'hi:p:m:b:v:') except getopt.GetoptError: usage() for opt, arg in opts : if opt == '-h': usage() elif opt in ("-i"): fname_segmentation = arg elif opt in ("-p"): name_process = arg elif opt in("-m"): name_method = arg elif opt in('-b'): volume_output = int(arg) elif opt in ('-v'): verbose = int(arg) # display usage if a mandatory argument is not provided if fname_segmentation == '' or name_process == '': usage() # display usage if the requested process is not available if name_process not in processes: usage() # display usage if incorrect method if name_process == 'compute_CSA' and (name_method not in method_CSA): usage() # display usage if no method provided if name_process=='compute_CSA' and method_CSA == '': usage() # check existence of input files sct.check_file_exist(fname_segmentation) # print arguments print '\nCheck parameters:' print '.. segmentation file: '+fname_segmentation if name_process == 'extract_centerline': extract_centerline(fname_segmentation) if name_process == 'compute_CSA' : compute_CSA(fname_segmentation,name_method,volume_output,verbose) # display elapsed time elapsed_time = time.time() - start_time print '\nFinished! Elapsed time: '+str(int(round(elapsed_time)))+'s' # End of Main # EXTRACT_CENTERLINE # ========================================================================================== def extract_centerline(fname_segmentation): # Extract path, file and extension path_data, file_data, ext_data = sct.extract_fname(fname_segmentation) # create temporary folder path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") sct.run('mkdir '+path_tmp) # copy files into tmp folder sct.run('cp '+fname_segmentation+' '+path_tmp) # go to tmp folder os.chdir(path_tmp) remove_temp_files = param.remove_temp_files # Change orientation of the input segmentation into RPI print '\nOrient segmentation image to RPI orientation...' fname_segmentation_orient = 'tmp.segmentation_rpi' + ext_data sct.run('sct_orientation -i ' + file_data+ext_data + ' -o ' + fname_segmentation_orient + ' -orientation RPI') # Extract orientation of the input segmentation status,sct_orientation_output = sct.run('sct_orientation -i ' + file_data+ext_data + ' -get') orientation = sct_orientation_output[-3:] print '\nOrientation of segmentation image: ' + orientation # Get size of data print '\nGet dimensions data...' nx, ny, nz, nt, px, py, pz, pt = sct.get_dimension(fname_segmentation_orient) print '.. '+str(nx)+' x '+str(ny)+' y '+str(nz)+' z '+str(nt) print '\nOpen segmentation volume...' file = nibabel.load(fname_segmentation_orient) data = file.get_data() hdr = file.get_header() # Extract min and max index in Z direction X, Y, Z = (data>0).nonzero() min_z_index, max_z_index = min(Z), max(Z) x_centerline = [0 for i in range(0,max_z_index-min_z_index+1)] y_centerline = [0 for i in range(0,max_z_index-min_z_index+1)] z_centerline = [iz for iz in range(min_z_index, max_z_index+1)] # Extract segmentation points and average per slice for iz in range(min_z_index, max_z_index+1): x_seg, y_seg = (data[:,:,iz]>0).nonzero() x_centerline[iz-min_z_index] = np.mean(x_seg) y_centerline[iz-min_z_index] = np.mean(y_seg) for k in range(len(X)): data[X[k],Y[k],Z[k]] = 0 # Fit the centerline points with splines and return the new fitted coordinates x_centerline_fit, y_centerline_fit,x_centerline_deriv,y_centerline_deriv,z_centerline_deriv = b_spline_centerline(x_centerline,y_centerline,z_centerline) # Create an image with the centerline for iz in range(min_z_index, max_z_index+1): data[round(x_centerline_fit[iz-min_z_index]),round(y_centerline_fit[iz-min_z_index]),iz] = 1 # Write the centerline image in RPI orientation hdr.set_data_dtype('uint8') # set imagetype to uint8 print '\nWrite NIFTI volumes...' img = nibabel.Nifti1Image(data, None, hdr) nibabel.save(img, 'tmp.centerline.nii') sct.generate_output_file('tmp.centerline.nii','./',file_data+'_centerline',ext_data) del data # come back to parent folder os.chdir('..') # Change orientation of the output centerline into input orientation print '\nOrient centerline image to input orientation: ' + orientation fname_segmentation_orient = 'tmp.segmentation_rpi' + ext_data sct.run('sct_orientation -i ' + path_tmp+'/'+file_data+'_centerline'+ext_data + ' -o ' + file_data+'_centerline'+ext_data + ' -orientation ' + orientation) # Remove temporary files if remove_temp_files == 1 : print('\nRemove temporary files...') sct.run('rm -rf '+path_tmp) # to view results print '\nTo view results, type:' print 'fslview '+file_data+'_centerline &\n' # End of extract_centerline # COMPUTE_CSA # ========================================================================================== def compute_CSA(fname_segmentation,name_method,volume_output,verbose): # Extract path, file and extension path_data_seg, file_data_seg, ext_data_seg = sct.extract_fname(fname_segmentation) # create temporary folder path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") sct.run('mkdir '+path_tmp) # copy files into tmp folder sct.run('cp '+fname_segmentation+' '+path_tmp) # go to tmp folder os.chdir(path_tmp) # initialize parameters remove_temp_files = param.remove_temp_files step = param.step # Change orientation of the input segmentation into RPI print '\nOrient segmentation image to RPI orientation...' fname_segmentation_orient = 'tmp.segmentation_rpi' + ext_data_seg sct.run('sct_orientation -i ' + file_data_seg + ext_data_seg + ' -o ' + fname_segmentation_orient + ' -orientation RPI') # Get size of data print '\nGet dimensions data...' nx, ny, nz, nt, px, py, pz, pt = sct.get_dimension(fname_segmentation_orient) print '.. '+str(nx)+' x '+str(ny)+' y '+str(nz)+' z '+str(nt) print '\nOpen segmentation volume...' file_seg = nibabel.load(fname_segmentation_orient) data_seg = file_seg.get_data() hdr_seg = file_seg.get_header() # Get mm scales of the volume x_scale=hdr_seg['pixdim'][1] y_scale=hdr_seg['pixdim'][2] z_scale=hdr_seg['pixdim'][3] # Extract min and max index in Z direction X, Y, Z = (data_seg>0).nonzero() coords_seg = np.array([str([X[i],Y[i],Z[i]]) for i in xrange(0,len(Z))]) #don't know why but finding strings in array of array of strings is WAY faster than doing the same with integers #coords_seg = [[X[i],Y[i],Z[i]] for i in range(0,len(Z))] #don't know why but finding strings in array of array of strings is WAY faster than doing the same with integers min_z_index, max_z_index = min(Z), max(Z) Xp,Yp = (data_seg[:,:,0]>=0).nonzero() # X and Y range x_centerline = [0 for i in xrange(0,max_z_index-min_z_index+1)] y_centerline = [0 for i in xrange(0,max_z_index-min_z_index+1)] z_centerline = [iz for iz in xrange(min_z_index, max_z_index+1)] # Extract segmentation points and average per slice for iz in xrange(min_z_index, max_z_index+1): x_seg, y_seg = (data_seg[:,:,iz]>0).nonzero() x_centerline[iz-min_z_index] = np.mean(x_seg) y_centerline[iz-min_z_index] = np.mean(y_seg) # ### First Method : counting voxel in orthogonal plane + fitting ellipse in orthogonal plane # Fit the centerline points with spline and return the new fitted coordinates x_centerline_fit, y_centerline_fit,x_centerline_deriv,y_centerline_deriv,z_centerline_deriv = b_spline_centerline(x_centerline,y_centerline,z_centerline) # 3D plot of the fit # fig=plt.figure() # ax=Axes3D(fig) # ax.plot(x_centerline,y_centerline,z_centerline,zdir='z') # ax.plot(x_centerline_fit,y_centerline_fit,z_centerline,zdir='z') # plt.show() # Defining cartesian basis vectors x=np.array([1,0,0]) y=np.array([0,1,0]) z=np.array([0,0,1]) # Creating folder in which JPG files will be stored sct.run('mkdir JPG_Results') # Computing CSA print('\nComputing CSA...') # Empty arrays in which CSA for each z slice will be stored sections_ortho_counting = [0 for i in xrange(0,max_z_index-min_z_index+1)] sections_ortho_ellipse = [0 for i in xrange(0,max_z_index-min_z_index+1)] sections_z_ellipse = [0 for i in xrange(0,max_z_index-min_z_index+1)] sections_z_counting = [0 for i in xrange(0,max_z_index-min_z_index+1)] for iz in xrange(0, len(z_centerline)): # Equation of the the plane which is orthogonal to the spline at z=iz a = x_centerline_deriv[iz] b = y_centerline_deriv[iz] c = z_centerline_deriv[iz] #vector normal to the plane normal=normalize(np.array([a,b,c])) # angle between normal vector and z angle = np.arccos(np.dot(normal,z)) if name_method == 'counting_ortho_plane' or name_method == 'ellipse_ortho_plane': x_center = x_centerline_fit[iz] y_center = y_centerline_fit[iz] z_center = z_centerline[iz] # use of x in order to get orientation of each plane, basis_1 is in the plane ax+by+cz+d=0 basis_1 = normalize(np.cross(normal,x)) basis_2 = normalize(np.cross(normal,basis_1)) # maximum dimension of the tilted plane. Try multiply numerator by sqrt(2) ? max_diameter = (max([(max(X)-min(X))*x_scale,(max(Y)-min(Y))*y_scale]))/(np.cos(angle)) # Forcing the step to be the min of x and y scale (default value is 1 mm) step = min([x_scale,y_scale]) # discretized plane which will be filled with 0/1 plane_seg = np.zeros((int(max_diameter/step),int(max_diameter/step))) # how the plane will be skimmed through plane_grid = np.linspace(-int(max_diameter/2),int(max_diameter/2),int(max_diameter/step)) # we go through the plane for i_b1 in plane_grid : for i_b2 in plane_grid : point = np.array([x_center*x_scale,y_center*y_scale,z_center*z_scale]) + i_b1*basis_1 +i_b2*basis_2 # to which voxel belongs each point of the plane coord_voxel = str([ int(point[0]/x_scale), int(point[1]/y_scale), int(point[2]/z_scale)]) #coord_voxel = [ int(point[0]/x_scale), int(point[1]/y_scale), int(point[2]/z_scale)] if (coord_voxel in coords_seg) is True : # if this voxel is 1 plane_seg[int((plane_grid==i_b1).nonzero()[0])][int((plane_grid==i_b2).nonzero()[0])] = 1 # number of voxels that are in the intersection of each plane and the nonzeros values of segmentation, times the area of one cell of the discretized plane if name_method == 'counting_ortho_plane': sections_ortho_counting[iz] = len((plane_seg>0).nonzero()[0])*step*step if verbose ==1 and name_method == 'counting_ortho_plane' : print('\nsection ' + str(sections_ortho_counting[iz])) if name_method == 'ellipse_ortho_plane' : os.chdir('JPG_Results') imsave('plane_ortho_' + str(iz) + '.jpg', plane_seg) # Tresholded gradient image mag = edge_detection('plane_ortho_' + str(iz) + '.jpg') #Coordinates of the contour x_contour,y_contour = (mag>0).nonzero() x_contour = x_contour*step y_contour = y_contour*step #Fitting an ellipse fit = Ellipse_fit(x_contour,y_contour) # Semi-minor axis, semi-major axis a_ellipse, b_ellipse = ellipse_dim(fit) #Section = pi*a*b sections_ortho_ellipse[iz] = a_ellipse*b_ellipse*np.pi if verbose == 1 and name_method == 'ellipse_ortho_plane': print('\nsection ' + str(sections_ortho_ellipse[iz])) os.chdir('..') if name_method == 'counting_z_plane' or name_method == 'ellipse_z_plane': # getting the segmentation for each z plane x_seg, y_seg = (data_seg[:,:,iz+min_z_index]>0).nonzero() seg = [[x_seg[i],y_seg[i]] for i in range(0,len(x_seg))] plane=np.zeros((max(Xp),max(Yp))) for i in seg: # filling the plane with 0 and 1 regarding to the segmentation plane[i[0] - 1][i[1] - 1] = 1 if name_method == 'counting_z_plane' : sections_z_counting[iz] = len((plane>0).nonzero()[0])*x_scale*y_scale*np.cos(angle) if verbose == 1 and name_method == 'counting_z_plane': print('\nsection ' + str(sections_z_counting[iz])) if name_method == 'ellipse_z_plane': os.chdir('JPG_Results') imsave('plane_z_' + str(iz) + '.jpg', plane) # Tresholded gradient image mag = edge_detection('plane_z_' + str(iz) + '.jpg') x_contour,y_contour = (mag>0).nonzero() x_contour = x_contour*x_scale y_contour = y_contour*y_scale # Fitting an ellipse fit = Ellipse_fit(x_contour,y_contour) a_ellipse, b_ellipse = ellipse_dim(fit) sections_z_ellipse[iz] = a_ellipse*b_ellipse*np.pi*np.cos(angle) if verbose == 1 and name_method == 'ellipse_z_plane': print('\nsection ' + str(sections_z_ellipse[iz])) os.chdir('..') # come back to parent folder os.chdir('..') # Creating output text file if name_method == 'counting_ortho_plane' : print('\nGenerating output text file...\n') file_results = open('Cross_Section_Area_ortho_counting.txt','w') file_results.write('List of Cross Section Areas for each z slice\n') for i in range(min_z_index, max_z_index+1): file_results.write('\nz = ' + str(i*z_scale) + ' mm -> CSA = ' + str(sections_ortho_counting[i-min_z_index]) + ' mm^2') file_results.close() if name_method == 'ellipse_ortho_plane' : print('\nGenerating output text file...\n') file_results = open('Cross_Section_Area_ortho_ellipse.txt','w') file_results.write('List of Cross Section Areas for each z slice\n') for i in range(min_z_index, max_z_index+1): file_results.write('\nz = ' + str(i*z_scale) + ' mm -> CSA = ' + str(sections_ortho_ellipse[i-min_z_index]) + ' mm^2') file_results.close() if name_method == 'ellipse_z_plane' : print('\nGenerating output text file...\n') file_results = open('Cross_Section_Area_z_ellipse.txt','w') file_results.write('List of Cross Section Areas for each z slice\n') for i in range(min_z_index, max_z_index+1): file_results.write('\nz = ' + str(i*z_scale) + ' mm -> CSA = ' + str(sections_z_ellipse[i-min_z_index]) + ' mm^2') file_results.close() if name_method == 'counting_z_plane' : print('\nGenerating output text file...\n') file_results = open('Cross_Section_Area_z_counting.txt','w') file_results.write('List of Cross Section Areas for each z slice\n') for i in range(min_z_index, max_z_index+1): file_results.write('\nz = ' + str(i*z_scale) + ' mm -> CSA = ' + str(sections_z_counting[i-min_z_index]) + ' mm^2') file_results.close() # if name_method == 'counting_z_plane': # fig=plt.figure() # plt.plot(z_centerline*z_scale,sections_z_counting) # plt.show() # if name_method == 'counting_ortho_plane': # fig=plt.figure() # plt.plot(z_centerline*z_scale,sections_ortho_counting) # plt.show() # if name_method == 'ellipse_z_plane': # fig=plt.figure() # plt.plot(z_centerline*z_scale,sections_z_ellipse) # plt.show() # if name_method == 'ellipse_ortho_plane': # fig=plt.figure() # plt.plot(z_centerline*z_scale,sections_ortho_ellipse) # plt.show() # if volume_output == 1 : # Extract orientation of the input segmentation status,sct_orientation_output = sct.run('sct_orientation -i '+path_data_seg+file_data_seg+ext_data_seg + ' -get') orientation = sct_orientation_output[-3:] for iz in range(0,len(z_centerline)): x_seg, y_seg = (data_seg[:,:,iz]>0).nonzero() seg = [[x_seg[i],y_seg[i]] for i in range(0,len(x_seg))] for i in seg : if name_method == 'counting_ortho_plane': data_seg[i[0],i[1],iz] = sections_ortho_counting[iz] if name_method == 'counting_z_plane': data_seg[i[0],i[1],iz] = sections_z_counting[iz] if name_method == 'ellipse_ortho_plane': data_seg[i[0],i[1],iz] = sections_ortho_ellipse[iz] if name_method == 'ellipse_z_plane': data_seg[i[0],i[1],iz] = sections_z_ellipse[iz] hdr_seg.set_data_dtype('uint8') # set imagetype to uint8 print '\nWrite NIFTI volumes...' img = nibabel.Nifti1Image(data_seg, None, hdr_seg) file_name = path_tmp+'/'+file_data_seg+'_CSA_slices_rpi'+ext_data_seg nibabel.save(img,file_name) print '.. File created:' + file_name # Change orientation of the output centerline into input orientation print '\nOrient image to input orientation: ' sct.run('sct_orientation -i '+path_tmp+'/'+file_data_seg+'_CSA_slices_rpi'+ext_data_seg + ' -o ' + file_data_seg+'_CSA_slices'+ext_data_seg + ' -orientation ' + orientation) del data_seg # Remove temporary files if remove_temp_files == 1 : print('\nRemove temporary files...') sct.run('rm -rf '+path_tmp) # End of compute_CSA #======================================================================================================================= # B-Spline fitting #======================================================================================================================= def b_spline_centerline(x_centerline,y_centerline,z_centerline): print '\nFitting centerline using B-spline approximation...' points = [[x_centerline[n],y_centerline[n],z_centerline[n]] for n in range(len(x_centerline))] nurbs = NURBS(3,3000,points) # BE very careful with the spline order that you choose : if order is too high ( > 4 or 5) you need to set a higher number of Control Points (cf sct_nurbs ). For the third argument (number of points), give at least len(z_centerline)+500 or higher P = nurbs.getCourbe3D() x_centerline_fit=P[0] y_centerline_fit=P[1] Q = nurbs.getCourbe3D_deriv() x_centerline_deriv=Q[0] y_centerline_deriv=Q[1] z_centerline_deriv=Q[2] return x_centerline_fit, y_centerline_fit,x_centerline_deriv,y_centerline_deriv,z_centerline_deriv #======================================================================================================================= # Normalization #======================================================================================================================= def normalize(vect): norm=np.linalg.norm(vect) return vect/norm #======================================================================================================================= # Ellipse fitting for a set of data #======================================================================================================================= #http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html def Ellipse_fit(x,y): x = x[:,np.newaxis] y = y[:,np.newaxis] D = np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x))) S = np.dot(D.T,D) C = np.zeros([6,6]) C[0,2] = C[2,0] = 2 C[1,1] = -1 E, V = eig(np.dot(inv(S), C)) n = np.argmax(np.abs(E)) a = V[:,n] return a #======================================================================================================================= # Getting a and b parameter for fitted ellipse #======================================================================================================================= def ellipse_dim(a): b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0] up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g) down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a)) down2=(b*b-a*c)*( (a-c)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a)) res1=np.sqrt(up/down1) res2=np.sqrt(up/down2) return np.array([res1, res2]) #======================================================================================================================= # Detect edges of an image #======================================================================================================================= def edge_detection(f) : #sigma = 1.0 img = Image.open(f) #grayscale imgdata = np.array(img, dtype = float) G = imgdata #G = ndi.filters.gaussian_filter(imgdata, sigma) gradx = np.array(G, dtype = float) grady = np.array(G, dtype = float) mask_x = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) mask_y = np.array([[1,2,1],[0,0,0],[-1,-2,-1]]) width = img.size[1] height = img.size[0] for i in range(1, width-1): for j in range(1, height-1): px = np.sum(mask_x*G[(i-1):(i+1)+1,(j-1):(j+1)+1]) py = np.sum(mask_y*G[(i-1):(i+1)+1,(j-1):(j+1)+1]) gradx[i][j] = px grady[i][j] = py mag = scipy.hypot(gradx,grady) treshold = np.max(mag)*0.9 for i in range(width): for j in range(height): if mag[i][j]>treshold: mag[i][j]=1 else: mag[i][j] = 0 return mag # Print usage # ========================================================================================== def usage(): print '\n' \ ''+os.path.basename(__file__)+'\n' \ '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' \ 'Part of the Spinal Cord Toolbox <https://sourceforge.net/projects/spinalcordtoolbox>\n' \ '\n'\ 'DESCRIPTION\n' \ ' This function performs various types of processing from the spinal cord segmentation, e.g.,\n' \ ' extract centerline, compute cross-sectional area (CSA).\n' \ '\n' \ 'USAGE\n' \ ' '+os.path.basename(__file__)+' -i <segmentation> -p <process>\n' \ '\n' \ 'MANDATORY ARGUMENTS\n' \ ' -i <segmentation> spinal cord segmentation (e.g., use sct_segmentation_propagation)\n' \ ' -p <process> type of process to be performed {extract_centerline}, {compute_CSA}\n' \ ' -m <method_CSA> if process is "compute_CSA", the following methods are available:\n' \ ' counting_ortho_plane: resample planes orthogonal to centerline and count\n' \ ' pixels in each plane.\n' \ ' counting_z_plane: count pixels in each slice and then geometrically\n' \ ' adjust using centerline orientation.\n' \ ' ellipse_ortho_plane: same process as counting_ortho_plane, but fit\n' \ ' ellipse instead of counting pixels.\n' \ ' ellipse_z_plane: same process as counting_z_plane, but fit ellipse\n' \ ' instead of counting pixels.\n' \ '\n' \ 'OPTIONAL ARGUMENTS\n' \ ' -v <0,1> verbose. Default='+str(param.verbose)+'.\n' \ ' -b <0,1> outputs a volume in which each slice\'s value is equal to the CSA in\n' \ ' mm^2. Default = 0\n' \ '\n' \ 'EXAMPLE\n' \ ' sct_process_segmentation.py -i binary_segmentation.nii.gz -p compute_CSA -m counting_z_plane\n' # exit program sys.exit(2) # START PROGRAM # ========================================================================================= if __name__ == "__main__": # initialize parameters param = param() # call main function main()
import speech_recognition as sr import cv2 import subprocess import sys def say(phrase): if phrase == "purpose": subprocess.Popen(['mpg123', 'resources/whatismypurpose.mp3']) elif phrase == "ohmygod": subprocess.Popen(['mpg123', 'resources/ohmygod.mp3']) def getState(): return curstate def speechCallback(recognizer, audio): try: curstate = getState() print curstate words = recognizer.recognize_google(audio) print("butterbot heard " + words) if "pass the butter" in words and curstate == "inquisition": curstate = "search_for_butter" elif "you pass butter" in words and curstate == "inquisition": say("ohmygod") curstate = "existential_crisis" else: print("not in dictionary") except sr.UnknownValueError: print("didn't catch that..." + repr(sys.exc_info()[0])) def setupSpeech(): r = sr.Recognizer() m = sr.Microphone() with m as source: r.adjust_for_ambient_noise(source) stop_listening = r.listen_in_background(m, speechCallback) def main(): global curstate curstate = "waiting" print("Initializing butterbot") print("Initializing speech module") setupSpeech() print("setup success") print("initializing camera module") say("purpose") curstate = "inquisition" print curstate while True: if curstate == "waiting": pass elif curstate == "inquisition": pass elif curstate == "search_for_butter": pass elif curstate == "go_to_butter": pass elif curstate == "grab_butter": pass elif curstate == "return_butter": pass elif curstate == "existential_crisis": pass if __name__=="__main__": main() added camera as a thread import speech_recognition as sr import cv2 import subprocess import sys from threading import Thread import find_butter def say(phrase): if phrase == "purpose": subprocess.Popen(['mpg123', 'resources/whatismypurpose.mp3']) elif phrase == "ohmygod": subprocess.Popen(['mpg123', 'resources/ohmygod.mp3']) def getState(): return curstate def speechCallback(recognizer, audio): try: curstate = getState() print curstate words = recognizer.recognize_google(audio) print("butterbot heard " + words) if "pass the butter" in words and curstate == "inquisition": curstate = "search_for_butter" elif "you pass butter" in words and curstate == "inquisition": say("ohmygod") curstate = "existential_crisis" else: print("not in dictionary") except sr.UnknownValueError: print("didn't catch that..." + repr(sys.exc_info()[0])) def setupSpeech(): r = sr.Recognizer() m = sr.Microphone() with m as source: r.adjust_for_ambient_noise(source) stop_listening = r.listen_in_background(m, speechCallback) def main(): global curstate curstate = "waiting" print("Initializing butterbot") print("Initializing speech module") setupSpeech() print("setup success") print("initializing camera module") tag = find_butter.tagpos() findbutter = Thread(target=find_butter.findButter, args=(tag,)) findbutter.setDaemon(True) findbutter.start() say("purpose") curstate = "inquisition" print curstate while True: if curstate == "waiting": pass elif curstate == "inquisition": pass elif curstate == "search_for_butter": pass elif curstate == "go_to_butter": pass elif curstate == "grab_butter": pass elif curstate == "return_butter": pass elif curstate == "existential_crisis": pass if __name__=="__main__": main()
#!/usr/bin/env python ######################################################################################### # # Register anatomical image to the template using the spinal cord centerline/segmentation. # # --------------------------------------------------------------------------------------- # Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: Benjamin De Leener, Julien Cohen-Adad, Augustin Roux # # About the license: see the file LICENSE.TXT ######################################################################################### # TODO: for -ref subject, crop data, otherwise registration is too long # TODO: testing script for all cases import sys import os import shutil import commands import time from glob import glob import sct_utils as sct from sct_utils import add_suffix from sct_image import set_orientation from sct_register_multimodal import Paramreg, ParamregMultiStep, register from msct_parser import Parser from msct_image import Image, find_zmin_zmax from shutil import move from sct_label_utils import ProcessLabels import numpy as np # get path of the toolbox path_script = os.path.dirname(__file__) path_sct = os.path.dirname(path_script) # DEFAULT PARAMETERS class Param: ## The constructor def __init__(self): self.debug = 0 self.remove_temp_files = 1 # remove temporary files self.fname_mask = '' # this field is needed in the function register@sct_register_multimodal self.padding = 10 # this field is needed in the function register@sct_register_multimodal self.verbose = 1 # verbose self.path_template = path_sct+'/data/PAM50' self.path_qc = os.path.abspath(os.curdir)+'/qc/' self.zsubsample = '0.25' self.param_straighten = '' # get default parameters # Note: step0 is used as pre-registration step0 = Paramreg(step='0', type='label', dof='Tx_Ty_Tz_Sz') # if ref=template, we only need translations and z-scaling because the cord is already straight step1 = Paramreg(step='1', type='seg', algo='centermassrot', smooth='2') # step2 = Paramreg(step='2', type='seg', algo='columnwise', smooth='0', smoothWarpXY='2') step2 = Paramreg(step='2', type='seg', algo='bsplinesyn', metric='MeanSquares', iter='3', smooth='1') # step3 = Paramreg(step='3', type='im', algo='syn', metric='CC', iter='1') paramreg = ParamregMultiStep([step0, step1, step2]) # PARSER # ========================================================================================== def get_parser(): param = Param() parser = Parser(__file__) parser.usage.set_description('Register anatomical image to the template.') parser.add_option(name="-i", type_value="file", description="Anatomical image.", mandatory=True, example="anat.nii.gz") parser.add_option(name="-s", type_value="file", description="Spinal cord segmentation.", mandatory=True, example="anat_seg.nii.gz") parser.add_option(name="-l", type_value="file", description="Labels. See: http://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels\n", mandatory=False, default_value='labels_reoriented.nii.gz', example="anat_labels.nii.gz") parser.add_option(name="-ofolder", type_value="folder_creation", description="Output folder.", mandatory=False, default_value='') parser.add_option(name="-t", type_value="folder", description="Path to template.", mandatory=False, default_value=param.path_template) parser.add_option(name='-c', type_value='multiple_choice', description='Contrast to use for registration.', mandatory=False, default_value='t2', example=['t1', 't2', 't2s']) parser.add_option(name='-ref', type_value='multiple_choice', description='Reference for registration: template: subject->template, subject: template->subject.', mandatory=False, default_value='template', example=['template', 'subject']) parser.add_option(name="-param", type_value=[[':'], 'str'], description='Parameters for registration (see sct_register_multimodal). Default: \ \n--\nstep=0\ntype=' + paramreg.steps['0'].type + '\ndof=' + paramreg.steps['0'].dof + '\ \n--\nstep=1\ntype=' + paramreg.steps['1'].type + '\nalgo=' + paramreg.steps['1'].algo + '\nmetric=' + paramreg.steps['1'].metric + '\niter=' + paramreg.steps['1'].iter + '\nsmooth=' + paramreg.steps['1'].smooth + '\ngradStep=' + paramreg.steps['1'].gradStep + '\nslicewise=' + paramreg.steps['1'].slicewise + '\nsmoothWarpXY=' + paramreg.steps['1'].smoothWarpXY + '\npca_eigenratio_th=' + paramreg.steps['1'].pca_eigenratio_th + '\ \n--\nstep=2\ntype=' + paramreg.steps['2'].type + '\nalgo=' + paramreg.steps['2'].algo + '\nmetric=' + paramreg.steps['2'].metric + '\niter=' + paramreg.steps['2'].iter + '\nsmooth=' + paramreg.steps['2'].smooth + '\ngradStep=' + paramreg.steps['2'].gradStep + '\nslicewise=' + paramreg.steps['2'].slicewise + '\nsmoothWarpXY=' + paramreg.steps['2'].smoothWarpXY + '\npca_eigenratio_th=' + paramreg.steps['1'].pca_eigenratio_th, mandatory=False) parser.add_option(name="-param-straighten", type_value='str', description="""Parameters for straightening (see sct_straighten_spinalcord).""", mandatory=False, default_value='') # parser.add_option(name="-cpu-nb", # type_value="int", # description="Number of CPU used for straightening. 0: no multiprocessing. By default, uses all the available cores.", # mandatory=False, # example="8") parser.add_option(name="-init-template", type_value="multiple_choice", description="You can create your own labels using a interactive viewer using option 'viewer", mandatory=False, default_value='0', example=['0', '1']) parser.add_option(name="-r", type_value="multiple_choice", description="""Remove temporary files.""", mandatory=False, default_value='1', example=['0', '1']) parser.add_option(name="-v", type_value="multiple_choice", description="""Verbose. 0: nothing. 1: basic. 2: extended.""", mandatory=False, default_value=param.verbose, example=['0', '1', '2']) return parser def rewrite_arguments(arguments): fname_data = arguments['-i'] fname_seg = arguments['-s'] fname_landmarks = arguments['-l'] if '-ofolder' in arguments: path_output = arguments['-ofolder'] else: path_output = '' path_template = sct.slash_at_the_end(arguments['-t'], 1) contrast_template = arguments['-c'] ref = arguments['-ref'] remove_temp_files = int(arguments['-r']) verbose = int(arguments['-v']) init_template=int(arguments['-init-template']) return (fname_data,fname_seg,fname_landmarks,path_output,path_template,contrast_template,ref,remove_temp_files,verbose,init_template) def write_paramaters(arguments,param,ref,verbose): param.verbose = verbose if '-param-straighten' in arguments: param.param_straighten = arguments['-param-straighten'] """ if '-cpu-nb' in arguments: arg_cpu = ' -cpu-nb '+str(arguments['-cpu-nb']) else: arg_cpu = '' registration parameters """ if '-param' in arguments: # reset parameters but keep step=0 (might be overwritten if user specified step=0) paramreg = ParamregMultiStep([step0]) if ref == 'subject': paramreg.steps['0'].dof = 'Tx_Ty_Tz_Rx_Ry_Rz_Sz' # add user parameters for paramStep in arguments['-param']: paramreg.addStep(paramStep) else: paramreg = ParamregMultiStep([step0, step1, step2]) # if ref=subject, initialize registration using different affine parameters if ref == 'subject': paramreg.steps['0'].dof = 'Tx_Ty_Tz_Rx_Ry_Rz_Sz' return (param,paramreg) def check_do_files_exist(fname_template,fname_template_vertebral_labeling,fname_template_seg,verbose): # TODO: no need to do that! sct.printv('\nCheck template files...') sct.check_file_exist(fname_template, verbose) sct.check_file_exist(fname_template_vertebral_labeling, verbose) sct.check_file_exist(fname_template_seg, verbose) def make_fname_of_templates(file_template,path_template,file_template_vertebral_labeling,file_template_seg): fname_template = path_template+'template/'+file_template fname_template_vertebral_labeling = path_template+'template/'+file_template_vertebral_labeling fname_template_seg = path_template+'template/'+file_template_seg return(fname_template,fname_template_vertebral_labeling,fname_template_seg) def print_arguments(verbose,fname_data,fname_landmarks,fname_seg,path_template,remove_temp_files): sct.printv('\nCheck parameters:', verbose) sct.printv(' Data: '+fname_data, verbose) sct.printv(' Landmarks: '+fname_landmarks, verbose) sct.printv(' Segmentation: '+fname_seg, verbose) sct.printv(' Path template: '+path_template, verbose) sct.printv(' Remove temp files: '+str(remove_temp_files), verbose) def check_data_segmentation_landmarks_same_space(fname_data,fname_seg,fname_landmarks,verbose): sct.printv('\nCheck if data, segmentation and landmarks are in the same space...') path_data, file_data, ext_data = sct.extract_fname(fname_data) if not sct.check_if_same_space(fname_data, fname_seg): sct.printv('ERROR: Data image and segmentation are not in the same space. Please check space and orientation of your files', verbose, 'error') if not sct.check_if_same_space(fname_data, fname_landmarks): sct.printv('ERROR: Data image and landmarks are not in the same space. Please check space and orientation of your files', verbose, 'error') return (ext_data,path_data,file_data) def set_temporary_files(): ftmp_data = 'data.nii' ftmp_seg = 'seg.nii.gz' ftmp_label = 'label.nii.gz' ftmp_template = 'template.nii' ftmp_template_seg = 'template_seg.nii.gz' ftmp_template_label = 'template_label.nii.gz' return(ftmp_data,ftmp_seg,ftmp_label,ftmp_template,ftmp_template_seg,ftmp_template_label) def copy_files_to_temporary_files(verbose,fname_data,path_tmp,ftmp_seg,ftmp_data,fname_seg,fname_landmarks,ftmp_label,fname_template,ftmp_template,fname_template_seg,ftmp_template_seg): sct.printv('\nCopying input data to tmp folder and convert to nii...', verbose) sct.run('sct_convert -i '+fname_data+' -o '+path_tmp+ftmp_data) sct.run('sct_convert -i '+fname_seg+' -o '+path_tmp+ftmp_seg) sct.run('sct_convert -i '+fname_landmarks+' -o '+path_tmp+ftmp_label) sct.run('sct_convert -i '+fname_template+' -o '+path_tmp+ftmp_template) sct.run('sct_convert -i '+fname_template_seg+' -o '+path_tmp+ftmp_template_seg) # sct.run('sct_convert -i '+fname_template_label+' -o '+path_tmp+ftmp_template_label) def set_viewer_parameters(viewer): viewer.number_of_slices = 1 pz = 1 viewer.gap_inter_slice = int(10 / pz) viewer.calculate_list_slices() viewer.help_url = 'https://sourceforge.net/p/spinalcordtoolbox/wiki/sct_label_vertebrae/attachment/label_vertebrae_viewer.png' def prepare_input_image_for_viewer(fname_data): # reorient image to SAL to be compatible with viewer im_input = Image(fname_data) im_input_SAL = im_input.copy() im_input_SAL.change_orientation('SAL') return(im_input_SAL) def check_mask_point_not_empty(mask_points): if(mask_points): return True else: sct.printv('\nERROR: the viewer has been closed before entering all manual points. Please try again.', 1, type='error') return False def use_viewer_to_define_labels(fname_data): from sct_viewer import ClickViewerRegisterToTemplate from msct_image import Image import sct_image image_input = Image(fname_data) image_input_orientation = sct_image.orientation(image_input, get=True, verbose=False) reoriented_image_filename = 'reoriented_image_source.nii.gz' path_tmp_viewer = sct.tmp_create(verbose=False) cmd_image = 'sct_image -i "%s" -o "%s" -setorient SAL -v 0' % ( fname_data, reoriented_image_filename) sct.run(cmd_image, verbose=False) im_input_SAL=prepare_input_image_for_viewer(fname_data) viewer = ClickViewerRegisterToTemplate(im_input_SAL, orientation_subplot=['sag', 'ax']) set_viewer_parameters(viewer) mask_points = viewer.start() #if not mask_points and viewer.closed: # mask_points = viewer.list_points_useful_notation #if check_mask_point_not_empty(mask_points): if True: print(0) import sct_image # create the mask containing either the three-points or centerline mask for initialization sct.run("sct_label_utils -i " + reoriented_image_filename + " -create " + mask_points ,verbose=False) print(1) sct.run('sct_image -i ' + 'labels.nii.gz'+ ' -o ' + 'labels_reoriented.nii.gz' + ' -setorient ' + image_input_orientation + ' -v 0',verbose=False) print(2) # reorient the initialization mask to correspond to input image orientation #mask_reoriented_filename = sct.add_suffix(file_data + ext_data, "_mask_viewer") #sct.run( #'sct_image -i ' + path_tmp_viewer + mask_filename + ' -o ' + folder_output + mask_reoriented_filename + ' -setorient ' + image_input_orientation + ' -v 0', #verbose=False) # MAIN # ========================================================================================== def main(): parser = get_parser() param = Param() print(sys.argv[1:]) """ Rewrite arguments and set parameters""" arguments = parser.parse(sys.argv[1:]) (fname_data, fname_seg, fname_landmarks, path_output, path_template, contrast_template, ref, remove_temp_files,verbose,init_template)=rewrite_arguments(arguments) (param, paramreg)=write_paramaters(arguments,param,ref,verbose) if(init_template): use_viewer_to_define_labels(fname_data) # initialize other parameters # file_template_label = param.file_template_label zsubsample = param.zsubsample template = os.path.basename(os.path.normpath(path_template)) # smoothing_sigma = param.smoothing_sigma # retrieve template file names from sct_warp_template import get_file_label file_template_vertebral_labeling = get_file_label(path_template+'template/', 'vertebral') file_template = get_file_label(path_template+'template/', contrast_template.upper()+'-weighted') file_template_seg = get_file_label(path_template+'template/', 'spinal cord') """ Start timer""" start_time = time.time() """ Manage file of templates""" (fname_template, fname_template_vertebral_labeling, fname_template_seg)=make_fname_of_templates(file_template,path_template,file_template_vertebral_labeling,file_template_seg) check_do_files_exist(fname_template,fname_template_vertebral_labeling,fname_template_seg,verbose) print_arguments(verbose, fname_data, fname_landmarks, fname_seg, path_template, remove_temp_files) """ Create QC folder """ sct.create_folder(param.path_qc) """ Check if data, segmentation and landmarks are in the same space""" (ext_data, path_data, file_data)=check_data_segmentation_landmarks_same_space(fname_data, fname_seg, fname_landmarks,verbose) ''' Check input labels''' labels = check_labels(fname_landmarks) """ create temporary folder, set temporary file names, copy files into it and go in it """ path_tmp = sct.tmp_create(verbose=verbose) (ftmp_data, ftmp_seg, ftmp_label, ftmp_template, ftmp_template_seg, ftmp_template_label)=set_temporary_files() copy_files_to_temporary_files(verbose, fname_data, path_tmp, ftmp_seg, ftmp_data, fname_seg, fname_landmarks, ftmp_label, fname_template, ftmp_template, fname_template_seg, ftmp_template_seg) os.chdir(path_tmp) ''' Generate labels from template vertebral labeling''' sct.printv('\nGenerate labels from template vertebral labeling', verbose) sct.run('sct_label_utils -i '+fname_template_vertebral_labeling+' -vert-body 0 -o '+ftmp_template_label) ''' check if provided labels are available in the template''' sct.printv('\nCheck if provided labels are available in the template', verbose) image_label_template = Image(ftmp_template_label) labels_template = image_label_template.getNonZeroCoordinates(sorting='value') if labels[-1].value > labels_template[-1].value: sct.printv('ERROR: Wrong landmarks input. Labels must have correspondence in template space. \nLabel max ' 'provided: ' + str(labels[-1].value) + '\nLabel max from template: ' + str(labels_template[-1].value), verbose, 'error') ''' binarize segmentation (in case it has values below 0 caused by manual editing)''' sct.printv('\nBinarize segmentation', verbose) sct.run('sct_maths -i seg.nii.gz -bin 0.5 -o seg.nii.gz') # smooth segmentation (jcohenadad, issue #613) # sct.printv('\nSmooth segmentation...', verbose) # sct.run('sct_maths -i '+ftmp_seg+' -smooth 1.5 -o '+add_suffix(ftmp_seg, '_smooth')) # jcohenadad: updated 2016-06-16: DO NOT smooth the seg anymore. Issue # # sct.run('sct_maths -i '+ftmp_seg+' -smooth 0 -o '+add_suffix(ftmp_seg, '_smooth')) # ftmp_seg = add_suffix(ftmp_seg, '_smooth') # Switch between modes: subject->template or template->subject if ref == 'template': # resample data to 1mm isotropic sct.printv('\nResample data to 1mm isotropic...', verbose) sct.run('sct_resample -i '+ftmp_data+' -mm 1.0x1.0x1.0 -x linear -o '+add_suffix(ftmp_data, '_1mm')) ftmp_data = add_suffix(ftmp_data, '_1mm') sct.run('sct_resample -i '+ftmp_seg+' -mm 1.0x1.0x1.0 -x linear -o '+add_suffix(ftmp_seg, '_1mm')) ftmp_seg = add_suffix(ftmp_seg, '_1mm') # N.B. resampling of labels is more complicated, because they are single-point labels, therefore resampling with neighrest neighbour can make them disappear. Therefore a more clever approach is required. resample_labels(ftmp_label, ftmp_data, add_suffix(ftmp_label, '_1mm')) ftmp_label = add_suffix(ftmp_label, '_1mm') # Change orientation of input images to RPI sct.printv('\nChange orientation of input images to RPI...', verbose) sct.run('sct_image -i '+ftmp_data+' -setorient RPI -o '+add_suffix(ftmp_data, '_rpi')) ftmp_data = add_suffix(ftmp_data, '_rpi') sct.run('sct_image -i '+ftmp_seg+' -setorient RPI -o '+add_suffix(ftmp_seg, '_rpi')) ftmp_seg = add_suffix(ftmp_seg, '_rpi') sct.run('sct_image -i '+ftmp_label+' -setorient RPI -o '+add_suffix(ftmp_label, '_rpi')) ftmp_label = add_suffix(ftmp_label, '_rpi') # get landmarks in native space # crop segmentation # output: segmentation_rpi_crop.nii.gz status_crop, output_crop = sct.run('sct_crop_image -i '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_crop')+' -dim 2 -bzmax', verbose) ftmp_seg = add_suffix(ftmp_seg, '_crop') cropping_slices = output_crop.split('Dimension 2: ')[1].split('\n')[0].split(' ') # straighten segmentation sct.printv('\nStraighten the spinal cord using centerline/segmentation...', verbose) # check if warp_curve2straight and warp_straight2curve already exist (i.e. no need to do it another time) if os.path.isfile('../warp_curve2straight.nii.gz') and os.path.isfile('../warp_straight2curve.nii.gz') and os.path.isfile('../straight_ref.nii.gz'): # if they exist, copy them into current folder sct.printv('WARNING: Straightening was already run previously. Copying warping fields...', verbose, 'warning') shutil.copy('../warp_curve2straight.nii.gz', 'warp_curve2straight.nii.gz') shutil.copy('../warp_straight2curve.nii.gz', 'warp_straight2curve.nii.gz') shutil.copy('../straight_ref.nii.gz', 'straight_ref.nii.gz') # apply straightening sct.run('sct_apply_transfo -i '+ftmp_seg+' -w warp_curve2straight.nii.gz -d straight_ref.nii.gz -o '+add_suffix(ftmp_seg, '_straight')) else: sct.run('sct_straighten_spinalcord -i '+ftmp_seg+' -s '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_straight')+' -qc 0 -r 0 -v '+str(verbose), verbose) # N.B. DO NOT UPDATE VARIABLE ftmp_seg BECAUSE TEMPORARY USED LATER # re-define warping field using non-cropped space (to avoid issue #367) sct.run('sct_concat_transfo -w warp_straight2curve.nii.gz -d '+ftmp_data+' -o warp_straight2curve.nii.gz') # Label preparation: # -------------------------------------------------------------------------------- # Remove unused label on template. Keep only label present in the input label image sct.printv('\nRemove unused label on template. Keep only label present in the input label image...', verbose) sct.run('sct_label_utils -i '+ftmp_template_label+' -o '+ftmp_template_label+' -remove '+ftmp_label) # Dilating the input label so they can be straighten without losing them sct.printv('\nDilating input labels using 3vox ball radius') sct.run('sct_maths -i '+ftmp_label+' -o '+add_suffix(ftmp_label, '_dilate')+' -dilate 3') ftmp_label = add_suffix(ftmp_label, '_dilate') # Apply straightening to labels sct.printv('\nApply straightening to labels...', verbose) sct.run('sct_apply_transfo -i '+ftmp_label+' -o '+add_suffix(ftmp_label, '_straight')+' -d '+add_suffix(ftmp_seg, '_straight')+' -w warp_curve2straight.nii.gz -x nn') ftmp_label = add_suffix(ftmp_label, '_straight') # Compute rigid transformation straight landmarks --> template landmarks sct.printv('\nEstimate transformation for step #0...', verbose) from msct_register_landmarks import register_landmarks try: register_landmarks(ftmp_label, ftmp_template_label, paramreg.steps['0'].dof, fname_affine='straight2templateAffine.txt', verbose=verbose) except Exception: sct.printv('ERROR: input labels do not seem to be at the right place. Please check the position of the labels. See documentation for more details: https://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels/', verbose=verbose, type='error') # Concatenate transformations: curve --> straight --> affine sct.printv('\nConcatenate transformations: curve --> straight --> affine...', verbose) sct.run('sct_concat_transfo -w warp_curve2straight.nii.gz,straight2templateAffine.txt -d template.nii -o warp_curve2straightAffine.nii.gz') # Apply transformation sct.printv('\nApply transformation...', verbose) sct.run('sct_apply_transfo -i '+ftmp_data+' -o '+add_suffix(ftmp_data, '_straightAffine')+' -d '+ftmp_template+' -w warp_curve2straightAffine.nii.gz') ftmp_data = add_suffix(ftmp_data, '_straightAffine') sct.run('sct_apply_transfo -i '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_straightAffine')+' -d '+ftmp_template+' -w warp_curve2straightAffine.nii.gz -x linear') ftmp_seg = add_suffix(ftmp_seg, '_straightAffine') """ # Benjamin: Issue from Allan Martin, about the z=0 slice that is screwed up, caused by the affine transform. # Solution found: remove slices below and above landmarks to avoid rotation effects points_straight = [] for coord in landmark_template: points_straight.append(coord.z) min_point, max_point = int(round(np.min(points_straight))), int(round(np.max(points_straight))) sct.run('sct_crop_image -i ' + ftmp_seg + ' -start ' + str(min_point) + ' -end ' + str(max_point) + ' -dim 2 -b 0 -o ' + add_suffix(ftmp_seg, '_black')) ftmp_seg = add_suffix(ftmp_seg, '_black') """ # binarize sct.printv('\nBinarize segmentation...', verbose) sct.run('sct_maths -i '+ftmp_seg+' -bin 0.5 -o '+add_suffix(ftmp_seg, '_bin')) ftmp_seg = add_suffix(ftmp_seg, '_bin') # find min-max of anat2template (for subsequent cropping) zmin_template, zmax_template = find_zmin_zmax(ftmp_seg) # crop template in z-direction (for faster processing) sct.printv('\nCrop data in template space (for faster processing)...', verbose) sct.run('sct_crop_image -i '+ftmp_template+' -o '+add_suffix(ftmp_template, '_crop')+' -dim 2 -start '+str(zmin_template)+' -end '+str(zmax_template)) ftmp_template = add_suffix(ftmp_template, '_crop') sct.run('sct_crop_image -i '+ftmp_template_seg+' -o '+add_suffix(ftmp_template_seg, '_crop')+' -dim 2 -start '+str(zmin_template)+' -end '+str(zmax_template)) ftmp_template_seg = add_suffix(ftmp_template_seg, '_crop') sct.run('sct_crop_image -i '+ftmp_data+' -o '+add_suffix(ftmp_data, '_crop')+' -dim 2 -start '+str(zmin_template)+' -end '+str(zmax_template)) ftmp_data = add_suffix(ftmp_data, '_crop') sct.run('sct_crop_image -i '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_crop')+' -dim 2 -start '+str(zmin_template)+' -end '+str(zmax_template)) ftmp_seg = add_suffix(ftmp_seg, '_crop') # sub-sample in z-direction sct.printv('\nSub-sample in z-direction (for faster processing)...', verbose) sct.run('sct_resample -i '+ftmp_template+' -o '+add_suffix(ftmp_template, '_sub')+' -f 1x1x'+zsubsample, verbose) ftmp_template = add_suffix(ftmp_template, '_sub') sct.run('sct_resample -i '+ftmp_template_seg+' -o '+add_suffix(ftmp_template_seg, '_sub')+' -f 1x1x'+zsubsample, verbose) ftmp_template_seg = add_suffix(ftmp_template_seg, '_sub') sct.run('sct_resample -i '+ftmp_data+' -o '+add_suffix(ftmp_data, '_sub')+' -f 1x1x'+zsubsample, verbose) ftmp_data = add_suffix(ftmp_data, '_sub') sct.run('sct_resample -i '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_sub')+' -f 1x1x'+zsubsample, verbose) ftmp_seg = add_suffix(ftmp_seg, '_sub') # Registration straight spinal cord to template sct.printv('\nRegister straight spinal cord to template...', verbose) # loop across registration steps warp_forward = [] warp_inverse = [] for i_step in range(1, len(paramreg.steps)): sct.printv('\nEstimate transformation for step #'+str(i_step)+'...', verbose) # identify which is the src and dest if paramreg.steps[str(i_step)].type == 'im': src = ftmp_data dest = ftmp_template interp_step = 'linear' elif paramreg.steps[str(i_step)].type == 'seg': src = ftmp_seg dest = ftmp_template_seg interp_step = 'nn' else: sct.printv('ERROR: Wrong image type.', 1, 'error') # if step>1, apply warp_forward_concat to the src image to be used if i_step > 1: # sct.run('sct_apply_transfo -i '+src+' -d '+dest+' -w '+','.join(warp_forward)+' -o '+sct.add_suffix(src, '_reg')+' -x '+interp_step, verbose) # apply transformation from previous step, to use as new src for registration sct.run('sct_apply_transfo -i '+src+' -d '+dest+' -w '+','.join(warp_forward)+' -o '+add_suffix(src, '_regStep'+str(i_step-1))+' -x '+interp_step, verbose) src = add_suffix(src, '_regStep'+str(i_step-1)) # register src --> dest # TODO: display param for debugging warp_forward_out, warp_inverse_out = register(src, dest, paramreg, param, str(i_step)) warp_forward.append(warp_forward_out) warp_inverse.append(warp_inverse_out) # Concatenate transformations: sct.printv('\nConcatenate transformations: anat --> template...', verbose) sct.run('sct_concat_transfo -w warp_curve2straightAffine.nii.gz,'+','.join(warp_forward)+' -d template.nii -o warp_anat2template.nii.gz', verbose) # sct.run('sct_concat_transfo -w warp_curve2straight.nii.gz,straight2templateAffine.txt,'+','.join(warp_forward)+' -d template.nii -o warp_anat2template.nii.gz', verbose) sct.printv('\nConcatenate transformations: template --> anat...', verbose) warp_inverse.reverse() sct.run('sct_concat_transfo -w '+','.join(warp_inverse)+',-straight2templateAffine.txt,warp_straight2curve.nii.gz -d data.nii -o warp_template2anat.nii.gz', verbose) # register template->subject elif ref == 'subject': # Change orientation of input images to RPI sct.printv('\nChange orientation of input images to RPI...', verbose) sct.run('sct_image -i ' + ftmp_data + ' -setorient RPI -o ' + add_suffix(ftmp_data, '_rpi')) ftmp_data = add_suffix(ftmp_data, '_rpi') sct.run('sct_image -i ' + ftmp_seg + ' -setorient RPI -o ' + add_suffix(ftmp_seg, '_rpi')) ftmp_seg = add_suffix(ftmp_seg, '_rpi') sct.run('sct_image -i ' + ftmp_label + ' -setorient RPI -o ' + add_suffix(ftmp_label, '_rpi')) ftmp_label = add_suffix(ftmp_label, '_rpi') # Remove unused label on template. Keep only label present in the input label image sct.printv('\nRemove unused label on template. Keep only label present in the input label image...', verbose) sct.run('sct_label_utils -i '+ftmp_template_label+' -o '+ftmp_template_label+' -remove '+ftmp_label) # Add one label because at least 3 orthogonal labels are required to estimate an affine transformation. This new label is added at the level of the upper most label (lowest value), at 1cm to the right. for i_file in [ftmp_label, ftmp_template_label]: im_label = Image(i_file) coord_label = im_label.getCoordinatesAveragedByValue() # N.B. landmarks are sorted by value # Create new label from copy import deepcopy new_label = deepcopy(coord_label[0]) # move it 5mm to the left (orientation is RAS) nx, ny, nz, nt, px, py, pz, pt = im_label.dim new_label.x = round(coord_label[0].x + 5.0 / px) # assign value 99 new_label.value = 99 # Add to existing image im_label.data[int(new_label.x), int(new_label.y), int(new_label.z)] = new_label.value # Overwrite label file # im_label.setFileName('label_rpi_modif.nii.gz') im_label.save() # Bring template to subject space using landmark-based transformation sct.printv('\nEstimate transformation for step #0...', verbose) from msct_register_landmarks import register_landmarks warp_forward = ['template2subjectAffine.txt'] warp_inverse = ['-template2subjectAffine.txt'] try: register_landmarks(ftmp_template_label, ftmp_label, paramreg.steps['0'].dof, fname_affine=warp_forward[0], verbose=verbose, path_qc=param.path_qc) except Exception: sct.printv('ERROR: input labels do not seem to be at the right place. Please check the position of the labels. See documentation for more details: https://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels/', verbose=verbose, type='error') # loop across registration steps for i_step in range(1, len(paramreg.steps)): sct.printv('\nEstimate transformation for step #'+str(i_step)+'...', verbose) # identify which is the src and dest if paramreg.steps[str(i_step)].type == 'im': src = ftmp_template dest = ftmp_data interp_step = 'linear' elif paramreg.steps[str(i_step)].type == 'seg': src = ftmp_template_seg dest = ftmp_seg interp_step = 'nn' else: sct.printv('ERROR: Wrong image type.', 1, 'error') # apply transformation from previous step, to use as new src for registration sct.run('sct_apply_transfo -i '+src+' -d '+dest+' -w '+','.join(warp_forward)+' -o '+add_suffix(src, '_regStep'+str(i_step-1))+' -x '+interp_step, verbose) src = add_suffix(src, '_regStep'+str(i_step-1)) # register src --> dest # TODO: display param for debugging warp_forward_out, warp_inverse_out = register(src, dest, paramreg, param, str(i_step)) warp_forward.append(warp_forward_out) warp_inverse.insert(0, warp_inverse_out) # Concatenate transformations: sct.printv('\nConcatenate transformations: template --> subject...', verbose) sct.run('sct_concat_transfo -w '+','.join(warp_forward)+' -d data.nii -o warp_template2anat.nii.gz', verbose) sct.printv('\nConcatenate transformations: subject --> template...', verbose) sct.run('sct_concat_transfo -w '+','.join(warp_inverse)+' -d template.nii -o warp_anat2template.nii.gz', verbose) # Apply warping fields to anat and template sct.run('sct_apply_transfo -i template.nii -o template2anat.nii.gz -d data.nii -w warp_template2anat.nii.gz -crop 1', verbose) sct.run('sct_apply_transfo -i data.nii -o anat2template.nii.gz -d template.nii -w warp_anat2template.nii.gz -crop 1', verbose) # come back to parent folder os.chdir('..') # Generate output files sct.printv('\nGenerate output files...', verbose) sct.generate_output_file(path_tmp+'warp_template2anat.nii.gz', path_output+'warp_template2anat.nii.gz', verbose) sct.generate_output_file(path_tmp+'warp_anat2template.nii.gz', path_output+'warp_anat2template.nii.gz', verbose) sct.generate_output_file(path_tmp+'template2anat.nii.gz', path_output+'template2anat'+ext_data, verbose) sct.generate_output_file(path_tmp+'anat2template.nii.gz', path_output+'anat2template'+ext_data, verbose) if ref == 'template': # copy straightening files in case subsequent SCT functions need them sct.generate_output_file(path_tmp+'warp_curve2straight.nii.gz', path_output+'warp_curve2straight.nii.gz', verbose) sct.generate_output_file(path_tmp+'warp_straight2curve.nii.gz', path_output+'warp_straight2curve.nii.gz', verbose) sct.generate_output_file(path_tmp+'straight_ref.nii.gz', path_output+'straight_ref.nii.gz', verbose) # Delete temporary files if remove_temp_files: sct.printv('\nDelete temporary files...', verbose) sct.run('rm -rf '+path_tmp) # display elapsed time elapsed_time = time.time() - start_time sct.printv('\nFinished! Elapsed time: '+str(int(round(elapsed_time)))+'s', verbose) # to view results sct.printv('\nTo view results, type:', verbose) sct.printv('fslview '+fname_data+' '+path_output+'template2anat -b 0,4000 &', verbose, 'info') sct.printv('fslview '+fname_template+' -b 0,5000 '+path_output+'anat2template &\n', verbose, 'info') # Resample labels # ========================================================================================== def resample_labels(fname_labels, fname_dest, fname_output): """ This function re-create labels into a space that has been resampled. It works by re-defining the location of each label using the old and new voxel size. """ # get dimensions of input and destination files nx, ny, nz, nt, px, py, pz, pt = Image(fname_labels).dim nxd, nyd, nzd, ntd, pxd, pyd, pzd, ptd = Image(fname_dest).dim sampling_factor = [float(nx)/nxd, float(ny)/nyd, float(nz)/nzd] # read labels from sct_label_utils import ProcessLabels processor = ProcessLabels(fname_labels) label_list = processor.display_voxel() label_new_list = [] for label in label_list: label_sub_new = [str(int(round(int(label.x)/sampling_factor[0]))), str(int(round(int(label.y)/sampling_factor[1]))), str(int(round(int(label.z)/sampling_factor[2]))), str(int(float(label.value)))] label_new_list.append(','.join(label_sub_new)) label_new_list = ':'.join(label_new_list) # create new labels sct.run('sct_label_utils -i '+fname_dest+' -create '+label_new_list+' -v 1 -o '+fname_output) def check_labels(fname_landmarks): """ Make sure input labels are consistent Parameters ---------- fname_landmarks: file name of input labels Returns ------- none """ if(fname_landmarks=='viewer'): print('halloooooo') sct.printv('\nCheck input labels...') # open label file image_label = Image(fname_landmarks) # -> all labels must be different labels = image_label.getNonZeroCoordinates(sorting='value') # check if there is two labels if not len(labels) == 2: sct.printv('ERROR: Label file has ' + str(len(labels)) + ' label(s). It must contain exactly two labels.', 1, 'error') # check if the two labels are integer for label in labels: if not int(label.value) == label.value: sct.printv('ERROR: Label should be integer.', 1, 'error') # check if the two labels are different if labels[0].value == labels[1].value: sct.printv('ERROR: The two labels must be different.', 1, 'error') return labels # START PROGRAM # ========================================================================================== if __name__ == "__main__": # call main function main() Removed print Former-commit-id: b29ac4940b53d18117038180d9f06a9fdd05a7f2 #!/usr/bin/env python ######################################################################################### # # Register anatomical image to the template using the spinal cord centerline/segmentation. # # --------------------------------------------------------------------------------------- # Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: Benjamin De Leener, Julien Cohen-Adad, Augustin Roux # # About the license: see the file LICENSE.TXT ######################################################################################### # TODO: for -ref subject, crop data, otherwise registration is too long # TODO: testing script for all cases import sys import os import shutil import commands import time from glob import glob import sct_utils as sct from sct_utils import add_suffix from sct_image import set_orientation from sct_register_multimodal import Paramreg, ParamregMultiStep, register from msct_parser import Parser from msct_image import Image, find_zmin_zmax from shutil import move from sct_label_utils import ProcessLabels import numpy as np # get path of the toolbox path_script = os.path.dirname(__file__) path_sct = os.path.dirname(path_script) # DEFAULT PARAMETERS class Param: ## The constructor def __init__(self): self.debug = 0 self.remove_temp_files = 1 # remove temporary files self.fname_mask = '' # this field is needed in the function register@sct_register_multimodal self.padding = 10 # this field is needed in the function register@sct_register_multimodal self.verbose = 1 # verbose self.path_template = path_sct+'/data/PAM50' self.path_qc = os.path.abspath(os.curdir)+'/qc/' self.zsubsample = '0.25' self.param_straighten = '' # get default parameters # Note: step0 is used as pre-registration step0 = Paramreg(step='0', type='label', dof='Tx_Ty_Tz_Sz') # if ref=template, we only need translations and z-scaling because the cord is already straight step1 = Paramreg(step='1', type='seg', algo='centermassrot', smooth='2') # step2 = Paramreg(step='2', type='seg', algo='columnwise', smooth='0', smoothWarpXY='2') step2 = Paramreg(step='2', type='seg', algo='bsplinesyn', metric='MeanSquares', iter='3', smooth='1') # step3 = Paramreg(step='3', type='im', algo='syn', metric='CC', iter='1') paramreg = ParamregMultiStep([step0, step1, step2]) # PARSER # ========================================================================================== def get_parser(): param = Param() parser = Parser(__file__) parser.usage.set_description('Register anatomical image to the template.') parser.add_option(name="-i", type_value="file", description="Anatomical image.", mandatory=True, example="anat.nii.gz") parser.add_option(name="-s", type_value="file", description="Spinal cord segmentation.", mandatory=True, example="anat_seg.nii.gz") parser.add_option(name="-l", type_value="file", description="Labels. See: http://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels\n", mandatory=False, default_value='labels_reoriented.nii.gz', example="anat_labels.nii.gz") parser.add_option(name="-ofolder", type_value="folder_creation", description="Output folder.", mandatory=False, default_value='') parser.add_option(name="-t", type_value="folder", description="Path to template.", mandatory=False, default_value=param.path_template) parser.add_option(name='-c', type_value='multiple_choice', description='Contrast to use for registration.', mandatory=False, default_value='t2', example=['t1', 't2', 't2s']) parser.add_option(name='-ref', type_value='multiple_choice', description='Reference for registration: template: subject->template, subject: template->subject.', mandatory=False, default_value='template', example=['template', 'subject']) parser.add_option(name="-param", type_value=[[':'], 'str'], description='Parameters for registration (see sct_register_multimodal). Default: \ \n--\nstep=0\ntype=' + paramreg.steps['0'].type + '\ndof=' + paramreg.steps['0'].dof + '\ \n--\nstep=1\ntype=' + paramreg.steps['1'].type + '\nalgo=' + paramreg.steps['1'].algo + '\nmetric=' + paramreg.steps['1'].metric + '\niter=' + paramreg.steps['1'].iter + '\nsmooth=' + paramreg.steps['1'].smooth + '\ngradStep=' + paramreg.steps['1'].gradStep + '\nslicewise=' + paramreg.steps['1'].slicewise + '\nsmoothWarpXY=' + paramreg.steps['1'].smoothWarpXY + '\npca_eigenratio_th=' + paramreg.steps['1'].pca_eigenratio_th + '\ \n--\nstep=2\ntype=' + paramreg.steps['2'].type + '\nalgo=' + paramreg.steps['2'].algo + '\nmetric=' + paramreg.steps['2'].metric + '\niter=' + paramreg.steps['2'].iter + '\nsmooth=' + paramreg.steps['2'].smooth + '\ngradStep=' + paramreg.steps['2'].gradStep + '\nslicewise=' + paramreg.steps['2'].slicewise + '\nsmoothWarpXY=' + paramreg.steps['2'].smoothWarpXY + '\npca_eigenratio_th=' + paramreg.steps['1'].pca_eigenratio_th, mandatory=False) parser.add_option(name="-param-straighten", type_value='str', description="""Parameters for straightening (see sct_straighten_spinalcord).""", mandatory=False, default_value='') # parser.add_option(name="-cpu-nb", # type_value="int", # description="Number of CPU used for straightening. 0: no multiprocessing. By default, uses all the available cores.", # mandatory=False, # example="8") parser.add_option(name="-init-template", type_value="multiple_choice", description="You can create your own labels using a interactive viewer using option 'viewer", mandatory=False, default_value='0', example=['0', '1']) parser.add_option(name="-r", type_value="multiple_choice", description="""Remove temporary files.""", mandatory=False, default_value='1', example=['0', '1']) parser.add_option(name="-v", type_value="multiple_choice", description="""Verbose. 0: nothing. 1: basic. 2: extended.""", mandatory=False, default_value=param.verbose, example=['0', '1', '2']) return parser def rewrite_arguments(arguments): fname_data = arguments['-i'] fname_seg = arguments['-s'] fname_landmarks = arguments['-l'] if '-ofolder' in arguments: path_output = arguments['-ofolder'] else: path_output = '' path_template = sct.slash_at_the_end(arguments['-t'], 1) contrast_template = arguments['-c'] ref = arguments['-ref'] remove_temp_files = int(arguments['-r']) verbose = int(arguments['-v']) init_template=int(arguments['-init-template']) return (fname_data,fname_seg,fname_landmarks,path_output,path_template,contrast_template,ref,remove_temp_files,verbose,init_template) def write_paramaters(arguments,param,ref,verbose): param.verbose = verbose if '-param-straighten' in arguments: param.param_straighten = arguments['-param-straighten'] """ if '-cpu-nb' in arguments: arg_cpu = ' -cpu-nb '+str(arguments['-cpu-nb']) else: arg_cpu = '' registration parameters """ if '-param' in arguments: # reset parameters but keep step=0 (might be overwritten if user specified step=0) paramreg = ParamregMultiStep([step0]) if ref == 'subject': paramreg.steps['0'].dof = 'Tx_Ty_Tz_Rx_Ry_Rz_Sz' # add user parameters for paramStep in arguments['-param']: paramreg.addStep(paramStep) else: paramreg = ParamregMultiStep([step0, step1, step2]) # if ref=subject, initialize registration using different affine parameters if ref == 'subject': paramreg.steps['0'].dof = 'Tx_Ty_Tz_Rx_Ry_Rz_Sz' return (param,paramreg) def check_do_files_exist(fname_template,fname_template_vertebral_labeling,fname_template_seg,verbose): # TODO: no need to do that! sct.printv('\nCheck template files...') sct.check_file_exist(fname_template, verbose) sct.check_file_exist(fname_template_vertebral_labeling, verbose) sct.check_file_exist(fname_template_seg, verbose) def make_fname_of_templates(file_template,path_template,file_template_vertebral_labeling,file_template_seg): fname_template = path_template+'template/'+file_template fname_template_vertebral_labeling = path_template+'template/'+file_template_vertebral_labeling fname_template_seg = path_template+'template/'+file_template_seg return(fname_template,fname_template_vertebral_labeling,fname_template_seg) def print_arguments(verbose,fname_data,fname_landmarks,fname_seg,path_template,remove_temp_files): sct.printv('\nCheck parameters:', verbose) sct.printv(' Data: '+fname_data, verbose) sct.printv(' Landmarks: '+fname_landmarks, verbose) sct.printv(' Segmentation: '+fname_seg, verbose) sct.printv(' Path template: '+path_template, verbose) sct.printv(' Remove temp files: '+str(remove_temp_files), verbose) def check_data_segmentation_landmarks_same_space(fname_data,fname_seg,fname_landmarks,verbose): sct.printv('\nCheck if data, segmentation and landmarks are in the same space...') path_data, file_data, ext_data = sct.extract_fname(fname_data) if not sct.check_if_same_space(fname_data, fname_seg): sct.printv('ERROR: Data image and segmentation are not in the same space. Please check space and orientation of your files', verbose, 'error') if not sct.check_if_same_space(fname_data, fname_landmarks): sct.printv('ERROR: Data image and landmarks are not in the same space. Please check space and orientation of your files', verbose, 'error') return (ext_data,path_data,file_data) def set_temporary_files(): ftmp_data = 'data.nii' ftmp_seg = 'seg.nii.gz' ftmp_label = 'label.nii.gz' ftmp_template = 'template.nii' ftmp_template_seg = 'template_seg.nii.gz' ftmp_template_label = 'template_label.nii.gz' return(ftmp_data,ftmp_seg,ftmp_label,ftmp_template,ftmp_template_seg,ftmp_template_label) def copy_files_to_temporary_files(verbose,fname_data,path_tmp,ftmp_seg,ftmp_data,fname_seg,fname_landmarks,ftmp_label,fname_template,ftmp_template,fname_template_seg,ftmp_template_seg): sct.printv('\nCopying input data to tmp folder and convert to nii...', verbose) sct.run('sct_convert -i '+fname_data+' -o '+path_tmp+ftmp_data) sct.run('sct_convert -i '+fname_seg+' -o '+path_tmp+ftmp_seg) sct.run('sct_convert -i '+fname_landmarks+' -o '+path_tmp+ftmp_label) sct.run('sct_convert -i '+fname_template+' -o '+path_tmp+ftmp_template) sct.run('sct_convert -i '+fname_template_seg+' -o '+path_tmp+ftmp_template_seg) # sct.run('sct_convert -i '+fname_template_label+' -o '+path_tmp+ftmp_template_label) def set_viewer_parameters(viewer): viewer.number_of_slices = 1 pz = 1 viewer.gap_inter_slice = int(10 / pz) viewer.calculate_list_slices() viewer.help_url = 'https://sourceforge.net/p/spinalcordtoolbox/wiki/sct_label_vertebrae/attachment/label_vertebrae_viewer.png' def prepare_input_image_for_viewer(fname_data): # reorient image to SAL to be compatible with viewer im_input = Image(fname_data) im_input_SAL = im_input.copy() im_input_SAL.change_orientation('SAL') return(im_input_SAL) def check_mask_point_not_empty(mask_points): if(mask_points): return True else: sct.printv('\nERROR: the viewer has been closed before entering all manual points. Please try again.', 1, type='error') return False def use_viewer_to_define_labels(fname_data): from sct_viewer import ClickViewerRegisterToTemplate from msct_image import Image import sct_image image_input = Image(fname_data) image_input_orientation = sct_image.orientation(image_input, get=True, verbose=False) reoriented_image_filename = 'reoriented_image_source.nii.gz' path_tmp_viewer = sct.tmp_create(verbose=False) cmd_image = 'sct_image -i "%s" -o "%s" -setorient SAL -v 0' % ( fname_data, reoriented_image_filename) sct.run(cmd_image, verbose=False) im_input_SAL=prepare_input_image_for_viewer(fname_data) viewer = ClickViewerRegisterToTemplate(im_input_SAL, orientation_subplot=['sag', 'ax']) set_viewer_parameters(viewer) mask_points = viewer.start() #if not mask_points and viewer.closed: # mask_points = viewer.list_points_useful_notation #if check_mask_point_not_empty(mask_points): if True: import sct_image # create the mask containing either the three-points or centerline mask for initialization sct.run("sct_label_utils -i " + reoriented_image_filename + " -create " + mask_points ,verbose=False) sct.run('sct_image -i ' + 'labels.nii.gz'+ ' -o ' + 'labels_reoriented.nii.gz' + ' -setorient ' + image_input_orientation + ' -v 0',verbose=False) # reorient the initialization mask to correspond to input image orientation #mask_reoriented_filename = sct.add_suffix(file_data + ext_data, "_mask_viewer") #sct.run( #'sct_image -i ' + path_tmp_viewer + mask_filename + ' -o ' + folder_output + mask_reoriented_filename + ' -setorient ' + image_input_orientation + ' -v 0', #verbose=False) # MAIN # ========================================================================================== def main(): parser = get_parser() param = Param() """ Rewrite arguments and set parameters""" arguments = parser.parse(sys.argv[1:]) (fname_data, fname_seg, fname_landmarks, path_output, path_template, contrast_template, ref, remove_temp_files,verbose,init_template)=rewrite_arguments(arguments) (param, paramreg)=write_paramaters(arguments,param,ref,verbose) if(init_template): use_viewer_to_define_labels(fname_data) # initialize other parameters # file_template_label = param.file_template_label zsubsample = param.zsubsample template = os.path.basename(os.path.normpath(path_template)) # smoothing_sigma = param.smoothing_sigma # retrieve template file names from sct_warp_template import get_file_label file_template_vertebral_labeling = get_file_label(path_template+'template/', 'vertebral') file_template = get_file_label(path_template+'template/', contrast_template.upper()+'-weighted') file_template_seg = get_file_label(path_template+'template/', 'spinal cord') """ Start timer""" start_time = time.time() """ Manage file of templates""" (fname_template, fname_template_vertebral_labeling, fname_template_seg)=make_fname_of_templates(file_template,path_template,file_template_vertebral_labeling,file_template_seg) check_do_files_exist(fname_template,fname_template_vertebral_labeling,fname_template_seg,verbose) print_arguments(verbose, fname_data, fname_landmarks, fname_seg, path_template, remove_temp_files) """ Create QC folder """ sct.create_folder(param.path_qc) """ Check if data, segmentation and landmarks are in the same space""" (ext_data, path_data, file_data)=check_data_segmentation_landmarks_same_space(fname_data, fname_seg, fname_landmarks,verbose) ''' Check input labels''' labels = check_labels(fname_landmarks) """ create temporary folder, set temporary file names, copy files into it and go in it """ path_tmp = sct.tmp_create(verbose=verbose) (ftmp_data, ftmp_seg, ftmp_label, ftmp_template, ftmp_template_seg, ftmp_template_label)=set_temporary_files() copy_files_to_temporary_files(verbose, fname_data, path_tmp, ftmp_seg, ftmp_data, fname_seg, fname_landmarks, ftmp_label, fname_template, ftmp_template, fname_template_seg, ftmp_template_seg) os.chdir(path_tmp) ''' Generate labels from template vertebral labeling''' sct.printv('\nGenerate labels from template vertebral labeling', verbose) sct.run('sct_label_utils -i '+fname_template_vertebral_labeling+' -vert-body 0 -o '+ftmp_template_label) ''' check if provided labels are available in the template''' sct.printv('\nCheck if provided labels are available in the template', verbose) image_label_template = Image(ftmp_template_label) labels_template = image_label_template.getNonZeroCoordinates(sorting='value') if labels[-1].value > labels_template[-1].value: sct.printv('ERROR: Wrong landmarks input. Labels must have correspondence in template space. \nLabel max ' 'provided: ' + str(labels[-1].value) + '\nLabel max from template: ' + str(labels_template[-1].value), verbose, 'error') ''' binarize segmentation (in case it has values below 0 caused by manual editing)''' sct.printv('\nBinarize segmentation', verbose) sct.run('sct_maths -i seg.nii.gz -bin 0.5 -o seg.nii.gz') # smooth segmentation (jcohenadad, issue #613) # sct.printv('\nSmooth segmentation...', verbose) # sct.run('sct_maths -i '+ftmp_seg+' -smooth 1.5 -o '+add_suffix(ftmp_seg, '_smooth')) # jcohenadad: updated 2016-06-16: DO NOT smooth the seg anymore. Issue # # sct.run('sct_maths -i '+ftmp_seg+' -smooth 0 -o '+add_suffix(ftmp_seg, '_smooth')) # ftmp_seg = add_suffix(ftmp_seg, '_smooth') # Switch between modes: subject->template or template->subject if ref == 'template': # resample data to 1mm isotropic sct.printv('\nResample data to 1mm isotropic...', verbose) sct.run('sct_resample -i '+ftmp_data+' -mm 1.0x1.0x1.0 -x linear -o '+add_suffix(ftmp_data, '_1mm')) ftmp_data = add_suffix(ftmp_data, '_1mm') sct.run('sct_resample -i '+ftmp_seg+' -mm 1.0x1.0x1.0 -x linear -o '+add_suffix(ftmp_seg, '_1mm')) ftmp_seg = add_suffix(ftmp_seg, '_1mm') # N.B. resampling of labels is more complicated, because they are single-point labels, therefore resampling with neighrest neighbour can make them disappear. Therefore a more clever approach is required. resample_labels(ftmp_label, ftmp_data, add_suffix(ftmp_label, '_1mm')) ftmp_label = add_suffix(ftmp_label, '_1mm') # Change orientation of input images to RPI sct.printv('\nChange orientation of input images to RPI...', verbose) sct.run('sct_image -i '+ftmp_data+' -setorient RPI -o '+add_suffix(ftmp_data, '_rpi')) ftmp_data = add_suffix(ftmp_data, '_rpi') sct.run('sct_image -i '+ftmp_seg+' -setorient RPI -o '+add_suffix(ftmp_seg, '_rpi')) ftmp_seg = add_suffix(ftmp_seg, '_rpi') sct.run('sct_image -i '+ftmp_label+' -setorient RPI -o '+add_suffix(ftmp_label, '_rpi')) ftmp_label = add_suffix(ftmp_label, '_rpi') # get landmarks in native space # crop segmentation # output: segmentation_rpi_crop.nii.gz status_crop, output_crop = sct.run('sct_crop_image -i '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_crop')+' -dim 2 -bzmax', verbose) ftmp_seg = add_suffix(ftmp_seg, '_crop') cropping_slices = output_crop.split('Dimension 2: ')[1].split('\n')[0].split(' ') # straighten segmentation sct.printv('\nStraighten the spinal cord using centerline/segmentation...', verbose) # check if warp_curve2straight and warp_straight2curve already exist (i.e. no need to do it another time) if os.path.isfile('../warp_curve2straight.nii.gz') and os.path.isfile('../warp_straight2curve.nii.gz') and os.path.isfile('../straight_ref.nii.gz'): # if they exist, copy them into current folder sct.printv('WARNING: Straightening was already run previously. Copying warping fields...', verbose, 'warning') shutil.copy('../warp_curve2straight.nii.gz', 'warp_curve2straight.nii.gz') shutil.copy('../warp_straight2curve.nii.gz', 'warp_straight2curve.nii.gz') shutil.copy('../straight_ref.nii.gz', 'straight_ref.nii.gz') # apply straightening sct.run('sct_apply_transfo -i '+ftmp_seg+' -w warp_curve2straight.nii.gz -d straight_ref.nii.gz -o '+add_suffix(ftmp_seg, '_straight')) else: sct.run('sct_straighten_spinalcord -i '+ftmp_seg+' -s '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_straight')+' -qc 0 -r 0 -v '+str(verbose), verbose) # N.B. DO NOT UPDATE VARIABLE ftmp_seg BECAUSE TEMPORARY USED LATER # re-define warping field using non-cropped space (to avoid issue #367) sct.run('sct_concat_transfo -w warp_straight2curve.nii.gz -d '+ftmp_data+' -o warp_straight2curve.nii.gz') # Label preparation: # -------------------------------------------------------------------------------- # Remove unused label on template. Keep only label present in the input label image sct.printv('\nRemove unused label on template. Keep only label present in the input label image...', verbose) sct.run('sct_label_utils -i '+ftmp_template_label+' -o '+ftmp_template_label+' -remove '+ftmp_label) # Dilating the input label so they can be straighten without losing them sct.printv('\nDilating input labels using 3vox ball radius') sct.run('sct_maths -i '+ftmp_label+' -o '+add_suffix(ftmp_label, '_dilate')+' -dilate 3') ftmp_label = add_suffix(ftmp_label, '_dilate') # Apply straightening to labels sct.printv('\nApply straightening to labels...', verbose) sct.run('sct_apply_transfo -i '+ftmp_label+' -o '+add_suffix(ftmp_label, '_straight')+' -d '+add_suffix(ftmp_seg, '_straight')+' -w warp_curve2straight.nii.gz -x nn') ftmp_label = add_suffix(ftmp_label, '_straight') # Compute rigid transformation straight landmarks --> template landmarks sct.printv('\nEstimate transformation for step #0...', verbose) from msct_register_landmarks import register_landmarks try: register_landmarks(ftmp_label, ftmp_template_label, paramreg.steps['0'].dof, fname_affine='straight2templateAffine.txt', verbose=verbose) except Exception: sct.printv('ERROR: input labels do not seem to be at the right place. Please check the position of the labels. See documentation for more details: https://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels/', verbose=verbose, type='error') # Concatenate transformations: curve --> straight --> affine sct.printv('\nConcatenate transformations: curve --> straight --> affine...', verbose) sct.run('sct_concat_transfo -w warp_curve2straight.nii.gz,straight2templateAffine.txt -d template.nii -o warp_curve2straightAffine.nii.gz') # Apply transformation sct.printv('\nApply transformation...', verbose) sct.run('sct_apply_transfo -i '+ftmp_data+' -o '+add_suffix(ftmp_data, '_straightAffine')+' -d '+ftmp_template+' -w warp_curve2straightAffine.nii.gz') ftmp_data = add_suffix(ftmp_data, '_straightAffine') sct.run('sct_apply_transfo -i '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_straightAffine')+' -d '+ftmp_template+' -w warp_curve2straightAffine.nii.gz -x linear') ftmp_seg = add_suffix(ftmp_seg, '_straightAffine') """ # Benjamin: Issue from Allan Martin, about the z=0 slice that is screwed up, caused by the affine transform. # Solution found: remove slices below and above landmarks to avoid rotation effects points_straight = [] for coord in landmark_template: points_straight.append(coord.z) min_point, max_point = int(round(np.min(points_straight))), int(round(np.max(points_straight))) sct.run('sct_crop_image -i ' + ftmp_seg + ' -start ' + str(min_point) + ' -end ' + str(max_point) + ' -dim 2 -b 0 -o ' + add_suffix(ftmp_seg, '_black')) ftmp_seg = add_suffix(ftmp_seg, '_black') """ # binarize sct.printv('\nBinarize segmentation...', verbose) sct.run('sct_maths -i '+ftmp_seg+' -bin 0.5 -o '+add_suffix(ftmp_seg, '_bin')) ftmp_seg = add_suffix(ftmp_seg, '_bin') # find min-max of anat2template (for subsequent cropping) zmin_template, zmax_template = find_zmin_zmax(ftmp_seg) # crop template in z-direction (for faster processing) sct.printv('\nCrop data in template space (for faster processing)...', verbose) sct.run('sct_crop_image -i '+ftmp_template+' -o '+add_suffix(ftmp_template, '_crop')+' -dim 2 -start '+str(zmin_template)+' -end '+str(zmax_template)) ftmp_template = add_suffix(ftmp_template, '_crop') sct.run('sct_crop_image -i '+ftmp_template_seg+' -o '+add_suffix(ftmp_template_seg, '_crop')+' -dim 2 -start '+str(zmin_template)+' -end '+str(zmax_template)) ftmp_template_seg = add_suffix(ftmp_template_seg, '_crop') sct.run('sct_crop_image -i '+ftmp_data+' -o '+add_suffix(ftmp_data, '_crop')+' -dim 2 -start '+str(zmin_template)+' -end '+str(zmax_template)) ftmp_data = add_suffix(ftmp_data, '_crop') sct.run('sct_crop_image -i '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_crop')+' -dim 2 -start '+str(zmin_template)+' -end '+str(zmax_template)) ftmp_seg = add_suffix(ftmp_seg, '_crop') # sub-sample in z-direction sct.printv('\nSub-sample in z-direction (for faster processing)...', verbose) sct.run('sct_resample -i '+ftmp_template+' -o '+add_suffix(ftmp_template, '_sub')+' -f 1x1x'+zsubsample, verbose) ftmp_template = add_suffix(ftmp_template, '_sub') sct.run('sct_resample -i '+ftmp_template_seg+' -o '+add_suffix(ftmp_template_seg, '_sub')+' -f 1x1x'+zsubsample, verbose) ftmp_template_seg = add_suffix(ftmp_template_seg, '_sub') sct.run('sct_resample -i '+ftmp_data+' -o '+add_suffix(ftmp_data, '_sub')+' -f 1x1x'+zsubsample, verbose) ftmp_data = add_suffix(ftmp_data, '_sub') sct.run('sct_resample -i '+ftmp_seg+' -o '+add_suffix(ftmp_seg, '_sub')+' -f 1x1x'+zsubsample, verbose) ftmp_seg = add_suffix(ftmp_seg, '_sub') # Registration straight spinal cord to template sct.printv('\nRegister straight spinal cord to template...', verbose) # loop across registration steps warp_forward = [] warp_inverse = [] for i_step in range(1, len(paramreg.steps)): sct.printv('\nEstimate transformation for step #'+str(i_step)+'...', verbose) # identify which is the src and dest if paramreg.steps[str(i_step)].type == 'im': src = ftmp_data dest = ftmp_template interp_step = 'linear' elif paramreg.steps[str(i_step)].type == 'seg': src = ftmp_seg dest = ftmp_template_seg interp_step = 'nn' else: sct.printv('ERROR: Wrong image type.', 1, 'error') # if step>1, apply warp_forward_concat to the src image to be used if i_step > 1: # sct.run('sct_apply_transfo -i '+src+' -d '+dest+' -w '+','.join(warp_forward)+' -o '+sct.add_suffix(src, '_reg')+' -x '+interp_step, verbose) # apply transformation from previous step, to use as new src for registration sct.run('sct_apply_transfo -i '+src+' -d '+dest+' -w '+','.join(warp_forward)+' -o '+add_suffix(src, '_regStep'+str(i_step-1))+' -x '+interp_step, verbose) src = add_suffix(src, '_regStep'+str(i_step-1)) # register src --> dest # TODO: display param for debugging warp_forward_out, warp_inverse_out = register(src, dest, paramreg, param, str(i_step)) warp_forward.append(warp_forward_out) warp_inverse.append(warp_inverse_out) # Concatenate transformations: sct.printv('\nConcatenate transformations: anat --> template...', verbose) sct.run('sct_concat_transfo -w warp_curve2straightAffine.nii.gz,'+','.join(warp_forward)+' -d template.nii -o warp_anat2template.nii.gz', verbose) # sct.run('sct_concat_transfo -w warp_curve2straight.nii.gz,straight2templateAffine.txt,'+','.join(warp_forward)+' -d template.nii -o warp_anat2template.nii.gz', verbose) sct.printv('\nConcatenate transformations: template --> anat...', verbose) warp_inverse.reverse() sct.run('sct_concat_transfo -w '+','.join(warp_inverse)+',-straight2templateAffine.txt,warp_straight2curve.nii.gz -d data.nii -o warp_template2anat.nii.gz', verbose) # register template->subject elif ref == 'subject': # Change orientation of input images to RPI sct.printv('\nChange orientation of input images to RPI...', verbose) sct.run('sct_image -i ' + ftmp_data + ' -setorient RPI -o ' + add_suffix(ftmp_data, '_rpi')) ftmp_data = add_suffix(ftmp_data, '_rpi') sct.run('sct_image -i ' + ftmp_seg + ' -setorient RPI -o ' + add_suffix(ftmp_seg, '_rpi')) ftmp_seg = add_suffix(ftmp_seg, '_rpi') sct.run('sct_image -i ' + ftmp_label + ' -setorient RPI -o ' + add_suffix(ftmp_label, '_rpi')) ftmp_label = add_suffix(ftmp_label, '_rpi') # Remove unused label on template. Keep only label present in the input label image sct.printv('\nRemove unused label on template. Keep only label present in the input label image...', verbose) sct.run('sct_label_utils -i '+ftmp_template_label+' -o '+ftmp_template_label+' -remove '+ftmp_label) # Add one label because at least 3 orthogonal labels are required to estimate an affine transformation. This new label is added at the level of the upper most label (lowest value), at 1cm to the right. for i_file in [ftmp_label, ftmp_template_label]: im_label = Image(i_file) coord_label = im_label.getCoordinatesAveragedByValue() # N.B. landmarks are sorted by value # Create new label from copy import deepcopy new_label = deepcopy(coord_label[0]) # move it 5mm to the left (orientation is RAS) nx, ny, nz, nt, px, py, pz, pt = im_label.dim new_label.x = round(coord_label[0].x + 5.0 / px) # assign value 99 new_label.value = 99 # Add to existing image im_label.data[int(new_label.x), int(new_label.y), int(new_label.z)] = new_label.value # Overwrite label file # im_label.setFileName('label_rpi_modif.nii.gz') im_label.save() # Bring template to subject space using landmark-based transformation sct.printv('\nEstimate transformation for step #0...', verbose) from msct_register_landmarks import register_landmarks warp_forward = ['template2subjectAffine.txt'] warp_inverse = ['-template2subjectAffine.txt'] try: register_landmarks(ftmp_template_label, ftmp_label, paramreg.steps['0'].dof, fname_affine=warp_forward[0], verbose=verbose, path_qc=param.path_qc) except Exception: sct.printv('ERROR: input labels do not seem to be at the right place. Please check the position of the labels. See documentation for more details: https://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels/', verbose=verbose, type='error') # loop across registration steps for i_step in range(1, len(paramreg.steps)): sct.printv('\nEstimate transformation for step #'+str(i_step)+'...', verbose) # identify which is the src and dest if paramreg.steps[str(i_step)].type == 'im': src = ftmp_template dest = ftmp_data interp_step = 'linear' elif paramreg.steps[str(i_step)].type == 'seg': src = ftmp_template_seg dest = ftmp_seg interp_step = 'nn' else: sct.printv('ERROR: Wrong image type.', 1, 'error') # apply transformation from previous step, to use as new src for registration sct.run('sct_apply_transfo -i '+src+' -d '+dest+' -w '+','.join(warp_forward)+' -o '+add_suffix(src, '_regStep'+str(i_step-1))+' -x '+interp_step, verbose) src = add_suffix(src, '_regStep'+str(i_step-1)) # register src --> dest # TODO: display param for debugging warp_forward_out, warp_inverse_out = register(src, dest, paramreg, param, str(i_step)) warp_forward.append(warp_forward_out) warp_inverse.insert(0, warp_inverse_out) # Concatenate transformations: sct.printv('\nConcatenate transformations: template --> subject...', verbose) sct.run('sct_concat_transfo -w '+','.join(warp_forward)+' -d data.nii -o warp_template2anat.nii.gz', verbose) sct.printv('\nConcatenate transformations: subject --> template...', verbose) sct.run('sct_concat_transfo -w '+','.join(warp_inverse)+' -d template.nii -o warp_anat2template.nii.gz', verbose) # Apply warping fields to anat and template sct.run('sct_apply_transfo -i template.nii -o template2anat.nii.gz -d data.nii -w warp_template2anat.nii.gz -crop 1', verbose) sct.run('sct_apply_transfo -i data.nii -o anat2template.nii.gz -d template.nii -w warp_anat2template.nii.gz -crop 1', verbose) # come back to parent folder os.chdir('..') # Generate output files sct.printv('\nGenerate output files...', verbose) sct.generate_output_file(path_tmp+'warp_template2anat.nii.gz', path_output+'warp_template2anat.nii.gz', verbose) sct.generate_output_file(path_tmp+'warp_anat2template.nii.gz', path_output+'warp_anat2template.nii.gz', verbose) sct.generate_output_file(path_tmp+'template2anat.nii.gz', path_output+'template2anat'+ext_data, verbose) sct.generate_output_file(path_tmp+'anat2template.nii.gz', path_output+'anat2template'+ext_data, verbose) if ref == 'template': # copy straightening files in case subsequent SCT functions need them sct.generate_output_file(path_tmp+'warp_curve2straight.nii.gz', path_output+'warp_curve2straight.nii.gz', verbose) sct.generate_output_file(path_tmp+'warp_straight2curve.nii.gz', path_output+'warp_straight2curve.nii.gz', verbose) sct.generate_output_file(path_tmp+'straight_ref.nii.gz', path_output+'straight_ref.nii.gz', verbose) # Delete temporary files if remove_temp_files: sct.printv('\nDelete temporary files...', verbose) sct.run('rm -rf '+path_tmp) # display elapsed time elapsed_time = time.time() - start_time sct.printv('\nFinished! Elapsed time: '+str(int(round(elapsed_time)))+'s', verbose) # to view results sct.printv('\nTo view results, type:', verbose) sct.printv('fslview '+fname_data+' '+path_output+'template2anat -b 0,4000 &', verbose, 'info') sct.printv('fslview '+fname_template+' -b 0,5000 '+path_output+'anat2template &\n', verbose, 'info') # Resample labels # ========================================================================================== def resample_labels(fname_labels, fname_dest, fname_output): """ This function re-create labels into a space that has been resampled. It works by re-defining the location of each label using the old and new voxel size. """ # get dimensions of input and destination files nx, ny, nz, nt, px, py, pz, pt = Image(fname_labels).dim nxd, nyd, nzd, ntd, pxd, pyd, pzd, ptd = Image(fname_dest).dim sampling_factor = [float(nx)/nxd, float(ny)/nyd, float(nz)/nzd] # read labels from sct_label_utils import ProcessLabels processor = ProcessLabels(fname_labels) label_list = processor.display_voxel() label_new_list = [] for label in label_list: label_sub_new = [str(int(round(int(label.x)/sampling_factor[0]))), str(int(round(int(label.y)/sampling_factor[1]))), str(int(round(int(label.z)/sampling_factor[2]))), str(int(float(label.value)))] label_new_list.append(','.join(label_sub_new)) label_new_list = ':'.join(label_new_list) # create new labels sct.run('sct_label_utils -i '+fname_dest+' -create '+label_new_list+' -v 1 -o '+fname_output) def check_labels(fname_landmarks): """ Make sure input labels are consistent Parameters ---------- fname_landmarks: file name of input labels Returns ------- none """ if(fname_landmarks=='viewer'): sct.printv('\nCheck input labels...') # open label file image_label = Image(fname_landmarks) # -> all labels must be different labels = image_label.getNonZeroCoordinates(sorting='value') # check if there is two labels if not len(labels) == 2: sct.printv('ERROR: Label file has ' + str(len(labels)) + ' label(s). It must contain exactly two labels.', 1, 'error') # check if the two labels are integer for label in labels: if not int(label.value) == label.value: sct.printv('ERROR: Label should be integer.', 1, 'error') # check if the two labels are different if labels[0].value == labels[1].value: sct.printv('ERROR: The two labels must be different.', 1, 'error') return labels # START PROGRAM # ========================================================================================== if __name__ == "__main__": # call main function main()
#!/usr/bin/env python ######################################################################################### # # Register anatomical image to the template using the spinal cord centerline/segmentation. # # --------------------------------------------------------------------------------------- # Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca> # Author: Benjamin De Leener, Julien Cohen-Adad, Augustin Roux # Modified: 2014-08-29 # # About the license: see the file LICENSE.TXT ######################################################################################### # TODO: make function sct_convert_binary_to_trilinear # TODO: testing script for all cases # TODO: try to combine seg and image based for 2nd stage # TODO: output name file for warp using "src" and "dest" file name, i.e. warp_filesrc2filedest.nii.gz # TODO: flag to output warping field # TODO: check if destination is axial orientation # TODO: set gradient-step-length in mm instead of vox size. # DEFAULT PARAMETERS class param: ## The constructor def __init__(self): self.debug = 0 self.remove_temp_files = 1 # remove temporary files self.output_type = 1 self.speed = 'fast' # speed of registration. slow | normal | fast self.verbose = 1 # verbose self.test = 0 self.folder_template = '/data/template' self.folder_template_DS = '/testing/data' self.file_template = 'MNI-Poly-AMU_T2.nii.gz' self.file_template_label = 'landmarks_center.nii.gz' self.file_template_seg = 'MNI-Poly-AMU_cord.nii.gz' self.smoothing_sigma = 5 # Smoothing along centerline to improve accuracy and remove step effects import sys import getopt import os import commands import time import sct_utils as sct # MAIN # ========================================================================================== def main(): # Initialization fname_data = '' fname_landmarks = '' fname_seg = '' folder_template = param.folder_template file_template = param.file_template file_template_label = param.file_template_label file_template_seg = param.file_template_seg output_type = param.output_type speed = param.speed test = param.test remove_temp_files = param.remove_temp_files verbose = param.verbose smoothing_sigma = param.smoothing_sigma # start timer start_time = time.time() # get path of the toolbox status, path_sct = commands.getstatusoutput('echo $SCT_DIR') # # get path of the template # path_template = path_sct+folder_template # Parameters for debug mode if param.debug: print '\n*** WARNING: DEBUG MODE ON ***\n' fname_data = path_sct+'/testing/data/errsm_23/t2/t2.nii.gz' fname_landmarks = path_sct+'/testing/data/errsm_23/t2/t2_landmarks_C2_T2_center.nii.gz' fname_seg = path_sct+'/testing/data/errsm_23/t2/t2_segmentation_PropSeg.nii.gz' speed = 'superfast' # Check input parameters try: opts, args = getopt.getopt(sys.argv[1:],'hi:l:m:o:r:s:t:') except getopt.GetoptError: usage() for opt, arg in opts: if opt == '-h': usage() elif opt in ("-i"): fname_data = arg elif opt in ('-l'): fname_landmarks = arg elif opt in ("-m"): fname_seg = arg elif opt in ("-o"): output_type = int(arg) elif opt in ("-r"): remove_temp_files = int(arg) elif opt in ("-s"): speed = arg elif opt in ("-t"): test = arg if test: folder_template = param.folder_template_DS # get fname of the template + template objects fname_template = path_sct+folder_template+'/'+file_template fname_template_label = path_sct+folder_template+'/'+file_template_label fname_template_seg = path_sct+folder_template+'/'+file_template_seg # display usage if a mandatory argument is not provided if fname_data == '' or fname_landmarks == '' or fname_seg == '': usage() # print arguments print '\nCheck parameters:' print '.. Data: '+fname_data print '.. Landmarks: '+fname_landmarks print '.. Segmentation: '+fname_seg print '.. Output type: '+str(output_type) print '.. Speed: '+speed print '.. Remove temp files: '+str(remove_temp_files) # Check speed parameter and create registration mode: slow 50x30, normal 50x15, fast 10x3 (default) print('\nAssign number of iterations based on speed...') if speed == "slow": nb_iterations = "50x30" elif speed == "normal": nb_iterations = "50x15" elif speed == "fast": nb_iterations = "10x3" elif speed == "superfast": nb_iterations = "3x1" # only for debugging purpose-- do not inform the user about this option else: print 'ERROR: Wrong input registration speed {slow, normal, fast}.' sys.exit(2) print '.. '+nb_iterations # Get full path # fname_data = os.path.abspath(fname_data) # fname_landmarks = os.path.abspath(fname_landmarks) # fname_seg = os.path.abspath(fname_seg) # check existence of input files print('\nCheck existence of input files...') sct.check_file_exist(fname_data,verbose) sct.check_file_exist(fname_landmarks,verbose) sct.check_file_exist(fname_seg,verbose) path_data, file_data, ext_data = sct.extract_fname(fname_data) # create temporary folder print('\nCreate temporary folder...') path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") status, output = sct.run('mkdir '+path_tmp) # copy files to temporary folder print('\nCopy files...') status, output = sct.run('sct_c3d '+fname_data+' -o '+path_tmp+'/data.nii') status, output = sct.run('sct_c3d '+fname_landmarks+' -o '+path_tmp+'/landmarks.nii.gz') status, output = sct.run('sct_c3d '+fname_seg+' -o '+path_tmp+'/segmentation.nii.gz') # go to tmp folder os.chdir(path_tmp) # Change orientation of input images to RPI print('\nChange orientation of input images to RPI...') status, output = sct.run('sct_orientation -i data.nii -o data_rpi.nii -orientation RPI') status, output = sct.run('sct_orientation -i landmarks.nii.gz -o landmarks_rpi.nii.gz -orientation RPI') status, output = sct.run('sct_orientation -i segmentation.nii.gz -o segmentation_rpi.nii.gz -orientation RPI') # Straighten the spinal cord using centerline/segmentation print('\nStraighten the spinal cord using centerline/segmentation...') status, output = sct.run('sct_straighten_spinalcord -i data_rpi.nii -c segmentation_rpi.nii.gz -r '+str(remove_temp_files)) # Apply straightening to segmentation print('\nApply straightening to segmentation...') sct.run('sct_WarpImageMultiTransform 3 segmentation_rpi.nii.gz segmentation_rpi_straight.nii.gz -R data_rpi_straight.nii warp_curve2straight.nii.gz') # Smoothing along centerline to improve accuracy and remove step effects print('\nSmoothing along centerline to improve accuracy and remove step effects...') sct.run('sct_c3d data_rpi_straight.nii -smooth 0x0x'+str(smoothing_sigma)+'vox -o data_rpi_straight.nii') sct.run('sct_c3d segmentation_rpi_straight.nii.gz -smooth 0x0x'+str(smoothing_sigma)+'vox -o segmentation_rpi_straight.nii.gz') # Label preparation: # -------------------------------------------------------------------------------- # Remove unused label on template. Keep only label present in the input label image print('\nRemove unused label on template. Keep only label present in the input label image...') status, output = sct.run('sct_label_utils -t remove -i '+fname_template_label+' -o template_label.nii.gz -r landmarks_rpi.nii.gz') # Create a cross for the template labels - 5 mm print('\nCreate a 5 mm cross for the template labels...') status, output = sct.run('sct_label_utils -t cross -i template_label.nii.gz -o template_label_cross.nii.gz -c 5') # Create a cross for the input labels and dilate for straightening preparation - 5 mm print('\nCreate a 5mm cross for the input labels and dilate for straightening preparation...') status, output = sct.run('sct_label_utils -t cross -i landmarks_rpi.nii.gz -o landmarks_rpi_cross3x3.nii.gz -c 5 -d') # Push the input labels in the template space print('\nPush the input labels to the straight space...') status, output = sct.run('sct_WarpImageMultiTransform 3 landmarks_rpi_cross3x3.nii.gz landmarks_rpi_cross3x3_straight.nii.gz -R data_rpi_straight.nii warp_curve2straight.nii.gz --use-NN') # Convert landmarks from FLOAT32 to INT print '\nConvert landmarks from FLOAT32 to INT...' sct.run('sct_c3d landmarks_rpi_cross3x3_straight.nii.gz -type int -o landmarks_rpi_cross3x3_straight.nii.gz') # Estimate affine transfo: straight --> template (landmark-based)' print '\nEstimate affine transfo: straight anat --> template (landmark-based)...' sct.run('sct_ANTSUseLandmarkImagesToGetAffineTransform template_label_cross.nii.gz landmarks_rpi_cross3x3_straight.nii.gz affine straight2templateAffine.txt') # Apply affine transformation: straight --> template print '\nApply affine transformation: straight --> template...' sct.run('sct_WarpImageMultiTransform 3 data_rpi_straight.nii data_rpi_straight2templateAffine.nii straight2templateAffine.txt -R '+fname_template) sct.run('sct_WarpImageMultiTransform 3 segmentation_rpi_straight.nii.gz segmentation_rpi_straight2templateAffine.nii.gz straight2templateAffine.txt -R '+fname_template) # now threshold at 0.5 (for partial volume interpolation) # do not do that anymore-- better to estimate transformation using trilinear interp image to avoid step effect. See issue #31 on github. # sct.run('sct_c3d segmentation_rpi_straight2templateAffine.nii.gz -threshold -inf 0.5 0 1 -o segmentation_rpi_straight2templateAffine.nii.gz') # Registration straight spinal cord to template print('\nRegister straight spinal cord to template...') #nb_iterations = '50x15' # TODO: nb iteration for step 2 sct.run('sct_register_multimodal -i data_rpi_straight2templateAffine.nii -d '+fname_template+' -s segmentation_rpi_straight2templateAffine.nii.gz -t '+fname_template_seg+' -r '+str(remove_temp_files)+' -n '+nb_iterations+' -v '+str(verbose)+' -x 1',verbose) # status, output = sct.run('sct_register_straight_spinalcord_to_template -i data_rpi_straight.nii.gz -l landmarks_rpi_cross3x3_straight.nii.gz -t '+path_template+'/MNI-Poly-AMU_T2.nii.gz -f template_label_cross.nii.gz -m '+path_template+'/mask_gaussian_templatespace_sigma20.nii.gz -r 1 -n '+nb_iterations+' -v 1') # Concatenate warping fields: template2anat & anat2template print('\nConcatenate warping fields: template2anat & anat2template...') cmd = 'sct_ComposeMultiTransform 3 warp_template2anat.nii.gz -R data.nii warp_straight2curve.nii.gz -i straight2templateAffine.txt warp_dest2src.nii.gz' print '>> '+cmd commands.getstatusoutput(cmd) cmd = 'sct_ComposeMultiTransform 3 warp_anat2template.nii.gz -R '+fname_template+' warp_src2dest.nii.gz straight2templateAffine.txt warp_curve2straight.nii.gz' print '>> '+cmd commands.getstatusoutput(cmd) # Apply warping fields to anat and template if output_type == 1: sct.run('sct_WarpImageMultiTransform 3 '+fname_template+' template2anat.nii.gz -R data.nii warp_template2anat.nii.gz') sct.run('sct_WarpImageMultiTransform 3 data.nii.gz anat2template.nii.gz -R '+fname_template+' warp_anat2template.nii.gz') # come back to parent folder os.chdir('..') # Generate output files print('\nGenerate output files...') sct.generate_output_file(path_tmp+'/warp_template2anat.nii.gz', 'warp_template2anat.nii.gz') sct.generate_output_file(path_tmp+'/warp_anat2template.nii.gz', 'warp_anat2template.nii.gz') if output_type == 1: sct.generate_output_file(path_tmp+'/template2anat.nii.gz', 'template2anat'+ext_data) sct.generate_output_file(path_tmp+'/anat2template.nii.gz', 'anat2template'+ext_data) # Delete temporary files if remove_temp_files == 1: print '\nDelete temporary files...' sct.run('rm -rf '+path_tmp) # display elapsed time elapsed_time = time.time() - start_time print '\nFinished! Elapsed time: '+str(int(round(elapsed_time)))+'s' # to view results print '\nTo view results, type:' print 'fslview template2anat -b 0,3000 '+fname_data+' &' print 'fslview anat2template '+fname_template+' -b 0,3000 &\n' # Print usage # ========================================================================================== def usage(): print '\n' \ ''+os.path.basename(__file__)+'\n' \ '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' \ 'Part of the Spinal Cord Toolbox <https://sourceforge.net/projects/spinalcordtoolbox>\n' \ '\n'\ 'DESCRIPTION\n' \ ' Register anatomical image to the template.\n' \ '\n' \ 'USAGE\n' \ ' '+os.path.basename(__file__)+' -i <anat> -l <landmarks> -m <segmentation>\n' \ '\n' \ 'MANDATORY ARGUMENTS\n' \ ' -i <anat> anatomical image\n' \ ' -l <landmarks> landmarks at spinal cord center. See: http://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels/\n' \ ' -m <segmentation> spinal cord segmentation. \n' \ '\n' \ 'OPTIONAL ARGUMENTS\n' \ ' -o {0, 1} output type. 0: warp, 1: warp+images. Default='+str(param.output_type)+'\n' \ ' -s {slow, normal, fast} Speed of registration. Slow gives the best results. Default='+param.speed+'\n' \ ' -r {0, 1} remove temporary files. Default='+str(param.remove_temp_files)+'\n' \ ' -t {0, 1} use down sampled template files (for testing)' # exit program sys.exit(2) # START PROGRAM # ========================================================================================== if __name__ == "__main__": # initialize parameters param = param() # call main function main() REF: updated dynamic range for fslview command Former-commit-id: bcd1e93db6fc0bfaeb4a4955c71a1c40ec94cdf4 Former-commit-id: 2fad3f07826c017aa816f5a1341cfcc7fe051245 #!/usr/bin/env python ######################################################################################### # # Register anatomical image to the template using the spinal cord centerline/segmentation. # # --------------------------------------------------------------------------------------- # Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca> # Author: Benjamin De Leener, Julien Cohen-Adad, Augustin Roux # Modified: 2014-08-29 # # About the license: see the file LICENSE.TXT ######################################################################################### # TODO: make function sct_convert_binary_to_trilinear # TODO: testing script for all cases # TODO: try to combine seg and image based for 2nd stage # TODO: output name file for warp using "src" and "dest" file name, i.e. warp_filesrc2filedest.nii.gz # TODO: flag to output warping field # TODO: check if destination is axial orientation # TODO: set gradient-step-length in mm instead of vox size. # DEFAULT PARAMETERS class param: ## The constructor def __init__(self): self.debug = 0 self.remove_temp_files = 1 # remove temporary files self.output_type = 1 self.speed = 'fast' # speed of registration. slow | normal | fast self.verbose = 1 # verbose self.test = 0 self.folder_template = '/data/template' self.folder_template_DS = '/testing/data' self.file_template = 'MNI-Poly-AMU_T2.nii.gz' self.file_template_label = 'landmarks_center.nii.gz' self.file_template_seg = 'MNI-Poly-AMU_cord.nii.gz' self.smoothing_sigma = 5 # Smoothing along centerline to improve accuracy and remove step effects import sys import getopt import os import commands import time import sct_utils as sct # MAIN # ========================================================================================== def main(): # Initialization fname_data = '' fname_landmarks = '' fname_seg = '' folder_template = param.folder_template file_template = param.file_template file_template_label = param.file_template_label file_template_seg = param.file_template_seg output_type = param.output_type speed = param.speed test = param.test remove_temp_files = param.remove_temp_files verbose = param.verbose smoothing_sigma = param.smoothing_sigma # start timer start_time = time.time() # get path of the toolbox status, path_sct = commands.getstatusoutput('echo $SCT_DIR') # # get path of the template # path_template = path_sct+folder_template # Parameters for debug mode if param.debug: print '\n*** WARNING: DEBUG MODE ON ***\n' fname_data = path_sct+'/testing/data/errsm_23/t2/t2.nii.gz' fname_landmarks = path_sct+'/testing/data/errsm_23/t2/t2_landmarks_C2_T2_center.nii.gz' fname_seg = path_sct+'/testing/data/errsm_23/t2/t2_segmentation_PropSeg.nii.gz' speed = 'superfast' # Check input parameters try: opts, args = getopt.getopt(sys.argv[1:],'hi:l:m:o:r:s:t:') except getopt.GetoptError: usage() for opt, arg in opts: if opt == '-h': usage() elif opt in ("-i"): fname_data = arg elif opt in ('-l'): fname_landmarks = arg elif opt in ("-m"): fname_seg = arg elif opt in ("-o"): output_type = int(arg) elif opt in ("-r"): remove_temp_files = int(arg) elif opt in ("-s"): speed = arg elif opt in ("-t"): test = arg if test: folder_template = param.folder_template_DS # get fname of the template + template objects fname_template = path_sct+folder_template+'/'+file_template fname_template_label = path_sct+folder_template+'/'+file_template_label fname_template_seg = path_sct+folder_template+'/'+file_template_seg # display usage if a mandatory argument is not provided if fname_data == '' or fname_landmarks == '' or fname_seg == '': usage() # print arguments print '\nCheck parameters:' print '.. Data: '+fname_data print '.. Landmarks: '+fname_landmarks print '.. Segmentation: '+fname_seg print '.. Output type: '+str(output_type) print '.. Speed: '+speed print '.. Remove temp files: '+str(remove_temp_files) # Check speed parameter and create registration mode: slow 50x30, normal 50x15, fast 10x3 (default) print('\nAssign number of iterations based on speed...') if speed == "slow": nb_iterations = "50x30" elif speed == "normal": nb_iterations = "50x15" elif speed == "fast": nb_iterations = "10x3" elif speed == "superfast": nb_iterations = "3x1" # only for debugging purpose-- do not inform the user about this option else: print 'ERROR: Wrong input registration speed {slow, normal, fast}.' sys.exit(2) print '.. '+nb_iterations # Get full path # fname_data = os.path.abspath(fname_data) # fname_landmarks = os.path.abspath(fname_landmarks) # fname_seg = os.path.abspath(fname_seg) # check existence of input files print('\nCheck existence of input files...') sct.check_file_exist(fname_data,verbose) sct.check_file_exist(fname_landmarks,verbose) sct.check_file_exist(fname_seg,verbose) path_data, file_data, ext_data = sct.extract_fname(fname_data) # create temporary folder print('\nCreate temporary folder...') path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S") status, output = sct.run('mkdir '+path_tmp) # copy files to temporary folder print('\nCopy files...') status, output = sct.run('sct_c3d '+fname_data+' -o '+path_tmp+'/data.nii') status, output = sct.run('sct_c3d '+fname_landmarks+' -o '+path_tmp+'/landmarks.nii.gz') status, output = sct.run('sct_c3d '+fname_seg+' -o '+path_tmp+'/segmentation.nii.gz') # go to tmp folder os.chdir(path_tmp) # Change orientation of input images to RPI print('\nChange orientation of input images to RPI...') status, output = sct.run('sct_orientation -i data.nii -o data_rpi.nii -orientation RPI') status, output = sct.run('sct_orientation -i landmarks.nii.gz -o landmarks_rpi.nii.gz -orientation RPI') status, output = sct.run('sct_orientation -i segmentation.nii.gz -o segmentation_rpi.nii.gz -orientation RPI') # Straighten the spinal cord using centerline/segmentation print('\nStraighten the spinal cord using centerline/segmentation...') status, output = sct.run('sct_straighten_spinalcord -i data_rpi.nii -c segmentation_rpi.nii.gz -r '+str(remove_temp_files)) # Apply straightening to segmentation print('\nApply straightening to segmentation...') sct.run('sct_WarpImageMultiTransform 3 segmentation_rpi.nii.gz segmentation_rpi_straight.nii.gz -R data_rpi_straight.nii warp_curve2straight.nii.gz') # Smoothing along centerline to improve accuracy and remove step effects print('\nSmoothing along centerline to improve accuracy and remove step effects...') sct.run('sct_c3d data_rpi_straight.nii -smooth 0x0x'+str(smoothing_sigma)+'vox -o data_rpi_straight.nii') sct.run('sct_c3d segmentation_rpi_straight.nii.gz -smooth 0x0x'+str(smoothing_sigma)+'vox -o segmentation_rpi_straight.nii.gz') # Label preparation: # -------------------------------------------------------------------------------- # Remove unused label on template. Keep only label present in the input label image print('\nRemove unused label on template. Keep only label present in the input label image...') status, output = sct.run('sct_label_utils -t remove -i '+fname_template_label+' -o template_label.nii.gz -r landmarks_rpi.nii.gz') # Create a cross for the template labels - 5 mm print('\nCreate a 5 mm cross for the template labels...') status, output = sct.run('sct_label_utils -t cross -i template_label.nii.gz -o template_label_cross.nii.gz -c 5') # Create a cross for the input labels and dilate for straightening preparation - 5 mm print('\nCreate a 5mm cross for the input labels and dilate for straightening preparation...') status, output = sct.run('sct_label_utils -t cross -i landmarks_rpi.nii.gz -o landmarks_rpi_cross3x3.nii.gz -c 5 -d') # Push the input labels in the template space print('\nPush the input labels to the straight space...') status, output = sct.run('sct_WarpImageMultiTransform 3 landmarks_rpi_cross3x3.nii.gz landmarks_rpi_cross3x3_straight.nii.gz -R data_rpi_straight.nii warp_curve2straight.nii.gz --use-NN') # Convert landmarks from FLOAT32 to INT print '\nConvert landmarks from FLOAT32 to INT...' sct.run('sct_c3d landmarks_rpi_cross3x3_straight.nii.gz -type int -o landmarks_rpi_cross3x3_straight.nii.gz') # Estimate affine transfo: straight --> template (landmark-based)' print '\nEstimate affine transfo: straight anat --> template (landmark-based)...' sct.run('sct_ANTSUseLandmarkImagesToGetAffineTransform template_label_cross.nii.gz landmarks_rpi_cross3x3_straight.nii.gz affine straight2templateAffine.txt') # Apply affine transformation: straight --> template print '\nApply affine transformation: straight --> template...' sct.run('sct_WarpImageMultiTransform 3 data_rpi_straight.nii data_rpi_straight2templateAffine.nii straight2templateAffine.txt -R '+fname_template) sct.run('sct_WarpImageMultiTransform 3 segmentation_rpi_straight.nii.gz segmentation_rpi_straight2templateAffine.nii.gz straight2templateAffine.txt -R '+fname_template) # now threshold at 0.5 (for partial volume interpolation) # do not do that anymore-- better to estimate transformation using trilinear interp image to avoid step effect. See issue #31 on github. # sct.run('sct_c3d segmentation_rpi_straight2templateAffine.nii.gz -threshold -inf 0.5 0 1 -o segmentation_rpi_straight2templateAffine.nii.gz') # Registration straight spinal cord to template print('\nRegister straight spinal cord to template...') #nb_iterations = '50x15' # TODO: nb iteration for step 2 sct.run('sct_register_multimodal -i data_rpi_straight2templateAffine.nii -d '+fname_template+' -s segmentation_rpi_straight2templateAffine.nii.gz -t '+fname_template_seg+' -r '+str(remove_temp_files)+' -n '+nb_iterations+' -v '+str(verbose)+' -x 1',verbose) # status, output = sct.run('sct_register_straight_spinalcord_to_template -i data_rpi_straight.nii.gz -l landmarks_rpi_cross3x3_straight.nii.gz -t '+path_template+'/MNI-Poly-AMU_T2.nii.gz -f template_label_cross.nii.gz -m '+path_template+'/mask_gaussian_templatespace_sigma20.nii.gz -r 1 -n '+nb_iterations+' -v 1') # Concatenate warping fields: template2anat & anat2template print('\nConcatenate warping fields: template2anat & anat2template...') cmd = 'sct_ComposeMultiTransform 3 warp_template2anat.nii.gz -R data.nii warp_straight2curve.nii.gz -i straight2templateAffine.txt warp_dest2src.nii.gz' print '>> '+cmd commands.getstatusoutput(cmd) cmd = 'sct_ComposeMultiTransform 3 warp_anat2template.nii.gz -R '+fname_template+' warp_src2dest.nii.gz straight2templateAffine.txt warp_curve2straight.nii.gz' print '>> '+cmd commands.getstatusoutput(cmd) # Apply warping fields to anat and template if output_type == 1: sct.run('sct_WarpImageMultiTransform 3 '+fname_template+' template2anat.nii.gz -R data.nii warp_template2anat.nii.gz') sct.run('sct_WarpImageMultiTransform 3 data.nii.gz anat2template.nii.gz -R '+fname_template+' warp_anat2template.nii.gz') # come back to parent folder os.chdir('..') # Generate output files print('\nGenerate output files...') sct.generate_output_file(path_tmp+'/warp_template2anat.nii.gz', 'warp_template2anat.nii.gz') sct.generate_output_file(path_tmp+'/warp_anat2template.nii.gz', 'warp_anat2template.nii.gz') if output_type == 1: sct.generate_output_file(path_tmp+'/template2anat.nii.gz', 'template2anat'+ext_data) sct.generate_output_file(path_tmp+'/anat2template.nii.gz', 'anat2template'+ext_data) # Delete temporary files if remove_temp_files == 1: print '\nDelete temporary files...' sct.run('rm -rf '+path_tmp) # display elapsed time elapsed_time = time.time() - start_time print '\nFinished! Elapsed time: '+str(int(round(elapsed_time)))+'s' # to view results print '\nTo view results, type:' print 'fslview template2anat -b 0,4000 '+fname_data+' &' print 'fslview anat2template '+fname_template+' -b 0,4000 &\n' # Print usage # ========================================================================================== def usage(): print '\n' \ ''+os.path.basename(__file__)+'\n' \ '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' \ 'Part of the Spinal Cord Toolbox <https://sourceforge.net/projects/spinalcordtoolbox>\n' \ '\n'\ 'DESCRIPTION\n' \ ' Register anatomical image to the template.\n' \ '\n' \ 'USAGE\n' \ ' '+os.path.basename(__file__)+' -i <anat> -l <landmarks> -m <segmentation>\n' \ '\n' \ 'MANDATORY ARGUMENTS\n' \ ' -i <anat> anatomical image\n' \ ' -l <landmarks> landmarks at spinal cord center. See: http://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels/\n' \ ' -m <segmentation> spinal cord segmentation. \n' \ '\n' \ 'OPTIONAL ARGUMENTS\n' \ ' -o {0, 1} output type. 0: warp, 1: warp+images. Default='+str(param.output_type)+'\n' \ ' -s {slow, normal, fast} Speed of registration. Slow gives the best results. Default='+param.speed+'\n' \ ' -r {0, 1} remove temporary files. Default='+str(param.remove_temp_files)+'\n' \ ' -t {0, 1} use down sampled template files (for testing)' # exit program sys.exit(2) # START PROGRAM # ========================================================================================== if __name__ == "__main__": # initialize parameters param = param() # call main function main()
import argparse from collections import OrderedDict import os import subprocess import logging import sys from jinja2 import Environment, PackageLoader logger = logging.getLogger(__name__) if sys.version[0] == '2': FileNotFoundError = OSError # Jinja2 tests and filters, available in all templates def jinja_filter_param_value_str(value, str_quote_style="", bool_is_str=False): """ Convert a parameter value to string suitable to be passed to an EDA tool Rules: - Booleans are represented as 0/1 or "true"/"false" depending on the bool_is_str argument - Strings are either passed through or enclosed in the characters specified in str_quote_style (e.g. '"' or '\\"') - Everything else (including int, float, etc.) are converted using the str() function. """ if type(value) == bool: if bool_is_str: return 'true' if value else 'false' else: return '1' if value else '0' elif type(value) == str or ((type(value) == bool) and bool_is_str): return str_quote_style + str(value) + str_quote_style else: return str(value) class FileAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): path = os.path.expandvars(values[0]) path = os.path.expanduser(path) path = os.path.abspath(path) setattr(namespace, self.dest, [path]) class Edatool(object): def __init__(self, edam=None, work_root=None, eda_api=None): _tool_name = self.__class__.__name__.lower() if not edam: edam = eda_api try: self.name = edam['name'] except KeyError: raise RuntimeError("Missing required parameter 'name'") self.tool_options = edam.get('tool_options', {}).get(_tool_name, {}) self.files = edam.get('files', []) self.toplevel = edam.get('toplevel', []) self.vpi_modules = edam.get('vpi', []) self.hooks = edam.get('hooks', {}) self.parameters = edam.get('parameters', {}) self.work_root = work_root self.env = os.environ.copy() self.env['WORK_ROOT'] = self.work_root self.plusarg = OrderedDict() self.vlogparam = OrderedDict() self.vlogdefine = OrderedDict() self.generic = OrderedDict() self.cmdlinearg = OrderedDict() self.parsed_args = False self.jinja_env = Environment( loader = PackageLoader(__package__, 'templates'), trim_blocks = True, lstrip_blocks = True, keep_trailing_newline = True, ) self.jinja_env.filters['param_value_str'] = jinja_filter_param_value_str self.jinja_env.filters['generic_value_str'] = jinja_filter_param_value_str @classmethod def get_doc(cls, api_ver): if api_ver == 0: desc = getattr(cls, '_description', 'Options for {} backend'.format(cls.__name__)) opts = {'description' : desc} for group in ['members', 'lists', 'dicts']: if group in cls.tool_options: opts[group] = [] for _name, _type in cls.tool_options[group].items(): opts[group].append({'name' : _name, 'type' : _type, 'desc' : ''}) return opts else: logger.warning("Invalid API version '{}' for get_tool_options".format(api_ver)) def configure(self, args): logger.info("Setting up project") self.configure_pre(args) self.configure_main() self.configure_post() def configure_pre(self, args): self.parse_args(args, self.argtypes) def configure_main(self): pass def configure_post(self): pass def build(self): self.build_pre() self.build_main() self.build_post() def build_pre(self): if 'pre_build' in self.hooks: self._run_scripts(self.hooks['pre_build'], 'pre_build') def build_main(self): logger.info("Building"); self._run_tool('make') def build_post(self): if 'post_build' in self.hooks: self._run_scripts(self.hooks['post_build'], 'post_build') def run(self, args): logger.info("Running") self.run_pre(args) self.run_main() self.run_post() def run_pre(self, args): self.parse_args(args, self.argtypes) if 'pre_run' in self.hooks: self._run_scripts(self.hooks['pre_run'], 'pre_run') def run_main(self): pass def run_post(self): if 'post_run' in self.hooks: self._run_scripts(self.hooks['post_run'], 'post_run') def parse_args(self, args, paramtypes): if self.parsed_args: return typedict = {'bool' : {'action' : 'store_true'}, 'file' : {'type' : str , 'nargs' : 1, 'action' : FileAction}, 'int' : {'type' : int , 'nargs' : 1}, 'str' : {'type' : str , 'nargs' : 1}, } progname = os.path.basename(sys.argv[0]) + ' run {}'.format(self.name) parser = argparse.ArgumentParser(prog = progname, conflict_handler='resolve') param_groups = {} _descr = {'plusarg' : 'Verilog plusargs (Run-time option)', 'vlogparam' : 'Verilog parameters (Compile-time option)', 'vlogdefine' : 'Verilog defines (Compile-time global symbol)', 'generic' : 'VHDL generic (Run-time option)', 'cmdlinearg' : 'Command-line arguments (Run-time option)'} param_type_map = {} for name, param in self.parameters.items(): _description = param.get('description', "No description") _paramtype = param['paramtype'] if _paramtype in paramtypes: if not _paramtype in param_groups: param_groups[_paramtype] = \ parser.add_argument_group(_descr[_paramtype]) default = None if not param.get('default') is None: try: if param['datatype'] == 'bool': default = param['default'] else: default = [typedict[param['datatype']]['type'](param['default'])] except KeyError as e: pass try: param_groups[_paramtype].add_argument('--'+name, help=_description, default=default, **typedict[param['datatype']]) except KeyError as e: raise RuntimeError("Invalid data type {} for parameter '{}'".format(str(e), name)) param_type_map[name.replace('-','_')] = _paramtype else: logging.warn("Parameter '{}' has unsupported type '{}' for requested backend".format(name, _paramtype)) #backend_args. backend_args = parser.add_argument_group("Backend arguments") _opts = self.__class__.get_doc(0) for _opt in _opts.get('members', []) + _opts.get('lists', []): backend_args.add_argument('--'+_opt['name'], help=_opt['desc']) #Parse arguments backend_members = [x['name'] for x in _opts.get('members', [])] backend_lists = [x['name'] for x in _opts.get('lists', [])] for key,value in sorted(vars(parser.parse_args(args)).items()): if value is None: continue if key in backend_members: self.tool_options[key] = value continue if key in backend_lists: if not key in self.tool_options: self.tool_options[key] = [] self.tool_options[key] += value.split(' ') continue paramtype = param_type_map[key] if type(value) == bool: _value = value else: _value = value[0] getattr(self, paramtype)[key] = _value self.parsed_args = True def render_template(self, template_file, target_file, template_vars = {}): """ Render a Jinja2 template for the backend The template file is expected in the directory templates/BACKEND_NAME. """ template_dir = str(self.__class__.__name__).lower() template = self.jinja_env.get_template('/'.join([template_dir, template_file])) file_path = os.path.join(self.work_root, target_file) with open(file_path, 'w') as f: f.write(template.render(template_vars)) def _get_fileset_files(self, force_slash=False): class File: def __init__(self, name, file_type, logical_name): self.name = name self.file_type = file_type self.logical_name = logical_name incdirs = [] src_files = [] for f in self.files: if 'is_include_file' in f and f['is_include_file']: _incdir = os.path.dirname(f['name']) or '.' if force_slash: _incdir = _incdir.replace('\\', '/') if not _incdir in incdirs: incdirs.append(_incdir) else: _name = f['name'] if force_slash: _name = _name.replace('\\', '/') file_type = f.get('file_type', '') logical_name = f.get('logical_name', '') src_files.append(File(_name, file_type, logical_name)) return (src_files, incdirs) def _param_value_str(self, param_value, str_quote_style="", bool_is_str=False): return jinja_filter_param_value_str(param_value, str_quote_style, bool_is_str) def _run_scripts(self, scripts, hook_name): for script in scripts: _env = self.env.copy() if 'env' in script: _env.update(script['env']) logger.info("Running {} script {}".format(hook_name, script['name'])) logger.debug("Environment: " + str(_env)) logger.debug("Working directory: " + self.work_root) try: subprocess.check_call(script['cmd'], cwd = self.work_root, env = _env) except FileNotFoundError as e: msg = "Unable to run {} script '{}': {}" raise RuntimeError(msg.format(hook_name, script['name'], str(e))) except subprocess.CalledProcessError as e: msg = "{} script '{}' exited with error code {}" raise RuntimeError(msg.format(hook_name, script['name'], e.returncode)) def _run_tool(self, cmd, args=[]): logger.debug("Running " + cmd) logger.debug("args : " + ' '.join(args)) try: subprocess.check_call([cmd] + args, cwd = self.work_root, stdin=subprocess.PIPE), except FileNotFoundError: _s = "Command '{}' not found. Make sure it is in $PATH" raise RuntimeError(_s.format(cmd)) except subprocess.CalledProcessError: _s = "'{}' exited with an error code" raise RuntimeError(_s.format(cmd)) def _write_fileset_to_f_file(self, output_file, include_vlogparams = True): """ Write a file list (*.f) file Returns a list of all files which were not added to the *.f file """ with open(output_file, 'w') as f: unused_files = [] (src_files, incdirs) = self._get_fileset_files() for key, value in self.vlogdefine.items(): define_str = self._param_value_str(param_value = value) f.write('+define+{}={}\n'.format(key, define_str)) if include_vlogparams: for key, value in self.vlogparam.items(): param_str = self._param_value_str(param_value = value, str_quote_style = '"') f.write('-pvalue+{}.{}={}\n'.format(self.toplevel, key, param_str)) for id in incdirs: f.write("+incdir+" + id + '\n') for src_file in src_files: if (src_file.file_type.startswith("verilogSource") or src_file.file_type.startswith("systemVerilogSource")): f.write(src_file.name + '\n') else: unused_files.append(src_file) return unused_files edatool: add option to call make with target import argparse from collections import OrderedDict import os import subprocess import logging import sys from jinja2 import Environment, PackageLoader logger = logging.getLogger(__name__) if sys.version[0] == '2': FileNotFoundError = OSError # Jinja2 tests and filters, available in all templates def jinja_filter_param_value_str(value, str_quote_style="", bool_is_str=False): """ Convert a parameter value to string suitable to be passed to an EDA tool Rules: - Booleans are represented as 0/1 or "true"/"false" depending on the bool_is_str argument - Strings are either passed through or enclosed in the characters specified in str_quote_style (e.g. '"' or '\\"') - Everything else (including int, float, etc.) are converted using the str() function. """ if type(value) == bool: if bool_is_str: return 'true' if value else 'false' else: return '1' if value else '0' elif type(value) == str or ((type(value) == bool) and bool_is_str): return str_quote_style + str(value) + str_quote_style else: return str(value) class FileAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): path = os.path.expandvars(values[0]) path = os.path.expanduser(path) path = os.path.abspath(path) setattr(namespace, self.dest, [path]) class Edatool(object): def __init__(self, edam=None, work_root=None, eda_api=None): _tool_name = self.__class__.__name__.lower() if not edam: edam = eda_api try: self.name = edam['name'] except KeyError: raise RuntimeError("Missing required parameter 'name'") self.tool_options = edam.get('tool_options', {}).get(_tool_name, {}) self.files = edam.get('files', []) self.toplevel = edam.get('toplevel', []) self.vpi_modules = edam.get('vpi', []) self.hooks = edam.get('hooks', {}) self.parameters = edam.get('parameters', {}) self.work_root = work_root self.env = os.environ.copy() self.env['WORK_ROOT'] = self.work_root self.plusarg = OrderedDict() self.vlogparam = OrderedDict() self.vlogdefine = OrderedDict() self.generic = OrderedDict() self.cmdlinearg = OrderedDict() self.parsed_args = False self.jinja_env = Environment( loader = PackageLoader(__package__, 'templates'), trim_blocks = True, lstrip_blocks = True, keep_trailing_newline = True, ) self.jinja_env.filters['param_value_str'] = jinja_filter_param_value_str self.jinja_env.filters['generic_value_str'] = jinja_filter_param_value_str @classmethod def get_doc(cls, api_ver): if api_ver == 0: desc = getattr(cls, '_description', 'Options for {} backend'.format(cls.__name__)) opts = {'description' : desc} for group in ['members', 'lists', 'dicts']: if group in cls.tool_options: opts[group] = [] for _name, _type in cls.tool_options[group].items(): opts[group].append({'name' : _name, 'type' : _type, 'desc' : ''}) return opts else: logger.warning("Invalid API version '{}' for get_tool_options".format(api_ver)) def configure(self, args): logger.info("Setting up project") self.configure_pre(args) self.configure_main() self.configure_post() def configure_pre(self, args): self.parse_args(args, self.argtypes) def configure_main(self): pass def configure_post(self): pass def build(self): self.build_pre() self.build_main() self.build_post() def build_pre(self): if 'pre_build' in self.hooks: self._run_scripts(self.hooks['pre_build'], 'pre_build') def build_main(self, target=None): logger.info("Building{}".format("" if target is None else "target " + " ".join(target))) self._run_tool('make', [] if target is None else [target]) def build_post(self): if 'post_build' in self.hooks: self._run_scripts(self.hooks['post_build'], 'post_build') def run(self, args): logger.info("Running") self.run_pre(args) self.run_main() self.run_post() def run_pre(self, args): self.parse_args(args, self.argtypes) if 'pre_run' in self.hooks: self._run_scripts(self.hooks['pre_run'], 'pre_run') def run_main(self): pass def run_post(self): if 'post_run' in self.hooks: self._run_scripts(self.hooks['post_run'], 'post_run') def parse_args(self, args, paramtypes): if self.parsed_args: return typedict = {'bool' : {'action' : 'store_true'}, 'file' : {'type' : str , 'nargs' : 1, 'action' : FileAction}, 'int' : {'type' : int , 'nargs' : 1}, 'str' : {'type' : str , 'nargs' : 1}, } progname = os.path.basename(sys.argv[0]) + ' run {}'.format(self.name) parser = argparse.ArgumentParser(prog = progname, conflict_handler='resolve') param_groups = {} _descr = {'plusarg' : 'Verilog plusargs (Run-time option)', 'vlogparam' : 'Verilog parameters (Compile-time option)', 'vlogdefine' : 'Verilog defines (Compile-time global symbol)', 'generic' : 'VHDL generic (Run-time option)', 'cmdlinearg' : 'Command-line arguments (Run-time option)'} param_type_map = {} for name, param in self.parameters.items(): _description = param.get('description', "No description") _paramtype = param['paramtype'] if _paramtype in paramtypes: if not _paramtype in param_groups: param_groups[_paramtype] = \ parser.add_argument_group(_descr[_paramtype]) default = None if not param.get('default') is None: try: if param['datatype'] == 'bool': default = param['default'] else: default = [typedict[param['datatype']]['type'](param['default'])] except KeyError as e: pass try: param_groups[_paramtype].add_argument('--'+name, help=_description, default=default, **typedict[param['datatype']]) except KeyError as e: raise RuntimeError("Invalid data type {} for parameter '{}'".format(str(e), name)) param_type_map[name.replace('-','_')] = _paramtype else: logging.warn("Parameter '{}' has unsupported type '{}' for requested backend".format(name, _paramtype)) #backend_args. backend_args = parser.add_argument_group("Backend arguments") _opts = self.__class__.get_doc(0) for _opt in _opts.get('members', []) + _opts.get('lists', []): backend_args.add_argument('--'+_opt['name'], help=_opt['desc']) #Parse arguments backend_members = [x['name'] for x in _opts.get('members', [])] backend_lists = [x['name'] for x in _opts.get('lists', [])] for key,value in sorted(vars(parser.parse_args(args)).items()): if value is None: continue if key in backend_members: self.tool_options[key] = value continue if key in backend_lists: if not key in self.tool_options: self.tool_options[key] = [] self.tool_options[key] += value.split(' ') continue paramtype = param_type_map[key] if type(value) == bool: _value = value else: _value = value[0] getattr(self, paramtype)[key] = _value self.parsed_args = True def render_template(self, template_file, target_file, template_vars = {}): """ Render a Jinja2 template for the backend The template file is expected in the directory templates/BACKEND_NAME. """ template_dir = str(self.__class__.__name__).lower() template = self.jinja_env.get_template('/'.join([template_dir, template_file])) file_path = os.path.join(self.work_root, target_file) with open(file_path, 'w') as f: f.write(template.render(template_vars)) def _get_fileset_files(self, force_slash=False): class File: def __init__(self, name, file_type, logical_name): self.name = name self.file_type = file_type self.logical_name = logical_name incdirs = [] src_files = [] for f in self.files: if 'is_include_file' in f and f['is_include_file']: _incdir = os.path.dirname(f['name']) or '.' if force_slash: _incdir = _incdir.replace('\\', '/') if not _incdir in incdirs: incdirs.append(_incdir) else: _name = f['name'] if force_slash: _name = _name.replace('\\', '/') file_type = f.get('file_type', '') logical_name = f.get('logical_name', '') src_files.append(File(_name, file_type, logical_name)) return (src_files, incdirs) def _param_value_str(self, param_value, str_quote_style="", bool_is_str=False): return jinja_filter_param_value_str(param_value, str_quote_style, bool_is_str) def _run_scripts(self, scripts, hook_name): for script in scripts: _env = self.env.copy() if 'env' in script: _env.update(script['env']) logger.info("Running {} script {}".format(hook_name, script['name'])) logger.debug("Environment: " + str(_env)) logger.debug("Working directory: " + self.work_root) try: subprocess.check_call(script['cmd'], cwd = self.work_root, env = _env) except FileNotFoundError as e: msg = "Unable to run {} script '{}': {}" raise RuntimeError(msg.format(hook_name, script['name'], str(e))) except subprocess.CalledProcessError as e: msg = "{} script '{}' exited with error code {}" raise RuntimeError(msg.format(hook_name, script['name'], e.returncode)) def _run_tool(self, cmd, args=[]): logger.debug("Running " + cmd) logger.debug("args : " + ' '.join(args)) try: subprocess.check_call([cmd] + args, cwd = self.work_root, stdin=subprocess.PIPE), except FileNotFoundError: _s = "Command '{}' not found. Make sure it is in $PATH" raise RuntimeError(_s.format(cmd)) except subprocess.CalledProcessError: _s = "'{}' exited with an error code" raise RuntimeError(_s.format(cmd)) def _write_fileset_to_f_file(self, output_file, include_vlogparams = True): """ Write a file list (*.f) file Returns a list of all files which were not added to the *.f file """ with open(output_file, 'w') as f: unused_files = [] (src_files, incdirs) = self._get_fileset_files() for key, value in self.vlogdefine.items(): define_str = self._param_value_str(param_value = value) f.write('+define+{}={}\n'.format(key, define_str)) if include_vlogparams: for key, value in self.vlogparam.items(): param_str = self._param_value_str(param_value = value, str_quote_style = '"') f.write('-pvalue+{}.{}={}\n'.format(self.toplevel, key, param_str)) for id in incdirs: f.write("+incdir+" + id + '\n') for src_file in src_files: if (src_file.file_type.startswith("verilogSource") or src_file.file_type.startswith("systemVerilogSource")): f.write(src_file.name + '\n') else: unused_files.append(src_file) return unused_files
import io import time import os from pathlib import Path from typing import Generic, Callable, List import numpy as np import sys from PIL import Image as PILImage, ImageChops from PIL import ImageDraw from kivy.app import App from kivy.core.clipboard import Clipboard from kivy.core.image import Image as CoreImage from kivy.core.window import Window from kivy.graphics.context_instructions import Color from kivy.graphics.instructions import InstructionGroup from kivy.graphics.vertex_instructions import Line, Rectangle from kivy.properties import ObjectProperty, NumericProperty, BooleanProperty, Clock, partial, StringProperty from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image from kivy.uix.label import Label from kivy.uix.stacklayout import StackLayout from kivy.uix.stencilview import StencilView from kivy.uix.widget import Widget class SpriteEditorApp(App): def __init__(self): super(SpriteEditorApp, self).__init__() self.canvas: 'SpriteEditorWidget' = None def build(self): self.canvas = SpriteEditorWidget() self.title = "Sprite Extractor" return self.canvas class SpriteEditorInfoLabel(Label): name = StringProperty() val_format = StringProperty() def __init__(self, **kwargs): super(SpriteEditorInfoLabel, self).__init__(**kwargs) def set_value(self, value): formatted = self.val_format % value self.text = f"{self.name}: {formatted}" class SpriteEditorWidget(Widget): image: PILImage = ObjectProperty(None) core_image: CoreImage = ObjectProperty(None) image_path: str = StringProperty(None) def _create_info_label(self, name, val_format="%i"): label = SpriteEditorInfoLabel(halign="left", text_size=(200, 32), size=(200, 20), size_hint=(1, None), padding=[8, 8]) label.name = name label.val_format = val_format self.info_stack.add_widget(label) return label def _create_tool_button(self, name, pressed: Callable): result = Button(text=name, size=(200, 50), size_hint=(1, None)) result.bind(on_press=pressed) self.tool_stack.add_widget(result) return result def __init__(self, **kwargs): super(SpriteEditorWidget, self).__init__(**kwargs) # self.images = dict() self.root = BoxLayout(orientation='horizontal') # self.root = FloatLayout(size=(Window.width, Window.height)) # self.grid = GridLayout(cols=8) self.add_widget(self.root) self.viewer = SpriteEditorViewer(owner=self, size_hint=(.7, 1)) self.viewer.padding = [4, 4] self.root.add_widget(self.viewer) self.toolbox = BoxLayout(orientation='vertical', size=(200, 50), size_hint=(None, 1)) self.root.add_widget(self.toolbox) tool_stack = StackLayout(size=(200, 50), size_hint=(None, 0.7)) tool_stack.orientation = "tb-lr" tool_stack.padding = [4, 4] self.toolbox.add_widget(tool_stack) self.tool_stack = tool_stack # self._create_tool_button('Load Image', self.load_image_press) self._create_tool_button('Toggle Grid', self.toggle_grid_press) self.select_button = self._create_tool_button('Select Region', self.select_press) self._create_tool_button('Copy Region to Clipboard', self.copy_region_press) self._create_tool_button('Create Sprite', self.create_sprite_press) self._create_tool_button('Find Unique Colors', self.find_unique_press) self._create_tool_button('Highlight Unique Colors', self.highlight_unique_press) self._create_tool_button('Extract Transparent Sprite', self.extract_transparent_press) info_stack = StackLayout(size=(200, 50), size_hint=(None, 0.3)) info_stack.orientation = "tb-lr" info_stack.padding = [4, 4] self.info_stack = info_stack self.x_label = self._create_info_label("x") self.y_label = self._create_info_label("y") self.sel_x_label = self._create_info_label("sel x") self.sel_y_label = self._create_info_label("sel y") self.sel_width_label = self._create_info_label("sel width") self.sel_height_label = self._create_info_label("sel height") self.toolbox.add_widget(info_stack) Window.bind(on_resize=self.on_window_resize) Window.clearcolor = (0.136, 0.191, 0.25, 1) Window.bind(on_dropfile=self._on_drop_file) self.root.size = (Window.width, Window.height) if len(sys.argv) > 1: self.load_image(sys.argv[1]) def _on_drop_file(self, window, file_path): print(file_path) self.load_image(file_path) def copy_region_press(self, *args): region = self.viewer.selection Clipboard.copy(f"\"REGION\": ({region.sel_y}, {region.sel_x}," + f" {region.sel_y + region.sel_height}, {region.sel_x + region.sel_width})") @staticmethod def date_for_filename(): return time.strftime("%Y%m%d%H%M%S", time.localtime()) def extract_transparent_press(self, *args): point_table = ([0] + ([255] * 255)) def diff_image(a, b): diff = ImageChops.difference(a, b) diff = diff.convert('L') diff = diff.point(point_table) diff = ImageChops.invert(diff) new = diff.convert('RGB') new.paste(b, mask=diff) return new p = Path(self.image_path) p = p.parents[0] sections = [] for root, dirs, files in os.walk(p): print(root, dirs, files) for file in files: if not file.endswith(".png"): continue image = PILImage.open(file) section = self.get_selection_image(image) sections.append(section) result = sections.pop() for section in sections: result = diff_image(result, section) self.save_image("../extracted", result) def highlight_unique_press(self, *args): sprite = np.array(self.get_selection_image()).tolist() unique = self.find_unique_colors() result = [] for rows in sprite: row = [] for pixel in rows: if pixel in unique: row.append(pixel) else: row.append([0, 0, 0]) result.append(row) result = np.array(result) result_image = PILImage.fromarray(result.astype('uint8'), "RGB") self.save_image("highlight", result_image) def get_selection_region(self): region = self.viewer.selection selection = (region.sel_x - 1, region.sel_y - 1, region.sel_x + region.sel_width - 1, region.sel_y + region.sel_height - 1) return selection def get_selection_image(self, custom_image=None) -> PILImage: if custom_image is None: image: PILImage = self.image else: image = custom_image selection = self.get_selection_region() sprite = image.crop(selection) return sprite def find_unique_colors(self) -> List[List[int]]: selection = self.get_selection_region() sprite = self.get_selection_image() image: PILImage = self.image.copy() draw = ImageDraw.Draw(image) draw.rectangle(selection, fill=0) del draw rest_pixels = np.array(image) sprite_pixels = np.array(sprite) rest_colors = np.unique(rest_pixels.reshape(-1, 3), axis=0).tolist() rest_colors = [item for item in rest_colors if item is not [0, 0, 0]] sprite_colors = np.unique(sprite_pixels.reshape(-1, 3), axis=0).tolist() unique_colors = [item for item in sprite_colors if item not in rest_colors] if len(unique_colors) == 0: print("No unique colors found") return unique_colors.sort(reverse=True) return unique_colors def save_image(self, name, image): p = Path(self.image_path) p = p.parents[0] / f"{name}_{self.date_for_filename()}.png" print(p) image.save(p) print("File written to:", p) def find_unique_press(self, *args): unique_colors = self.find_unique_colors() unique_colors = np.array([unique_colors]) print(unique_colors) print(unique_colors.shape) unique_color_image = PILImage.fromarray(unique_colors.astype('uint8'), "RGB") self.save_image("unique", unique_color_image) def create_sprite_press(self, *args): sprite = self.get_selection_image() self.save_image("sprite", sprite) def toggle_grid_press(self, *args): self.viewer.toggle_grid() def on_image_path(self, *args): self.image = PILImage.open(self.image_path) # CoreImage(path, keep_data=True) def load_image(self, path): self.image_path = path def on_image(self, sender, image: PILImage): print("Image set") image = self.image.convert("RGB") image_file = io.BytesIO() image.save(image_file, "png") image_file.seek(0) self.core_image = CoreImage(image_file, ext="png") self.viewer.set_texture(self.core_image.texture) def select_press(self, *args): self.viewer.tool = RegionTool() def on_window_resize(self, window, width, height): self.root.size = (width, height) class Tool: def begin(self, editor: 'SpriteEditorViewer'): pass def end(self, editor: 'SpriteEditorViewer'): pass def down(self, editor: 'SpriteEditorViewer', touch): pass def up(self, editor: 'SpriteEditorViewer', touch): pass def move(self, editor: 'SpriteEditorViewer', touch): pass class ZoomTool(Tool): def down(self, editor: 'SpriteEditorViewer', touch): local_pos = editor.image.to_local(touch.x, touch.y, relative=True) if touch.button == "scrolldown": editor.set_scale(editor.zoom_ratio, local_pos) return True elif touch.button == "scrollup": editor.set_scale(1.0 / editor.zoom_ratio, local_pos) return True class PanZoomTool(ZoomTool): def move(self, editor: 'SpriteEditorViewer', touch): editor.image.x += touch.dx editor.image.y += touch.dy super().move(editor, touch) class RegionTool(Tool): def begin(self, editor: 'SpriteEditorViewer'): editor.selection.visible = False editor.selection.sel_x = 0 editor.selection.sel_y = 0 editor.selection.sel_width = 0 editor.selection.sel_height = 0 editor.owner.select_button.background_color = [0, 1, 0, 1] def end(self, editor: 'SpriteEditorViewer'): editor.owner.select_button.background_color = [1, 1, 1, 1] def down(self, editor: 'SpriteEditorViewer', touch): local_pos = editor.window_pos_to_image((touch.x, touch.y)) editor.selection.sel_x = local_pos[0] editor.selection.sel_y = local_pos[1] editor.selection.visible = True def move(self, editor: 'SpriteEditorViewer', touch): local_pos = editor.window_pos_to_image((touch.x, touch.y)) editor.selection.sel_width = (local_pos[0] - editor.selection.sel_x) + 1 editor.selection.sel_height = (local_pos[1] - editor.selection.sel_y) + 1 def up(self, editor: 'SpriteEditorViewer', touch): local_pos = editor.window_pos_to_image((touch.x, touch.y)) editor.selection.sel_width = (local_pos[0] - editor.selection.sel_x) + 1 editor.selection.sel_height = (local_pos[1] - editor.selection.sel_y) + 1 editor.tool = PanZoomTool() class RegionSelection(Widget): sel_x = NumericProperty(0.0) sel_y = NumericProperty(0.0) sel_width = NumericProperty(0.0) sel_height = NumericProperty(0.0) visible = BooleanProperty(False) rect = ObjectProperty(None) def __init__(self, viewer: 'SpriteEditorViewer' = None, **kwargs): super(RegionSelection, self).__init__(**kwargs) self.viewer = viewer self.bind(sel_x=self.update, sel_y=self.update, sel_width=self.update, sel_height=self.update) self.viewer.image.bind(size=self.update, pos=self.update) self.viewer.bind(xscale=self.update, yscale=self.update) self.bind(visible=self.redraw) self._keyboard = Window.request_keyboard( self._keyboard_closed, self, 'text') if self._keyboard.widget: pass self._keyboard.bind(on_key_down=self._on_keyboard_down) def _keyboard_closed(self): print('My keyboard have been closed!') self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): amount = 1 if "shift" in modifiers: amount = 5 if "alt" in modifiers: if keycode[1] == "up": self.sel_height += amount self.sel_y -= amount return True elif keycode[1] == "down": self.sel_height -= amount self.sel_y += amount return True elif keycode[1] == "left": self.sel_width += amount self.sel_x -= amount return True elif keycode[1] == "right": self.sel_width -= amount self.sel_x += amount return True elif "ctrl" in modifiers: if keycode[1] == "up": self.sel_height -= amount return True elif keycode[1] == "down": self.sel_height += amount return True elif keycode[1] == "left": self.sel_width -= amount return True elif keycode[1] == "right": self.sel_width += amount return True else: if keycode[1] == "up": self.sel_y -= amount return True elif keycode[1] == "down": self.sel_y += amount return True elif keycode[1] == "left": self.sel_x -= amount return True elif keycode[1] == "right": self.sel_x += amount return True return False def update(self, *args): if self.rect is None: self.redraw() return self.rect.pos = self.viewer.image_pos_to_window((self.sel_x - 1, self.sel_y + self.sel_height - 1)) self.rect.size = self.viewer.image_size_to_window(self.sel_width, self.sel_height) self.viewer.owner.sel_x_label.set_value(self.sel_x) self.viewer.owner.sel_y_label.set_value(self.sel_y) self.viewer.owner.sel_width_label.set_value(self.sel_width) self.viewer.owner.sel_height_label.set_value(self.sel_height) def redraw(self, *args): self.canvas.clear() if not self.visible: return with self.canvas: Color(0.5, 1, 0.5, 0.3) self.rect = Rectangle() self.update() class SpriteEditorViewer(FloatLayout, StencilView): image = ObjectProperty(None) selection = ObjectProperty(None) zoom_ratio = NumericProperty(1.04) xscale = NumericProperty(1.0) yscale = NumericProperty(1.0) def __init__(self, owner=None, **kwargs): super(SpriteEditorViewer, self).__init__(**kwargs) self.image = SpriteEditorImage(allow_stretch=True, nocache=True, size_hint=(None, None)) self.add_widget(self.image) self.owner: 'SpriteEditorWidget' = owner self.grid = SpriteEditorGrid(owner=self.image, size_hint=(None, None)) self.add_widget(self.grid) self._tool: Generic[Tool] = None self.tool = PanZoomTool() self.selection = RegionSelection(viewer=self) self.add_widget(self.selection) Clock.schedule_interval(partial(self.update_info_callback), 0.05) @property def tool(self): return self._tool @tool.setter def tool(self, value): if self._tool is not None: self._tool.end(self) self._tool = value self._tool.begin(self) def image_size_to_window(self, width, height): return width * self.xscale, height * self.yscale def image_pos_to_window(self, pos): local_pos = list(pos) local_pos[0] *= self.xscale local_pos[1] *= self.yscale local_pos[1] = self.image.height - local_pos[1] win_pos = self.image.to_window(local_pos[0], local_pos[1], initial=False, relative=True) return list(win_pos) def window_pos_to_image(self, pos): local_pos = list(self.image.to_local(pos[0], pos[1], relative=True)) local_pos[1] = self.image.size[1] - local_pos[1] local_pos[0] /= self.xscale local_pos[1] /= self.yscale if local_pos[0] < 0: local_pos[0] = 0 if local_pos[1] < 0: local_pos[1] = 0 if local_pos[0] >= self.image.texture.size[0]: local_pos[0] = self.image.texture.size[0] - 1 if local_pos[1] >= self.image.texture.size[1]: local_pos[1] = self.image.texture.size[1] - 1 local_pos[0] = int(local_pos[0]) + 1 local_pos[1] = int(local_pos[1]) + 1 return local_pos def get_mouse_image_pos(self): pos = Window.mouse_pos local_pos = self.window_pos_to_image(pos) return local_pos def update_info_callback(self, dt): if self.image.texture is None: return local_pos = self.get_mouse_image_pos() self.owner.x_label.set_value(local_pos[0]) self.owner.y_label.set_value(local_pos[1]) def toggle_grid(self, value=None): if value is None: self.grid.visible = not self.grid.visible else: self.grid.visible = value pass def set_scale(self, value, local_pos): self.image.size = (self.image.size[0] * value, self.image.size[1] * value) self.image.x -= local_pos[0] * (value - 1.0) self.image.y -= local_pos[1] * (value - 1.0) self.xscale = self.image.size[0] / self.image.texture.size[0] self.yscale = self.image.size[1] / self.image.texture.size[1] def set_texture(self, texture): self.image.texture = texture self.reset_zoom() def reset_zoom(self): self.image.size = self.image.texture.size self.image.pos = (0.0, 0.0) def on_touch_down(self, touch): if not self.collide_point(*touch.pos): return super(SpriteEditorViewer, self).on_touch_down(touch) self._tool.down(self, touch) return super(SpriteEditorViewer, self).on_touch_down(touch) def on_touch_move(self, touch): if not self.collide_point(*touch.pos): return super(SpriteEditorViewer, self).on_touch_move(touch) self._tool.move(self, touch) return super(SpriteEditorViewer, self).on_touch_move(touch) def on_touch_up(self, touch): if not self.collide_point(*touch.pos): return super(SpriteEditorViewer, self).on_touch_up(touch) self._tool.up(self, touch) return super(SpriteEditorViewer, self).on_touch_up(touch) class SpriteEditorGrid(Widget): visible = BooleanProperty(False) def __init__(self, owner: 'SpriteEditorImage' = None, **kwargs): super(SpriteEditorGrid, self).__init__(**kwargs) self.owner = owner self.owner.bind(size=self.redraw, pos=self.redraw) self.bind(visible=self.redraw) def update(self, *args): self.pos = self.owner.pos self.size = self.owner.size self.redraw() def redraw(self, *args): # self.update() self.canvas.clear() if not self.visible: return self.pos = self.owner.pos self.size = self.owner.size width = self.owner.texture.size[0] height = self.owner.texture.size[1] h_stride = self.width / width v_stride = self.height / height grid = InstructionGroup() grid.add(Color(1, 1, 1)) for y in range(0, height): grid.add(Line(points=[self.x + 0, self.y + y * v_stride, self.x + self.width, self.y + y * v_stride])) for x in range(0, width): grid.add(Line(points=[self.x + x * h_stride, self.y + 0, self.x + x * h_stride, self.y + self.height])) self.canvas.add(grid) class SpriteEditorImage(Image): def __init__(self, **kwargs): super(SpriteEditorImage, self).__init__(**kwargs) self.bind(texture=self.update_texture_filters) def update_texture_filters(self, *args): self.texture.min_filter = 'nearest' self.texture.mag_filter = 'nearest' Overlaying the effects and dynamically updating implemented import io import time import os from pathlib import Path from typing import Generic, Callable, List, Optional import numpy as np import sys from PIL import Image as PILImage, ImageChops from PIL import ImageDraw from kivy.app import App from kivy.core.clipboard import Clipboard from kivy.core.image import Image as CoreImage from kivy.core.window import Window from kivy.graphics.context_instructions import Color from kivy.graphics.instructions import InstructionGroup from kivy.graphics.vertex_instructions import Line, Rectangle from kivy.properties import ObjectProperty, NumericProperty, BooleanProperty, Clock, partial, StringProperty from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image from kivy.uix.label import Label from kivy.uix.stacklayout import StackLayout from kivy.uix.stencilview import StencilView from kivy.uix.widget import Widget class SpriteEditorApp(App): def __init__(self): super(SpriteEditorApp, self).__init__() self.canvas: 'SpriteEditorWidget' = None def build(self): self.canvas = SpriteEditorWidget() self.title = "Sprite Extractor" return self.canvas class SpriteEditorInfoLabel(Label): name = StringProperty() val_format = StringProperty() def __init__(self, **kwargs): super(SpriteEditorInfoLabel, self).__init__(**kwargs) def set_value(self, value): formatted = self.val_format % value self.text = f"{self.name}: {formatted}" class SpriteEditorWidget(Widget): image: PILImage = ObjectProperty(None) core_image: CoreImage = ObjectProperty(None) image_path: str = StringProperty(None) def _create_info_label(self, name, val_format="%i"): label = SpriteEditorInfoLabel(halign="left", text_size=(200, 32), size=(200, 20), size_hint=(1, None), padding=[8, 8]) label.name = name label.val_format = val_format self.info_stack.add_widget(label) return label def _create_tool_button(self, name, pressed: Callable): result = Button(text=name, size=(200, 50), size_hint=(1, None)) result.bind(on_press=pressed) self.tool_stack.add_widget(result) return result def _toggle_press(self, button, *args): button.sp_toggle = not button.sp_toggle if button.sp_toggle: button.background_color = [0, 1, 0, 1] button.sp_event(button, True) else: button.background_color = [1, 1, 1, 1] button.sp_event(button, False) def _create_toggle_button(self, name, pressed: Callable): result = Button(text=name, size=(200, 50), size_hint=(1, None)) result.sp_toggle = False result.sp_event = pressed result.bind(on_press=self._toggle_press) self.tool_stack.add_widget(result) return result def _on_overlay_update(self, *args): if self.overlay_updater is not None: self.overlay_updater() def __init__(self, **kwargs): super(SpriteEditorWidget, self).__init__(**kwargs) # self.images = dict() self.root = BoxLayout(orientation='horizontal') # self.root = FloatLayout(size=(Window.width, Window.height)) # self.grid = GridLayout(cols=8) self.add_widget(self.root) self.viewer = SpriteEditorViewer(owner=self, size_hint=(.7, 1)) self.viewer.padding = [4, 4] self.root.add_widget(self.viewer) self.toolbox = BoxLayout(orientation='vertical', size=(200, 50), size_hint=(None, 1)) self.root.add_widget(self.toolbox) tool_stack = StackLayout(size=(200, 50), size_hint=(None, 0.7)) tool_stack.orientation = "tb-lr" tool_stack.padding = [4, 4] self.toolbox.add_widget(tool_stack) self.tool_stack = tool_stack # self._create_tool_button('Load Image', self.load_image_press) self._create_tool_button('Toggle Grid', self.toggle_grid_press) self.select_button = self._create_tool_button('Select Region', self.select_press) self._create_tool_button('Copy Region to Clipboard', self.copy_region_press) self._create_tool_button('Create Sprite', self.create_sprite_press) self._create_tool_button('Find Unique Colors', self.find_unique_press) self._create_tool_button('Highlight Unique Colors', self.highlight_unique_press) self._create_toggle_button('Overlay Unique Colors', self.overlay_unique_press) self._create_tool_button('Extract Transparent Sprite', self.extract_transparent_press) self._create_toggle_button('Overlay Transparent Sprite', self.overlay_transparent_press) self.overlay_updater: Optional[Callable] = None info_stack = StackLayout(size=(200, 50), size_hint=(None, 0.3)) info_stack.orientation = "tb-lr" info_stack.padding = [4, 4] self.info_stack = info_stack self.x_label = self._create_info_label("x") self.y_label = self._create_info_label("y") self.sel_x_label = self._create_info_label("sel x") self.sel_y_label = self._create_info_label("sel y") self.sel_width_label = self._create_info_label("sel width") self.sel_height_label = self._create_info_label("sel height") self.toolbox.add_widget(info_stack) self.viewer.selection.bind(on_update=self._on_overlay_update) Window.bind(on_resize=self.on_window_resize) Window.clearcolor = (0.136, 0.191, 0.25, 1) Window.bind(on_dropfile=self._on_drop_file) self.root.size = (Window.width, Window.height) if len(sys.argv) > 1: self.load_image(sys.argv[1]) def _on_drop_file(self, window, file_path): print(file_path) self.load_image(file_path) def copy_region_press(self, *args): region = self.viewer.selection Clipboard.copy(f"\"REGION\": ({region.sel_y}, {region.sel_x}," + f" {region.sel_y + region.sel_height}, {region.sel_x + region.sel_width})") @staticmethod def date_for_filename(): return time.strftime("%Y%m%d%H%M%S", time.localtime()) def overlay_update_transparent_extractor(self): extracted = self.extract_transparent() self.viewer.selection.overlay = self.pil_to_core(extracted) def overlay_update_highlight_unique(self): extracted = self.highlight_unique() self.viewer.selection.overlay = self.pil_to_core(extracted) def overlay_transparent_press(self, button, enabled, *args): if enabled: self.overlay_updater = self.overlay_update_transparent_extractor self.overlay_update_transparent_extractor() else: self.overlay_updater = None self.viewer.selection.overlay = None def overlay_unique_press(self, button, enabled, *args): if enabled: self.overlay_updater = self.overlay_update_highlight_unique self.overlay_update_highlight_unique() else: self.overlay_updater = None self.viewer.selection.overlay = None def extract_transparent(self): point_table = ([0] + ([255] * 255)) def diff_image(a, b): diff = ImageChops.difference(a, b) diff = diff.convert('L') diff = diff.point(point_table) diff = ImageChops.invert(diff) new = diff.convert('RGB') new.paste(b, mask=diff) return new p = Path(self.image_path) p = p.parents[0] sections = [] for root, dirs, files in os.walk(p): for file in files: if not file.endswith(".png"): continue image = PILImage.open(file) section = self.get_selection_image(image) sections.append(section.convert('RGB')) result = sections.pop() for section in sections: result = diff_image(result, section) return result def extract_transparent_press(self, *args): self.save_image("../extracted", self.extract_transparent()) def highlight_unique(self): sprite = np.array(self.get_selection_image()).tolist() unique = self.find_unique_colors() result = [] for rows in sprite: row = [] for pixel in rows: if pixel in unique: row.append(pixel) else: row.append([0, 0, 0]) result.append(row) result = np.array(result) result_image = PILImage.fromarray(result.astype('uint8'), "RGB") return result_image def highlight_unique_press(self, *args): self.save_image("highlight", self.highlight_unique()) def get_selection_region(self): region = self.viewer.selection selection = (region.sel_x - 1, region.sel_y - 1, region.sel_x + region.sel_width - 1, region.sel_y + region.sel_height - 1) return selection def get_selection_image(self, custom_image=None) -> PILImage: if custom_image is None: image: PILImage = self.image else: image = custom_image selection = self.get_selection_region() sprite = image.crop(selection) return sprite def find_unique_colors(self) -> List[List[int]]: selection = self.get_selection_region() sprite = self.get_selection_image() image: PILImage = self.image.copy() draw = ImageDraw.Draw(image) draw.rectangle(selection, fill=0) del draw rest_pixels = np.array(image) sprite_pixels = np.array(sprite) rest_colors = np.unique(rest_pixels.reshape(-1, 3), axis=0).tolist() rest_colors = [item for item in rest_colors if item is not [0, 0, 0]] sprite_colors = np.unique(sprite_pixels.reshape(-1, 3), axis=0).tolist() unique_colors = [item for item in sprite_colors if item not in rest_colors] if len(unique_colors) == 0: print("No unique colors found") return [] unique_colors.sort(reverse=True) return unique_colors def save_image(self, name, image): p = Path(self.image_path) p = p.parents[0] / f"{name}_{self.date_for_filename()}.png" print(p) image.save(p) print("File written to:", p) def find_unique_press(self, *args): unique_colors = self.find_unique_colors() if len(unique_colors) == 0: return unique_colors = np.array([unique_colors]) print(unique_colors) print(unique_colors.shape) unique_color_image = PILImage.fromarray(unique_colors.astype('uint8'), "RGB") self.save_image("unique", unique_color_image) def create_sprite_press(self, *args): sprite = self.get_selection_image() self.save_image("sprite", sprite) def toggle_grid_press(self, *args): self.viewer.toggle_grid() def on_image_path(self, *args): self.image = PILImage.open(self.image_path) # CoreImage(path, keep_data=True) def load_image(self, path): self.image_path = path def pil_to_core(self, pil): image = pil.convert("RGB") image_file = io.BytesIO() image.save(image_file, "png") image_file.seek(0) return CoreImage(image_file, ext="png") def on_image(self, sender, image: PILImage): print("Image set") self.core_image = self.pil_to_core(image) self.viewer.set_texture(self.core_image.texture) def select_press(self, *args): self.viewer.tool = RegionTool() def on_window_resize(self, window, width, height): self.root.size = (width, height) class Tool: def begin(self, editor: 'SpriteEditorViewer'): pass def end(self, editor: 'SpriteEditorViewer'): pass def down(self, editor: 'SpriteEditorViewer', touch): pass def up(self, editor: 'SpriteEditorViewer', touch): pass def move(self, editor: 'SpriteEditorViewer', touch): pass class ZoomTool(Tool): def down(self, editor: 'SpriteEditorViewer', touch): local_pos = editor.image.to_local(touch.x, touch.y, relative=True) if touch.button == "scrolldown": editor.set_scale(editor.zoom_ratio, local_pos) return True elif touch.button == "scrollup": editor.set_scale(1.0 / editor.zoom_ratio, local_pos) return True class PanZoomTool(ZoomTool): def move(self, editor: 'SpriteEditorViewer', touch): editor.image.x += touch.dx editor.image.y += touch.dy super().move(editor, touch) class RegionTool(Tool): def begin(self, editor: 'SpriteEditorViewer'): editor.selection.visible = False editor.selection.sel_x = 0 editor.selection.sel_y = 0 editor.selection.sel_width = 0 editor.selection.sel_height = 0 editor.owner.select_button.background_color = [0, 1, 0, 1] def end(self, editor: 'SpriteEditorViewer'): editor.owner.select_button.background_color = [1, 1, 1, 1] def down(self, editor: 'SpriteEditorViewer', touch): local_pos = editor.window_pos_to_image((touch.x, touch.y)) editor.selection.sel_x = local_pos[0] editor.selection.sel_y = local_pos[1] editor.selection.visible = True def move(self, editor: 'SpriteEditorViewer', touch): local_pos = editor.window_pos_to_image((touch.x, touch.y)) editor.selection.sel_width = (local_pos[0] - editor.selection.sel_x) + 1 editor.selection.sel_height = (local_pos[1] - editor.selection.sel_y) + 1 def up(self, editor: 'SpriteEditorViewer', touch): local_pos = editor.window_pos_to_image((touch.x, touch.y)) editor.selection.sel_width = (local_pos[0] - editor.selection.sel_x) + 1 editor.selection.sel_height = (local_pos[1] - editor.selection.sel_y) + 1 editor.tool = PanZoomTool() class RegionSelection(FloatLayout): sel_x = NumericProperty(0.0) sel_y = NumericProperty(0.0) sel_width = NumericProperty(0.0) sel_height = NumericProperty(0.0) visible = BooleanProperty(False) rect = ObjectProperty(None) @property def overlay(self): return self._overlay @overlay.setter def overlay(self, overlay): self._overlay = overlay if self._overlay is None: self.overlay_image.texture = None self.overlay_image.opacity = 0.0 else: self.overlay_image.texture = self.overlay.texture self.overlay_image.opacity = 1.0 def __init__(self, viewer: 'SpriteEditorViewer' = None, **kwargs): super(RegionSelection, self).__init__(**kwargs) self.viewer = viewer self.bind(sel_x=self.update, sel_y=self.update, sel_width=self.update, sel_height=self.update) self.bind(sel_x=self.update_overlay, sel_y=self.update_overlay, sel_width=self.update_overlay, sel_height=self.update_overlay) self.viewer.image.bind(size=self.update, pos=self.update) self.viewer.bind(xscale=self.update, yscale=self.update) self.bind(visible=self.redraw) self.overlay_image = SpriteEditorImage(allow_stretch=True, nocache=True, size_hint=(None, None)) self.add_widget(self.overlay_image) self.overlay_image.opacity = 0.0 self._overlay: Optional[CoreImage] = None self.register_event_type('on_update') self._keyboard = Window.request_keyboard( self._keyboard_closed, self, 'text') if self._keyboard.widget: pass self._keyboard.bind(on_key_down=self._on_keyboard_down) def _keyboard_closed(self): print('My keyboard have been closed!') self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): amount = 1 if "shift" in modifiers: amount = 5 if "alt" in modifiers: if keycode[1] == "up": self.sel_height += amount self.sel_y -= amount return True elif keycode[1] == "down": self.sel_height -= amount self.sel_y += amount return True elif keycode[1] == "left": self.sel_width += amount self.sel_x -= amount return True elif keycode[1] == "right": self.sel_width -= amount self.sel_x += amount return True elif "ctrl" in modifiers: if keycode[1] == "up": self.sel_height -= amount return True elif keycode[1] == "down": self.sel_height += amount return True elif keycode[1] == "left": self.sel_width -= amount return True elif keycode[1] == "right": self.sel_width += amount return True else: if keycode[1] == "up": self.sel_y -= amount return True elif keycode[1] == "down": self.sel_y += amount return True elif keycode[1] == "left": self.sel_x -= amount return True elif keycode[1] == "right": self.sel_x += amount return True return False def on_update(self, *args): pass def update_overlay(self, *args): if self.sel_width > 0 and self.sel_height > 0: self.dispatch("on_update") else: self.overlay = None def update(self, *args): if self.rect is None: self.redraw() return self.rect.pos = self.viewer.image_pos_to_window((self.sel_x - 1, self.sel_y + self.sel_height - 1)) self.rect.size = self.viewer.image_size_to_window(self.sel_width, self.sel_height) self.overlay_image.pos = self.rect.pos self.overlay_image.size = self.rect.size self.viewer.owner.sel_x_label.set_value(self.sel_x) self.viewer.owner.sel_y_label.set_value(self.sel_y) self.viewer.owner.sel_width_label.set_value(self.sel_width) self.viewer.owner.sel_height_label.set_value(self.sel_height) def redraw(self, *args): # self.canvas.clear() if not self.visible: self.opacity = 0.0 return else: self.opacity = 1.0 with self.canvas: Color(0.5, 1, 0.5, 0.3) self.rect = Rectangle() self.update() class SpriteEditorViewer(FloatLayout, StencilView): image = ObjectProperty(None) selection = ObjectProperty(None) zoom_ratio = NumericProperty(1.04) xscale = NumericProperty(1.0) yscale = NumericProperty(1.0) def __init__(self, owner=None, **kwargs): super(SpriteEditorViewer, self).__init__(**kwargs) self.image = SpriteEditorImage(allow_stretch=True, nocache=True, size_hint=(None, None)) self.add_widget(self.image) self.owner: 'SpriteEditorWidget' = owner self.grid = SpriteEditorGrid(owner=self.image, size_hint=(None, None)) self.add_widget(self.grid) self._tool: Generic[Tool] = None self.tool = PanZoomTool() self.selection = RegionSelection(viewer=self) self.add_widget(self.selection) Clock.schedule_interval(partial(self.update_info_callback), 0.05) @property def tool(self): return self._tool @tool.setter def tool(self, value): if self._tool is not None: self._tool.end(self) self._tool = value self._tool.begin(self) def image_size_to_window(self, width, height): return width * self.xscale, height * self.yscale def image_pos_to_window(self, pos): local_pos = list(pos) local_pos[0] *= self.xscale local_pos[1] *= self.yscale local_pos[1] = self.image.height - local_pos[1] win_pos = self.image.to_window(local_pos[0], local_pos[1], initial=False, relative=True) return list(win_pos) def window_pos_to_image(self, pos): local_pos = list(self.image.to_local(pos[0], pos[1], relative=True)) local_pos[1] = self.image.size[1] - local_pos[1] local_pos[0] /= self.xscale local_pos[1] /= self.yscale if local_pos[0] < 0: local_pos[0] = 0 if local_pos[1] < 0: local_pos[1] = 0 if local_pos[0] >= self.image.texture.size[0]: local_pos[0] = self.image.texture.size[0] - 1 if local_pos[1] >= self.image.texture.size[1]: local_pos[1] = self.image.texture.size[1] - 1 local_pos[0] = int(local_pos[0]) + 1 local_pos[1] = int(local_pos[1]) + 1 return local_pos def get_mouse_image_pos(self): pos = Window.mouse_pos local_pos = self.window_pos_to_image(pos) return local_pos def update_info_callback(self, dt): if self.image.texture is None: return local_pos = self.get_mouse_image_pos() self.owner.x_label.set_value(local_pos[0]) self.owner.y_label.set_value(local_pos[1]) def toggle_grid(self, value=None): if value is None: self.grid.visible = not self.grid.visible else: self.grid.visible = value pass def set_scale(self, value, local_pos): self.image.size = (self.image.size[0] * value, self.image.size[1] * value) self.image.x -= local_pos[0] * (value - 1.0) self.image.y -= local_pos[1] * (value - 1.0) self.xscale = self.image.size[0] / self.image.texture.size[0] self.yscale = self.image.size[1] / self.image.texture.size[1] def set_texture(self, texture): self.image.texture = texture self.reset_zoom() def reset_zoom(self): self.image.size = self.image.texture.size self.image.pos = (0.0, 0.0) def on_touch_down(self, touch): if not self.collide_point(*touch.pos): return super(SpriteEditorViewer, self).on_touch_down(touch) self._tool.down(self, touch) return super(SpriteEditorViewer, self).on_touch_down(touch) def on_touch_move(self, touch): if not self.collide_point(*touch.pos): return super(SpriteEditorViewer, self).on_touch_move(touch) self._tool.move(self, touch) return super(SpriteEditorViewer, self).on_touch_move(touch) def on_touch_up(self, touch): if not self.collide_point(*touch.pos): return super(SpriteEditorViewer, self).on_touch_up(touch) self._tool.up(self, touch) return super(SpriteEditorViewer, self).on_touch_up(touch) class SpriteEditorGrid(Widget): visible = BooleanProperty(False) def __init__(self, owner: 'SpriteEditorImage' = None, **kwargs): super(SpriteEditorGrid, self).__init__(**kwargs) self.owner = owner self.owner.bind(size=self.redraw, pos=self.redraw) self.bind(visible=self.redraw) def update(self, *args): self.pos = self.owner.pos self.size = self.owner.size self.redraw() def redraw(self, *args): # self.update() self.canvas.clear() if not self.visible: return self.pos = self.owner.pos self.size = self.owner.size width = self.owner.texture.size[0] height = self.owner.texture.size[1] h_stride = self.width / width v_stride = self.height / height grid = InstructionGroup() grid.add(Color(1, 1, 1)) for y in range(0, height): grid.add(Line(points=[self.x + 0, self.y + y * v_stride, self.x + self.width, self.y + y * v_stride])) for x in range(0, width): grid.add(Line(points=[self.x + x * h_stride, self.y + 0, self.x + x * h_stride, self.y + self.height])) self.canvas.add(grid) class SpriteEditorImage(Image): def __init__(self, **kwargs): super(SpriteEditorImage, self).__init__(**kwargs) self.bind(texture=self.update_texture_filters) def update_texture_filters(self, *args): if self.texture == None: return self.texture.min_filter = 'nearest' self.texture.mag_filter = 'nearest'
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2016 F5 Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: bigip_iapp_template short_description: Manages TCL iApps on a BIG-IP description: - Manages TCL iApps on a BIG-IP version_added: "2.3" options: name: description: - The name of the template being uploaded. If this is not provided, the module will attempt to retrieve the name from the template file itself. required: False content: description: - When used instead of 'src', sets the contents of an iApp template directly to the specified value. This is for simple values, but can be used with lookup plugins for anything complex or with formatting. Either one of C(src) or C(content) must be provided. src: description: - The iApp template to interpret and upload to the BIG-IP. Either one of C(src) or C(content) must be provided. required: true state: description: - Whether the iRule should exist or not. required: false default: present choices: - present - absent notes: - Requires the f5-sdk Python package on the host. This is as easy as pip install f5-sdk. - Requires the pyparsing Python package on the host. This is as easy as pip install pyparsing. - This module cannot yet manage 'cli script' sections that are found in some iApp templates extends_documentation_fragment: f5 author: - Tim Rupp (@caphrim007) ''' EXAMPLES = ''' - name: Add the iApp contained in template iapp.tmpl bigip_iapp_template: content: "{{ lookup('template', 'iapp.tmpl') }}" name: "my-iapp" password: "secret" server: "lb.mydomain.com" state: "present" user: "admin" delegate_to: localhost ''' RETURN = ''' ''' try: from f5.bigip.contexts import TransactionContextManager from f5.bigip import ManagementRoot from icontrol.session import iControlUnexpectedHTTPError HAS_F5SDK = True except ImportError: HAS_F5SDK = False try: from pyparsing import Optional, nestedExpr, Word, originalTextFor, \ CaselessLiteral, alphanums, OneOrMore, Forward, Suppress, alphas, \ nums HAS_PYPARSING = True except: HAS_PYPARSING = False class iAppGrammar: """Grammar parser for a subset of iApp V1 This class is a parser for a subset of allowed iApp template code. This subset is represented by the code below. cli script <SCRIPT-NAME> { } cli admin-partitions { update-partition <PARTITION> } sys application template <TEMPLATE> { actions { definition { html-help { } implementation { } presentation { } } } description none ignore-verification false requires-bigip-version-max none requires-bigip-version-min none signing-key none tmpl-signature none requires-modules { ltm gtm } } While other code is technically allowed in an iApp, this parser will not find it. """ def __init__(self): self.test = None self.parsed_results = None self.sections = ['implementation', 'presentation', 'html_help', 'scripts'] self.properties = ['partition', 'description', 'verification', 'version_max', 'version_min', 'signing_key', 'signature', 'required_modules'] def parse_string(self, test): self.test = test return self.parse_results() def parse_results(self): result = dict() for section in self.sections: result[section] = self.__parse_raw_text(section) for property in self.properties: result[property] = self.__parse_property(property) return result def generate_parser(self): """ This BNF is incomplete and is only my own interpretation of syntax based off of people I've talked to. It was not taken from internal sources, and can probably be improved as its performance is not fantastic. <labr> ::= "{" <rabr> ::= "}" <cli> ::= "cli" <script> ::= "script" <admin-partitions> ::= "admin-partitions" <uppercase> ::= 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' <lowercase> ::= 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' <nums> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 <alphas> ::= <uppercase> <lowercase> <alphanums> ::= <alphas> <nums> <iapp> ::= <cli-part> | <application-template-part> <cli-part> ::= <cli-script> | <cli-admin-partitions> <cli-script> ::= <cli> <script> <cli-admin-partitions> ::= <cli> <admin-partitions> <labr> <admin-partition-components> <rabr> <admin-partition-components> ::= <update-partition> <text1> <update-partition> ::= 'update-partition' <alphas> <name> ::= <alphas> | <name> <application-template-part> ::= 'sys' 'application' 'template' """ # General definitions and declarations toplevel = Forward() CL = CaselessLiteral lbra, rbra = map(Suppress, "{}") # Reserved Literals cli_ = CL('cli') admin_partition_ = CL('admin-partitions') update_partition_ = CL('update-partition') sys_ = CL('sys') script_ = CL('script') application_ = CL('application') template_ = CL('template') actions_ = CL('actions').suppress() definition_ = CL('definition').suppress() description_ = CL('description') htmlhelp_ = CL("html-help") implementation_ = CL("implementation") presentation_ = CL("presentation") verify_ = CL('ignore-verification') version_max = CL('requires-bigip-version-max') version_min = CL('requires-bigip-version-min') key_ = CL('signing-key') signature_ = CL('tmpl-signature') modules_ = CL('requires-modules') # Reserved words whose values we suppress from parsed results raw_text = originalTextFor(nestedExpr('{', '}')) # Raw text tokens script_text = raw_text.setResultsName('scripts') help_text = raw_text.setResultsName('html_help') implementation_text = raw_text.setResultsName('implementation') presentation_text_ = raw_text.setResultsName('presentation') # Sections actions = (Optional(htmlhelp_ + help_text) & Optional(implementation_ + implementation_text) & Optional(presentation_ + presentation_text_ ) ) # Parameter values bools = (Word('true') | Word('false')) word_nums = (Word(nums + '.') | 'none') name = Word(alphanums + '._-/') # Named values used when referencing results description_val = name.setResultsName('description') verify_val = bools.setResultsName('verification') version_max_val = word_nums.setResultsName('version_max') version_min_val = word_nums.setResultsName('version_min') key_val = word_nums.setResultsName('signing_key') signature_val = word_nums.setResultsName('signature') modules_val = OneOrMore(Word(alphas)).setResultsName('required_modules') partition_val = Word(alphanums + '._-').setResultsName('partition') # Properties that can be set on the iApp property_description = Optional(description_ + description_val) property_verify = Optional(verify_ & verify_val) property_version_max = Optional(version_max & version_max_val) property_version_min = Optional(version_min & version_min_val) property_key = Optional(key_ & key_val) property_signature = Optional(signature_ & signature_val) property_modules = Optional(modules_ + lbra + modules_val + rbra) properties = property_description & \ property_verify & \ property_version_max & \ property_version_min & \ property_key & \ property_signature & \ property_modules # Top-level sections that are commonly found in iApps partition = cli_ + admin_partition_ + lbra + \ update_partition_ + partition_val + rbra cli_scripts = cli_ + script_ + name + script_text application_template = sys_ + application_ + template_ + \ name + lbra + actions_ + lbra + \ definition_ + lbra + actions + rbra + \ rbra & properties template = Optional(partition) & \ Optional(cli_scripts) & \ Optional(application_template) toplevel << template return toplevel def __parse_property(self, section): """Returns a simple value :return: """ result=None toplevel = self.generate_parser() parsed = toplevel.parseString(self.test) if not hasattr(parsed, section): return result if section == 'required_modules': return list(parsed.required_modules) return getattr(parsed, section) def __parse_raw_text(self, section): """Returns a block of raw text Some of the sections in an iApp include raw tmsh commands. These need to be sent to the REST API endpoints as their raw contents so that the BIG-IP will register them correctly. :return: """ result=None toplevel = self.generate_parser() parsed = toplevel.parseString(self.test) if hasattr(parsed, section): # This slice will remove leading and trailing braces result = getattr(parsed, section)[1:-1] return result class BigIpiAppTemplateManager(object): def __init__(self, *args, **kwargs): self.changed_params = dict() self.params = kwargs self.api = None def apply_changes(self): result = dict() changed = False try: self.api = self.connect_to_bigip(**self.params) if self.params['state'] == "present": changed = self.present() elif self.params['state'] == "absent": changed = self.absent() except iControlUnexpectedHTTPError as e: raise F5ModuleError(str(e)) result.update(**self.changed_params) result.update(dict(changed=changed)) return result def present(self): if self.iapp_template_exists(): return self.update_iapp_template() else: if self.present_parameters_are_valid(self.params): return self.ensure_iapp_template_is_present() else: raise F5ModuleError( "Either 'content' or 'src' must be provided" ) def present_parameters_are_valid(self, params): if not params['content'] and not params['src']: return False else: return True def absent(self): changed = False if self.iapp_template_exists(): changed = self.ensure_iapp_template_is_absent() return changed def connect_to_bigip(self, **kwargs): return ManagementRoot(kwargs['server'], kwargs['user'], kwargs['password'], port=kwargs['server_port']) def read_iapp_template_information(self): iapp = self.load_iapp_template() return self.format_iapp_information(iapp) def format_iapp_information(self, iapp): result = dict() result['name'] = str(user.name) if hasattr(user, 'description'): result['full_name'] = str(user.description) return result def load_iapp_template(self): result = dict() result.update(self.load_iapp_application()) result.update(self.load_iapp_actions()) return result def load_iapp_application(self): params = dict( params='expandSubcollections=true' ) return self.api.tm.sys.application.templates.template.load( name=self.params['name'], partition=self.params['partition'], requests_params=params ) def iapp_template_exists(self): return self.api.tm.sys.application.templates.template.exists( name=self.params['name'], partition=self.params['partition'] ) def update_iapp_template(self): params = self.get_changed_parameters() if params: self.changed_params = camel_dict_to_snake_dict(params) if self.params['check_mode']: return True else: return False params['name'] = self.params['name'] params['partition'] = self.params['partition'] self.update_iapp_template_on_device(params) return True def update_iapp_template_on_device(self, params): tx = self.api.tm.transactions.transaction with TransactionContextManager(tx) as api: r = api.tm.sys.application.templates.template.load( name=self.params['name'], partition=self.params['partition'] ) r.actions.modify(**params) def get_changed_parameters(self): result = dict() current = self.read_iapp_template_information() if self.is_implementation_changed(current): result['implementation'] = self.params['implementation'] if self.is_presentation_changed(current): result['presentation'] = self.params['presentation'] if self.is_html_help_changed(current): result['htmlHelp'] = self.params['implementation'] if self.are_macros_changed(current): result['macro'] = self.params['macros'] if self.is_minimum_version_changed(current): result['requiresBigipVersionMin'] = self.params['version_min'] if self.is_maximim_version_changed(current): result['requiresBigipVersionMax'] = self.params['version_max'] if self.are_required_modules_changed(current): result['requiresModules'] = self.params['required_modules'] return result def is_implementation_changed(self, current): if self.params['implementation'] is None: return False if 'implementation' not in current: return True if self.params['implementation'] == current['implementation']: return False else: return True def is_presentation_changed(self, current): pass def is_html_help_changed(self, current): pass def are_macros_changed(self, current): pass def is_minimum_version_changed(self, current): pass def is_maximim_version_changed(self, current): pass def are_required_modules_changed(self, current): pass def ensure_iapp_template_is_present(self): params = self.get_iapp_template_creation_parameters() self.changed_params = camel_dict_to_snake_dict(params) if self.params['check_mode']: return True self.create_iapp_template_on_device(params) if self.iapp_template_exists(): return True else: raise F5ModuleError("Failed to create the iApp template") def get_iapp_template_creation_parameters(self): result = dict( name=self.params['name'], partition=self.params['partition'] ) if self.params['src']: with open(self.params['src']) as f: result['template'] = f.read() elif self.params['content']: result['template'] = self.params['content'] return result def create_iapp_template_on_device(self, params): tx = self.api.tm.transactions.transaction with TransactionContextManager(tx) as api: api.tm.sys.application.templates.template.create(**params) def ensure_iapp_template_is_absent(self): if self.params['check_mode']: return True self.delete_iapp_template_from_device() if self.iapp_template_exists(): raise F5ModuleError("Failed to delete the iApp template") return True def delete_iapp_template_from_device(self): tx = self.api.tm.transactions.transaction with TransactionContextManager(tx) as api: tpl = api.tm.sys.application.templates.template.load( name=self.params['name'], partition=self.params['partition'] ) tpl.delete() class BigIpiAppTemplateModuleConfig(object): def __init__(self): self.argument_spec = dict() self.meta_args = dict() self.supports_check_mode = True self.states = ['present', 'absent'] self.initialize_meta_args() self.initialize_argument_spec() def initialize_meta_args(self): args = dict( state=dict( type='str', default='present', choices=self.states ), name=dict( type='str', required=False ), content=dict(required=False, default=None), src=dict(required=False, default=None), ) self.meta_args = args def initialize_argument_spec(self): self.argument_spec = f5_argument_spec() self.argument_spec.update(self.meta_args) def create(self): return AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=self.supports_check_mode, mutually_exclusive=[ ['content', 'src'] ] ) def main(): if not HAS_F5SDK: raise F5ModuleError("The python f5-sdk module is required") if not HAS_PYPARSING: raise F5ModuleError("The python pyparsing module is required") config = BigIpiAppTemplateModuleConfig() module = config.create() try: obj = BigIpiAppTemplateManager( check_mode=module.check_mode, **module.params ) result = obj.apply_changes() module.exit_json(**result) except F5ModuleError as e: module.fail_json(msg=str(e)) from ansible.module_utils.basic import * from ansible.module_utils.ec2 import camel_dict_to_snake_dict from ansible.module_utils.f5 import * if __name__ == '__main__': main() finished with first go-around of the iapp_template module #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2016 F5 Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: bigip_iapp_template short_description: Manages TCL iApps on a BIG-IP description: - Manages TCL iApps on a BIG-IP version_added: "2.3" options: force: description: - Specifies whether or not to force the uploading of an iApp. This module does not handle the case of updating iApps in place. When forcing an update, this module will attempt to remove the existing module before uploading the new one. Existing modules cannot be removed, even with C(force), if a service has been instantiated from that template. required: False choices: - yes - no name: description: - The name of the iApp template that you want to delete. This option is only available when specifying a C(state) of C(absent) and is provided as a way to delete templates that you may no longer have the source of. content: description: - When used instead of 'src', sets the contents of an iApp template directly to the specified value. This is for simple values, but can be used with lookup plugins for anything complex or with formatting. Either one of C(src) or C(content) must be provided. src: description: - The iApp template to interpret and upload to the BIG-IP. Either one of C(src) or C(content) must be provided. required: true state: description: - Whether the iRule should exist or not. required: false default: present choices: - present - absent notes: - Requires the f5-sdk Python package on the host. This is as easy as pip install f5-sdk. extends_documentation_fragment: f5 author: - Tim Rupp (@caphrim007) ''' EXAMPLES = ''' - name: Add the iApp contained in template iapp.tmpl bigip_iapp_template: content: "{{ lookup('template', 'iapp.tmpl') }}" name: "my-iapp" password: "secret" server: "lb.mydomain.com" state: "present" user: "admin" delegate_to: localhost ''' RETURN = ''' ''' try: from f5.bigip.contexts import TransactionContextManager from f5.bigip import ManagementRoot from f5.utils.iapp_parser import IappParser from icontrol.session import iControlUnexpectedHTTPError HAS_F5SDK = True except ImportError: HAS_F5SDK = False class BigIpiAppTemplateManager(object): def __init__(self, *args, **kwargs): self.changed_params = dict() self.params = kwargs self.api = None def apply_changes(self): result = dict() changed = False try: self.api = self.connect_to_bigip(**self.params) if self.params['state'] == "present": changed = self.present() elif self.params['state'] == "absent": changed = self.absent() except iControlUnexpectedHTTPError as e: raise F5ModuleError(str(e)) result.update(**self.changed_params) result.update(dict(changed=changed)) return result def present(self): source = self.get_iapp_template_source( source=self.params['src'], content=self.params['content'] ) template = self.get_application_template(source) params = self.get_params_from_provided_iapp_template_information( template ) self.params.update(params) if self.iapp_template_exists(): return False else: if BigIpiAppTemplateManager.present_parameters_are_valid(self.params): return self.ensure_iapp_template_is_present() else: raise F5ModuleError( "Either 'content' or 'src' must be provided" ) @staticmethod def present_parameters_are_valid(params): if not params['content'] and not params['src']: return False else: return True def absent(self): changed = False if self.iapp_template_exists(): changed = self.ensure_iapp_template_is_absent() return changed def connect_to_bigip(self, **kwargs): return ManagementRoot(kwargs['server'], kwargs['user'], kwargs['password'], port=kwargs['server_port'], token=True) def get_params_from_provided_iapp_template_information(self, template): actions = template['actions']['definition'] result = dict( partition=self.get_iapp_template_partition(template=template), name=self.get_iapp_template_name(template=template), html_help=actions.get('htmlHelp', None), role_acl=actions.get('roleAcl', None), implementation=actions.get('implementation', None), presentation=actions.get('presentation', None), required_modules=template.get('requiresModules', None), max_version=template.get('requiresBigipVersionMax', None), min_version=template.get('requiresBigipVersionMin', None), verification=template.get('ignoreVerification', None) ) return result def get_iapp_template_partition(self, partition=None, template=None): if partition: return partition else: return template.get('partition', 'Common') def get_iapp_template_name(self, name=None, template=None): if name: return name else: if 'name' not in template: raise F5ModuleError( "An iApp template must include a name" ) return template['name'] def get_iapp_template_verification(self, template): if template.get('ignoreVerification', None) in BOOLEANS: return True else: return False def get_application_template(self, source): parser = IappParser(source) return parser.parse_template() def get_iapp_template_source(self, source=None, content=None): if source: with open(source) as fh: return fh.read() elif content: return content else: return None def load_iapp_template(self): result = dict() result.update(self.load_iapp_application()) result.update(self.load_iapp_actions()) return result def load_iapp_application(self): params = dict( params='expandSubcollections=true' ) return self.api.tm.sys.application.templates.template.load( name=self.params['name'], partition=self.params['partition'], requests_params=params ) def iapp_template_exists(self): return self.api.tm.sys.application.templates.template.exists( name=self.params['name'], partition=self.params['partition'] ) def ensure_iapp_template_is_present(self): params = self.get_iapp_template_creation_parameters() self.changed_params = camel_dict_to_snake_dict(params) if self.params['check_mode']: return True self.create_iapp_template_on_device(params) if self.iapp_template_exists(): return True else: raise F5ModuleError("Failed to create the iApp template") def get_iapp_template_creation_parameters(self): result = dict( name=self.params['name'], partition=self.params['partition'], actions=dict( htmlHelp=self.params['html_help'], roleAcl=self.params['role_acl'], implementation=self.params['implementation'], presentation=self.params['presentation'] ), required_modules=self.params['required_modules'], min_version=self.params['min_version'], max_version=self.params['max_version'], verification=self.params['verification'] ) return result def create_iapp_template_on_device(self, params): check_mode = self.params['check_mode'] if check_mode: return True self.api.tm.sys.application.templates.template.create( name=params['name'], partition=params['partition'], actions=dict( definition=dict(**params['actions']) ), requiresModules=params['required_modules'], ignoreVerification=params['verification'], requiresBigipVersionMax=params['max_version'], requiresBigipVersionMin=params['min_version'] ) if not self.iapp_template_exists(): raise F5ModuleError("Failed to create the iRule") return True def ensure_iapp_template_is_absent(self): if self.params['check_mode']: return True self.delete_iapp_template_from_device() if self.iapp_template_exists(): raise F5ModuleError("Failed to delete the iApp template") return True def delete_iapp_template_from_device(self): tpl = api.tm.sys.application.templates.template.load( name=self.params['name'], partition=self.params['partition'] ) tpl.delete() class BigIpiAppTemplateModuleConfig(object): def __init__(self): self.argument_spec = dict() self.meta_args = dict() self.supports_check_mode = True self.states = ['present', 'absent'] self.initialize_meta_args() self.initialize_argument_spec() def initialize_meta_args(self): args = dict( state=dict( type='str', default='present', choices=self.states ), force=dict( choices=BOOLEANS, required=False ), content=dict(required=False, default=None), src=dict(required=False, default=None), ) self.meta_args = args def initialize_argument_spec(self): self.argument_spec = f5_argument_spec() self.argument_spec.update(self.meta_args) def create(self): return AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=self.supports_check_mode, mutually_exclusive=[ ['content', 'src'] ] ) def main(): if not HAS_F5SDK: raise F5ModuleError("The python f5-sdk module is required") config = BigIpiAppTemplateModuleConfig() module = config.create() try: obj = BigIpiAppTemplateManager( check_mode=module.check_mode, **module.params ) result = obj.apply_changes() module.exit_json(**result) except F5ModuleError as e: module.fail_json(msg=str(e)) from ansible.module_utils.basic import * from ansible.module_utils.ec2 import camel_dict_to_snake_dict from ansible.module_utils.f5 import * if __name__ == '__main__': main()
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # Copyright (c) 2013 Matt Hite <mhite@hotmail.com> # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: bigip_facts short_description: Collect facts from F5 BIG-IP devices description: - Collect facts from F5 BIG-IP devices via iControl SOAP API version_added: 1.6 author: - Matt Hite (@mhite) - Tim Rupp (@caphrim007) notes: - Requires BIG-IP software version >= 11.4 - F5 developed module 'bigsuds' required (see http://devcentral.f5.com) - Best run as a local_action in your playbook - Tested with manager and above account privilege level - C(provision) facts were added in 2.2 - This module is deprecated. Use the C(bigip_device_facts) module instead. requirements: - bigsuds options: session: description: - BIG-IP session support; may be useful to avoid concurrency issues in certain circumstances. default: no type: bool include: description: - Fact category or list of categories to collect required: True choices: - address_class - certificate - client_ssl_profile - device - device_group - interface - key - node - pool - provision - rule - self_ip - software - system_info - traffic_group - trunk - virtual_address - virtual_server - vlan filter: description: - Shell-style glob matching string used to filter fact keys. Not applicable for software, provision, and system_info fact categories. extends_documentation_fragment: f5 ''' EXAMPLES = r''' - name: Collect BIG-IP facts bigip_facts: server: lb.mydomain.com user: admin password: secret include: - interface - vlan delegate_to: localhost ''' import fnmatch import re import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import string_types from ansible.module_utils.six.moves import map, zip try: from library.module_utils.network.f5.legacy import bigip_api, bigsuds_found from library.module_utils.network.f5.common import f5_argument_spec except ImportError: from ansible.module_utils.network.f5.legacy import bigip_api, bigsuds_found from ansible.module_utils.network.f5.common import f5_argument_spec try: from suds import MethodNotFound, WebFault except ImportError: pass # Handle via f5_utils.bigsuds_found class F5(object): """F5 iControl class. F5 BIG-IP iControl API class. Attributes: api: iControl API instance. """ def __init__(self, host, user, password, session=False, validate_certs=True, port=443): self.api = bigip_api(host, user, password, validate_certs, port) if session: self.start_session() def start_session(self): self.api = self.api.with_session_id() def get_api(self): return self.api def set_recursive_query_state(self, state): self.api.System.Session.set_recursive_query_state(state) def get_recursive_query_state(self): return self.api.System.Session.get_recursive_query_state() def enable_recursive_query_state(self): self.set_recursive_query_state('STATE_ENABLED') def disable_recursive_query_state(self): self.set_recursive_query_state('STATE_DISABLED') def set_active_folder(self, folder): self.api.System.Session.set_active_folder(folder=folder) def get_active_folder(self): return self.api.System.Session.get_active_folder() class Interfaces(object): """Interfaces class. F5 BIG-IP interfaces class. Attributes: api: iControl API instance. interfaces: A list of BIG-IP interface names. """ def __init__(self, api, regex=None): self.api = api self.interfaces = api.Networking.Interfaces.get_list() if regex: re_filter = re.compile(regex) self.interfaces = filter(re_filter.search, self.interfaces) def get_list(self): return self.interfaces def get_active_media(self): return self.api.Networking.Interfaces.get_active_media(self.interfaces) def get_actual_flow_control(self): return self.api.Networking.Interfaces.get_actual_flow_control(self.interfaces) def get_bundle_state(self): return self.api.Networking.Interfaces.get_bundle_state(self.interfaces) def get_description(self): return self.api.Networking.Interfaces.get_description(self.interfaces) def get_dual_media_state(self): return self.api.Networking.Interfaces.get_dual_media_state(self.interfaces) def get_enabled_state(self): return self.api.Networking.Interfaces.get_enabled_state(self.interfaces) def get_if_index(self): return self.api.Networking.Interfaces.get_if_index(self.interfaces) def get_learning_mode(self): return self.api.Networking.Interfaces.get_learning_mode(self.interfaces) def get_lldp_admin_status(self): return self.api.Networking.Interfaces.get_lldp_admin_status(self.interfaces) def get_lldp_tlvmap(self): return self.api.Networking.Interfaces.get_lldp_tlvmap(self.interfaces) def get_mac_address(self): return self.api.Networking.Interfaces.get_mac_address(self.interfaces) def get_media(self): return self.api.Networking.Interfaces.get_media(self.interfaces) def get_media_option(self): return self.api.Networking.Interfaces.get_media_option(self.interfaces) def get_media_option_sfp(self): return self.api.Networking.Interfaces.get_media_option_sfp(self.interfaces) def get_media_sfp(self): return self.api.Networking.Interfaces.get_media_sfp(self.interfaces) def get_media_speed(self): return self.api.Networking.Interfaces.get_media_speed(self.interfaces) def get_media_status(self): return self.api.Networking.Interfaces.get_media_status(self.interfaces) def get_mtu(self): return self.api.Networking.Interfaces.get_mtu(self.interfaces) def get_phy_master_slave_mode(self): return self.api.Networking.Interfaces.get_phy_master_slave_mode(self.interfaces) def get_prefer_sfp_state(self): return self.api.Networking.Interfaces.get_prefer_sfp_state(self.interfaces) def get_flow_control(self): return self.api.Networking.Interfaces.get_requested_flow_control(self.interfaces) def get_sflow_poll_interval(self): return self.api.Networking.Interfaces.get_sflow_poll_interval(self.interfaces) def get_sflow_poll_interval_global(self): return self.api.Networking.Interfaces.get_sflow_poll_interval_global(self.interfaces) def get_sfp_media_state(self): return self.api.Networking.Interfaces.get_sfp_media_state(self.interfaces) def get_stp_active_edge_port_state(self): return self.api.Networking.Interfaces.get_stp_active_edge_port_state(self.interfaces) def get_stp_enabled_state(self): return self.api.Networking.Interfaces.get_stp_enabled_state(self.interfaces) def get_stp_link_type(self): return self.api.Networking.Interfaces.get_stp_link_type(self.interfaces) def get_stp_protocol_detection_reset_state(self): return self.api.Networking.Interfaces.get_stp_protocol_detection_reset_state(self.interfaces) class SelfIPs(object): """Self IPs class. F5 BIG-IP Self IPs class. Attributes: api: iControl API instance. self_ips: List of self IPs. """ def __init__(self, api, regex=None): self.api = api self.self_ips = api.Networking.SelfIPV2.get_list() if regex: re_filter = re.compile(regex) self.self_ips = filter(re_filter.search, self.self_ips) def get_list(self): return self.self_ips def get_address(self): return self.api.Networking.SelfIPV2.get_address(self.self_ips) def get_allow_access_list(self): return self.api.Networking.SelfIPV2.get_allow_access_list(self.self_ips) def get_description(self): return self.api.Networking.SelfIPV2.get_description(self.self_ips) def get_enforced_firewall_policy(self): return self.api.Networking.SelfIPV2.get_enforced_firewall_policy(self.self_ips) def get_floating_state(self): return self.api.Networking.SelfIPV2.get_floating_state(self.self_ips) def get_fw_rule(self): return self.api.Networking.SelfIPV2.get_fw_rule(self.self_ips) def get_netmask(self): return self.api.Networking.SelfIPV2.get_netmask(self.self_ips) def get_staged_firewall_policy(self): return self.api.Networking.SelfIPV2.get_staged_firewall_policy(self.self_ips) def get_traffic_group(self): return self.api.Networking.SelfIPV2.get_traffic_group(self.self_ips) def get_vlan(self): return self.api.Networking.SelfIPV2.get_vlan(self.self_ips) def get_is_traffic_group_inherited(self): return self.api.Networking.SelfIPV2.is_traffic_group_inherited(self.self_ips) class Trunks(object): """Trunks class. F5 BIG-IP trunks class. Attributes: api: iControl API instance. trunks: List of trunks. """ def __init__(self, api, regex=None): self.api = api self.trunks = api.Networking.Trunk.get_list() if regex: re_filter = re.compile(regex) self.trunks = filter(re_filter.search, self.trunks) def get_list(self): return self.trunks def get_active_lacp_state(self): return self.api.Networking.Trunk.get_active_lacp_state(self.trunks) def get_configured_member_count(self): return self.api.Networking.Trunk.get_configured_member_count(self.trunks) def get_description(self): return self.api.Networking.Trunk.get_description(self.trunks) def get_distribution_hash_option(self): return self.api.Networking.Trunk.get_distribution_hash_option(self.trunks) def get_interface(self): return self.api.Networking.Trunk.get_interface(self.trunks) def get_lacp_enabled_state(self): return self.api.Networking.Trunk.get_lacp_enabled_state(self.trunks) def get_lacp_timeout_option(self): return self.api.Networking.Trunk.get_lacp_timeout_option(self.trunks) def get_link_selection_policy(self): return self.api.Networking.Trunk.get_link_selection_policy(self.trunks) def get_media_speed(self): return self.api.Networking.Trunk.get_media_speed(self.trunks) def get_media_status(self): return self.api.Networking.Trunk.get_media_status(self.trunks) def get_operational_member_count(self): return self.api.Networking.Trunk.get_operational_member_count(self.trunks) def get_stp_enabled_state(self): return self.api.Networking.Trunk.get_stp_enabled_state(self.trunks) def get_stp_protocol_detection_reset_state(self): return self.api.Networking.Trunk.get_stp_protocol_detection_reset_state(self.trunks) class Vlans(object): """Vlans class. F5 BIG-IP Vlans class. Attributes: api: iControl API instance. vlans: List of VLANs. """ def __init__(self, api, regex=None): self.api = api self.vlans = api.Networking.VLAN.get_list() if regex: re_filter = re.compile(regex) self.vlans = filter(re_filter.search, self.vlans) def get_list(self): return self.vlans def get_auto_lasthop(self): return self.api.Networking.VLAN.get_auto_lasthop(self.vlans) def get_cmp_hash_algorithm(self): return self.api.Networking.VLAN.get_cmp_hash_algorithm(self.vlans) def get_description(self): return self.api.Networking.VLAN.get_description(self.vlans) def get_dynamic_forwarding(self): return self.api.Networking.VLAN.get_dynamic_forwarding(self.vlans) def get_failsafe_action(self): return self.api.Networking.VLAN.get_failsafe_action(self.vlans) def get_failsafe_state(self): return self.api.Networking.VLAN.get_failsafe_state(self.vlans) def get_failsafe_timeout(self): return self.api.Networking.VLAN.get_failsafe_timeout(self.vlans) def get_if_index(self): return self.api.Networking.VLAN.get_if_index(self.vlans) def get_learning_mode(self): return self.api.Networking.VLAN.get_learning_mode(self.vlans) def get_mac_masquerade_address(self): return self.api.Networking.VLAN.get_mac_masquerade_address(self.vlans) def get_member(self): return self.api.Networking.VLAN.get_member(self.vlans) def get_mtu(self): return self.api.Networking.VLAN.get_mtu(self.vlans) def get_sflow_poll_interval(self): return self.api.Networking.VLAN.get_sflow_poll_interval(self.vlans) def get_sflow_poll_interval_global(self): return self.api.Networking.VLAN.get_sflow_poll_interval_global(self.vlans) def get_sflow_sampling_rate(self): return self.api.Networking.VLAN.get_sflow_sampling_rate(self.vlans) def get_sflow_sampling_rate_global(self): return self.api.Networking.VLAN.get_sflow_sampling_rate_global(self.vlans) def get_source_check_state(self): return self.api.Networking.VLAN.get_source_check_state(self.vlans) def get_true_mac_address(self): return self.api.Networking.VLAN.get_true_mac_address(self.vlans) def get_vlan_id(self): return self.api.Networking.VLAN.get_vlan_id(self.vlans) class Software(object): """Software class. F5 BIG-IP software class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_all_software_status(self): return self.api.System.SoftwareManagement.get_all_software_status() class VirtualServers(object): """Virtual servers class. F5 BIG-IP virtual servers class. Attributes: api: iControl API instance. virtual_servers: List of virtual servers. """ def __init__(self, api, regex=None): self.api = api self.virtual_servers = api.LocalLB.VirtualServer.get_list() if regex: re_filter = re.compile(regex) self.virtual_servers = filter(re_filter.search, self.virtual_servers) def get_list(self): return self.virtual_servers def get_name(self): return [x[x.rfind('/') + 1:] for x in self.virtual_servers] def get_actual_hardware_acceleration(self): return self.api.LocalLB.VirtualServer.get_actual_hardware_acceleration(self.virtual_servers) def get_authentication_profile(self): return self.api.LocalLB.VirtualServer.get_authentication_profile(self.virtual_servers) def get_auto_lasthop(self): return self.api.LocalLB.VirtualServer.get_auto_lasthop(self.virtual_servers) def get_bw_controller_policy(self): return self.api.LocalLB.VirtualServer.get_bw_controller_policy(self.virtual_servers) def get_clone_pool(self): return self.api.LocalLB.VirtualServer.get_clone_pool(self.virtual_servers) def get_cmp_enable_mode(self): return self.api.LocalLB.VirtualServer.get_cmp_enable_mode(self.virtual_servers) def get_connection_limit(self): return self.api.LocalLB.VirtualServer.get_connection_limit(self.virtual_servers) def get_connection_mirror_state(self): return self.api.LocalLB.VirtualServer.get_connection_mirror_state(self.virtual_servers) def get_default_pool_name(self): return self.api.LocalLB.VirtualServer.get_default_pool_name(self.virtual_servers) def get_description(self): return self.api.LocalLB.VirtualServer.get_description(self.virtual_servers) def get_destination(self): return self.api.LocalLB.VirtualServer.get_destination_v2(self.virtual_servers) def get_enabled_state(self): return self.api.LocalLB.VirtualServer.get_enabled_state(self.virtual_servers) def get_enforced_firewall_policy(self): return self.api.LocalLB.VirtualServer.get_enforced_firewall_policy(self.virtual_servers) def get_fallback_persistence_profile(self): return self.api.LocalLB.VirtualServer.get_fallback_persistence_profile(self.virtual_servers) def get_fw_rule(self): return self.api.LocalLB.VirtualServer.get_fw_rule(self.virtual_servers) def get_gtm_score(self): return self.api.LocalLB.VirtualServer.get_gtm_score(self.virtual_servers) def get_last_hop_pool(self): return self.api.LocalLB.VirtualServer.get_last_hop_pool(self.virtual_servers) def get_nat64_state(self): return self.api.LocalLB.VirtualServer.get_nat64_state(self.virtual_servers) def get_object_status(self): return self.api.LocalLB.VirtualServer.get_object_status(self.virtual_servers) def get_persistence_profile(self): return self.api.LocalLB.VirtualServer.get_persistence_profile(self.virtual_servers) def get_profile(self): return self.api.LocalLB.VirtualServer.get_profile(self.virtual_servers) def get_protocol(self): return self.api.LocalLB.VirtualServer.get_protocol(self.virtual_servers) def get_rate_class(self): return self.api.LocalLB.VirtualServer.get_rate_class(self.virtual_servers) def get_rate_limit(self): return self.api.LocalLB.VirtualServer.get_rate_limit(self.virtual_servers) def get_rate_limit_destination_mask(self): return self.api.LocalLB.VirtualServer.get_rate_limit_destination_mask(self.virtual_servers) def get_rate_limit_mode(self): return self.api.LocalLB.VirtualServer.get_rate_limit_mode(self.virtual_servers) def get_rate_limit_source_mask(self): return self.api.LocalLB.VirtualServer.get_rate_limit_source_mask(self.virtual_servers) def get_related_rule(self): return self.api.LocalLB.VirtualServer.get_related_rule(self.virtual_servers) def get_rule(self): return self.api.LocalLB.VirtualServer.get_rule(self.virtual_servers) def get_security_log_profile(self): return self.api.LocalLB.VirtualServer.get_security_log_profile(self.virtual_servers) def get_snat_pool(self): return self.api.LocalLB.VirtualServer.get_snat_pool(self.virtual_servers) def get_snat_type(self): return self.api.LocalLB.VirtualServer.get_snat_type(self.virtual_servers) def get_source_address(self): return self.api.LocalLB.VirtualServer.get_source_address(self.virtual_servers) def get_source_address_translation_lsn_pool(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_lsn_pool(self.virtual_servers) def get_source_address_translation_snat_pool(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_snat_pool(self.virtual_servers) def get_source_address_translation_type(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_type(self.virtual_servers) def get_source_port_behavior(self): return self.api.LocalLB.VirtualServer.get_source_port_behavior(self.virtual_servers) def get_staged_firewall_policy(self): return self.api.LocalLB.VirtualServer.get_staged_firewall_policy(self.virtual_servers) def get_translate_address_state(self): return self.api.LocalLB.VirtualServer.get_translate_address_state(self.virtual_servers) def get_translate_port_state(self): return self.api.LocalLB.VirtualServer.get_translate_port_state(self.virtual_servers) def get_type(self): return self.api.LocalLB.VirtualServer.get_type(self.virtual_servers) def get_vlan(self): return self.api.LocalLB.VirtualServer.get_vlan(self.virtual_servers) def get_wildmask(self): return self.api.LocalLB.VirtualServer.get_wildmask(self.virtual_servers) class Pools(object): """Pools class. F5 BIG-IP pools class. Attributes: api: iControl API instance. pool_names: List of pool names. """ def __init__(self, api, regex=None): self.api = api self.pool_names = api.LocalLB.Pool.get_list() if regex: re_filter = re.compile(regex) self.pool_names = filter(re_filter.search, self.pool_names) def get_list(self): return self.pool_names def get_name(self): return [x[x.rfind('/') + 1:] for x in self.pool_names] def get_action_on_service_down(self): return self.api.LocalLB.Pool.get_action_on_service_down(self.pool_names) def get_active_member_count(self): return self.api.LocalLB.Pool.get_active_member_count(self.pool_names) def get_aggregate_dynamic_ratio(self): return self.api.LocalLB.Pool.get_aggregate_dynamic_ratio(self.pool_names) def get_allow_nat_state(self): return self.api.LocalLB.Pool.get_allow_nat_state(self.pool_names) def get_allow_snat_state(self): return self.api.LocalLB.Pool.get_allow_snat_state(self.pool_names) def get_client_ip_tos(self): return self.api.LocalLB.Pool.get_client_ip_tos(self.pool_names) def get_client_link_qos(self): return self.api.LocalLB.Pool.get_client_link_qos(self.pool_names) def get_description(self): return self.api.LocalLB.Pool.get_description(self.pool_names) def get_gateway_failsafe_device(self): return self.api.LocalLB.Pool.get_gateway_failsafe_device(self.pool_names) def get_ignore_persisted_weight_state(self): return self.api.LocalLB.Pool.get_ignore_persisted_weight_state(self.pool_names) def get_lb_method(self): result = [] lb_choice = dict( LB_METHOD_DYNAMIC_RATIO_MEMBER='dynamic-ratio-member', LB_METHOD_DYNAMIC_RATIO='dynamic-ratio-node', LB_METHOD_FASTEST_APP_RESPONSE='fastest-app-response', LB_METHOD_FASTEST_NODE_ADDRESS='fastest-node', LB_METHOD_LEAST_CONNECTION_MEMBER='least-connections-member', LB_METHOD_LEAST_CONNECTION_NODE_ADDRESS='least-connections-node', LB_METHOD_LEAST_SESSIONS='least-sessions', LB_METHOD_OBSERVED_MEMBER='observed-member', LB_METHOD_OBSERVED_NODE_ADDRESS='observed-node', LB_METHOD_PREDICTIVE_MEMBER='predictive-member', LB_METHOD_PREDICTIVE_NODE_ADDRESS='predictive-node', LB_METHOD_RATIO_LEAST_CONNECTION_MEMBER='ratio-least-connections-member', LB_METHOD_RATIO_LEAST_CONNECTION_NODE_ADDRESS='ratio-least-connections-node', LB_METHOD_RATIO_MEMBER='ratio-member', LB_METHOD_RATIO_NODE_ADDRESS='ratio-node', LB_METHOD_RATIO_SESSION='ratio-session', LB_METHOD_ROUND_ROBIN='round-robin', LB_METHOD_WEIGHTED_LEAST_CONNECTION_MEMBER='weighted-least-connections-member', LB_METHOD_WEIGHTED_LEAST_CONNECTION_NODE_ADDRESS='weighted-least-connections-node' ) methods = self.api.LocalLB.Pool.get_lb_method(self.pool_names) for method in methods: result.append(lb_choice.get(method, method)) return result def get_member(self): return self.api.LocalLB.Pool.get_member_v2(self.pool_names) def get_minimum_active_member(self): return self.api.LocalLB.Pool.get_minimum_active_member(self.pool_names) def get_minimum_up_member(self): return self.api.LocalLB.Pool.get_minimum_up_member(self.pool_names) def get_minimum_up_member_action(self): return self.api.LocalLB.Pool.get_minimum_up_member_action(self.pool_names) def get_minimum_up_member_enabled_state(self): return self.api.LocalLB.Pool.get_minimum_up_member_enabled_state(self.pool_names) def get_monitor_association(self): return self.api.LocalLB.Pool.get_monitor_association(self.pool_names) def get_monitor_instance(self): return self.api.LocalLB.Pool.get_monitor_instance(self.pool_names) def get_object_status(self): return self.api.LocalLB.Pool.get_object_status(self.pool_names) def get_profile(self): return self.api.LocalLB.Pool.get_profile(self.pool_names) def get_queue_depth_limit(self): return self.api.LocalLB.Pool.get_queue_depth_limit(self.pool_names) def get_queue_on_connection_limit_state(self): return self.api.LocalLB.Pool.get_queue_on_connection_limit_state(self.pool_names) def get_queue_time_limit(self): return self.api.LocalLB.Pool.get_queue_time_limit(self.pool_names) def get_reselect_tries(self): return self.api.LocalLB.Pool.get_reselect_tries(self.pool_names) def get_server_ip_tos(self): return self.api.LocalLB.Pool.get_server_ip_tos(self.pool_names) def get_server_link_qos(self): return self.api.LocalLB.Pool.get_server_link_qos(self.pool_names) def get_simple_timeout(self): return self.api.LocalLB.Pool.get_simple_timeout(self.pool_names) def get_slow_ramp_time(self): return self.api.LocalLB.Pool.get_slow_ramp_time(self.pool_names) class Devices(object): """Devices class. F5 BIG-IP devices class. Attributes: api: iControl API instance. devices: List of devices. """ def __init__(self, api, regex=None): self.api = api self.devices = api.Management.Device.get_list() if regex: re_filter = re.compile(regex) self.devices = filter(re_filter.search, self.devices) def get_list(self): return self.devices def get_active_modules(self): return self.api.Management.Device.get_active_modules(self.devices) def get_base_mac_address(self): return self.api.Management.Device.get_base_mac_address(self.devices) def get_blade_addresses(self): return self.api.Management.Device.get_blade_addresses(self.devices) def get_build(self): return self.api.Management.Device.get_build(self.devices) def get_chassis_id(self): return self.api.Management.Device.get_chassis_id(self.devices) def get_chassis_type(self): return self.api.Management.Device.get_chassis_type(self.devices) def get_comment(self): return self.api.Management.Device.get_comment(self.devices) def get_configsync_address(self): return self.api.Management.Device.get_configsync_address(self.devices) def get_contact(self): return self.api.Management.Device.get_contact(self.devices) def get_description(self): return self.api.Management.Device.get_description(self.devices) def get_edition(self): return self.api.Management.Device.get_edition(self.devices) def get_failover_state(self): return self.api.Management.Device.get_failover_state(self.devices) def get_local_device(self): return self.api.Management.Device.get_local_device() def get_hostname(self): return self.api.Management.Device.get_hostname(self.devices) def get_inactive_modules(self): return self.api.Management.Device.get_inactive_modules(self.devices) def get_location(self): return self.api.Management.Device.get_location(self.devices) def get_management_address(self): return self.api.Management.Device.get_management_address(self.devices) def get_marketing_name(self): return self.api.Management.Device.get_marketing_name(self.devices) def get_multicast_address(self): return self.api.Management.Device.get_multicast_address(self.devices) def get_optional_modules(self): return self.api.Management.Device.get_optional_modules(self.devices) def get_platform_id(self): return self.api.Management.Device.get_platform_id(self.devices) def get_primary_mirror_address(self): return self.api.Management.Device.get_primary_mirror_address(self.devices) def get_product(self): return self.api.Management.Device.get_product(self.devices) def get_secondary_mirror_address(self): return self.api.Management.Device.get_secondary_mirror_address(self.devices) def get_software_version(self): return self.api.Management.Device.get_software_version(self.devices) def get_timelimited_modules(self): return self.api.Management.Device.get_timelimited_modules(self.devices) def get_timezone(self): return self.api.Management.Device.get_timezone(self.devices) def get_unicast_addresses(self): return self.api.Management.Device.get_unicast_addresses(self.devices) class DeviceGroups(object): """Device groups class. F5 BIG-IP device groups class. Attributes: api: iControl API instance. device_groups: List of device groups. """ def __init__(self, api, regex=None): self.api = api self.device_groups = api.Management.DeviceGroup.get_list() if regex: re_filter = re.compile(regex) self.device_groups = filter(re_filter.search, self.device_groups) def get_list(self): return self.device_groups def get_all_preferred_active(self): return self.api.Management.DeviceGroup.get_all_preferred_active(self.device_groups) def get_autosync_enabled_state(self): return self.api.Management.DeviceGroup.get_autosync_enabled_state(self.device_groups) def get_description(self): return self.api.Management.DeviceGroup.get_description(self.device_groups) def get_device(self): return self.api.Management.DeviceGroup.get_device(self.device_groups) def get_full_load_on_sync_state(self): return self.api.Management.DeviceGroup.get_full_load_on_sync_state(self.device_groups) def get_incremental_config_sync_size_maximum(self): return self.api.Management.DeviceGroup.get_incremental_config_sync_size_maximum(self.device_groups) def get_network_failover_enabled_state(self): return self.api.Management.DeviceGroup.get_network_failover_enabled_state(self.device_groups) def get_sync_status(self): return self.api.Management.DeviceGroup.get_sync_status(self.device_groups) def get_type(self): return self.api.Management.DeviceGroup.get_type(self.device_groups) class TrafficGroups(object): """Traffic groups class. F5 BIG-IP traffic groups class. Attributes: api: iControl API instance. traffic_groups: List of traffic groups. """ def __init__(self, api, regex=None): self.api = api self.traffic_groups = api.Management.TrafficGroup.get_list() if regex: re_filter = re.compile(regex) self.traffic_groups = filter(re_filter.search, self.traffic_groups) def get_list(self): return self.traffic_groups def get_auto_failback_enabled_state(self): return self.api.Management.TrafficGroup.get_auto_failback_enabled_state(self.traffic_groups) def get_auto_failback_time(self): return self.api.Management.TrafficGroup.get_auto_failback_time(self.traffic_groups) def get_default_device(self): return self.api.Management.TrafficGroup.get_default_device(self.traffic_groups) def get_description(self): return self.api.Management.TrafficGroup.get_description(self.traffic_groups) def get_ha_load_factor(self): return self.api.Management.TrafficGroup.get_ha_load_factor(self.traffic_groups) def get_ha_order(self): return self.api.Management.TrafficGroup.get_ha_order(self.traffic_groups) def get_is_floating(self): return self.api.Management.TrafficGroup.get_is_floating(self.traffic_groups) def get_mac_masquerade_address(self): return self.api.Management.TrafficGroup.get_mac_masquerade_address(self.traffic_groups) def get_unit_id(self): return self.api.Management.TrafficGroup.get_unit_id(self.traffic_groups) class Rules(object): """Rules class. F5 BIG-IP iRules class. Attributes: api: iControl API instance. rules: List of iRules. """ def __init__(self, api, regex=None): self.api = api self.rules = api.LocalLB.Rule.get_list() if regex: re_filter = re.compile(regex) self.traffic_groups = filter(re_filter.search, self.rules) def get_list(self): return self.rules def get_description(self): return self.api.LocalLB.Rule.get_description(rule_names=self.rules) def get_ignore_vertification(self): return self.api.LocalLB.Rule.get_ignore_vertification(rule_names=self.rules) def get_verification_status(self): return self.api.LocalLB.Rule.get_verification_status_v2(rule_names=self.rules) def get_definition(self): return [x['rule_definition'] for x in self.api.LocalLB.Rule.query_rule(rule_names=self.rules)] class Nodes(object): """Nodes class. F5 BIG-IP nodes class. Attributes: api: iControl API instance. nodes: List of nodes. """ def __init__(self, api, regex=None): self.api = api self.nodes = api.LocalLB.NodeAddressV2.get_list() if regex: re_filter = re.compile(regex) self.nodes = filter(re_filter.search, self.nodes) def get_list(self): return self.nodes def get_address(self): return self.api.LocalLB.NodeAddressV2.get_address(nodes=self.nodes) def get_name(self): return [x[x.rfind('/') + 1:] for x in self.nodes] def get_connection_limit(self): return self.api.LocalLB.NodeAddressV2.get_connection_limit(nodes=self.nodes) def get_description(self): return self.api.LocalLB.NodeAddressV2.get_description(nodes=self.nodes) def get_dynamic_ratio(self): return self.api.LocalLB.NodeAddressV2.get_dynamic_ratio_v2(nodes=self.nodes) def get_monitor_instance(self): return self.api.LocalLB.NodeAddressV2.get_monitor_instance(nodes=self.nodes) def get_monitor_rule(self): return self.api.LocalLB.NodeAddressV2.get_monitor_rule(nodes=self.nodes) def get_monitor_status(self): return self.api.LocalLB.NodeAddressV2.get_monitor_status(nodes=self.nodes) def get_object_status(self): return self.api.LocalLB.NodeAddressV2.get_object_status(nodes=self.nodes) def get_rate_limit(self): return self.api.LocalLB.NodeAddressV2.get_rate_limit(nodes=self.nodes) def get_ratio(self): return self.api.LocalLB.NodeAddressV2.get_ratio(nodes=self.nodes) def get_session_status(self): return self.api.LocalLB.NodeAddressV2.get_session_status(nodes=self.nodes) class VirtualAddresses(object): """Virtual addresses class. F5 BIG-IP virtual addresses class. Attributes: api: iControl API instance. virtual_addresses: List of virtual addresses. """ def __init__(self, api, regex=None): self.api = api self.virtual_addresses = api.LocalLB.VirtualAddressV2.get_list() if regex: re_filter = re.compile(regex) self.virtual_addresses = filter(re_filter.search, self.virtual_addresses) def get_list(self): return self.virtual_addresses def get_address(self): return self.api.LocalLB.VirtualAddressV2.get_address(self.virtual_addresses) def get_arp_state(self): return self.api.LocalLB.VirtualAddressV2.get_arp_state(self.virtual_addresses) def get_auto_delete_state(self): return self.api.LocalLB.VirtualAddressV2.get_auto_delete_state(self.virtual_addresses) def get_connection_limit(self): return self.api.LocalLB.VirtualAddressV2.get_connection_limit(self.virtual_addresses) def get_description(self): return self.api.LocalLB.VirtualAddressV2.get_description(self.virtual_addresses) def get_enabled_state(self): return self.api.LocalLB.VirtualAddressV2.get_enabled_state(self.virtual_addresses) def get_icmp_echo_state(self): return self.api.LocalLB.VirtualAddressV2.get_icmp_echo_state(self.virtual_addresses) def get_is_floating_state(self): return self.api.LocalLB.VirtualAddressV2.get_is_floating_state(self.virtual_addresses) def get_netmask(self): return self.api.LocalLB.VirtualAddressV2.get_netmask(self.virtual_addresses) def get_object_status(self): return self.api.LocalLB.VirtualAddressV2.get_object_status(self.virtual_addresses) def get_route_advertisement_state(self): return self.api.LocalLB.VirtualAddressV2.get_route_advertisement_state(self.virtual_addresses) def get_traffic_group(self): return self.api.LocalLB.VirtualAddressV2.get_traffic_group(self.virtual_addresses) class AddressClasses(object): """Address group/class class. F5 BIG-IP address group/class class. In TMUI these things are known as Address Data Groups. Examples that ship with the box include /Common/aol and /Common/private_net Attributes: api: iControl API instance. address_classes: List of address classes. """ def __init__(self, api, regex=None): self.api = api self.address_classes = api.LocalLB.Class.get_address_class_list() if regex: re_filter = re.compile(regex) self.address_classes = filter(re_filter.search, self.address_classes) def get_list(self): return self.address_classes def get_address_class(self): key = self.api.LocalLB.Class.get_address_class(self.address_classes) value = self.api.LocalLB.Class.get_address_class_member_data_value(key) result = [] for idx, v in enumerate(key): for idx2, member in enumerate(v['members']): dg_value = dict( value=value[idx][idx2] ) dg_value.update(member) result.append(dg_value) return result def get_description(self): return self.api.LocalLB.Class.get_description(self.address_classes) class Certificates(object): """Certificates class. F5 BIG-IP certificates class. Attributes: api: iControl API instance. certificates: List of certificate identifiers. certificate_list: List of certificate information structures. """ def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"): self.api = api self.certificate_list = api.Management.KeyCertificate.get_certificate_list(mode=mode) self.certificates = [x['certificate']['cert_info']['id'] for x in self.certificate_list] if regex: re_filter = re.compile(regex) self.certificates = filter(re_filter.search, self.certificates) self.certificate_list = [x for x in self.certificate_list if x['certificate']['cert_info']['id'] in self.certificates] def get_list(self): return self.certificates def get_certificate_list(self): return self.certificate_list class Keys(object): """Keys class. F5 BIG-IP keys class. Attributes: api: iControl API instance. keys: List of key identifiers. key_list: List of key information structures. """ def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"): self.api = api self.key_list = api.Management.KeyCertificate.get_key_list(mode=mode) self.keys = [x['key_info']['id'] for x in self.key_list] if regex: re_filter = re.compile(regex) self.keys = filter(re_filter.search, self.keys) self.key_list = [x for x in self.key_list if x['key_info']['id'] in self.keys] def get_list(self): return self.keys def get_key_list(self): return self.key_list class ProfileClientSSL(object): """Client SSL profiles class. F5 BIG-IP client SSL profiles class. Attributes: api: iControl API instance. profiles: List of client SSL profiles. """ def __init__(self, api, regex=None): self.api = api self.profiles = api.LocalLB.ProfileClientSSL.get_list() if regex: re_filter = re.compile(regex) self.profiles = filter(re_filter.search, self.profiles) def get_list(self): return self.profiles def get_alert_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_alert_timeout(self.profiles) def get_allow_nonssl_state(self): return self.api.LocalLB.ProfileClientSSL.get_allow_nonssl_state(self.profiles) def get_authenticate_depth(self): return self.api.LocalLB.ProfileClientSSL.get_authenticate_depth(self.profiles) def get_authenticate_once_state(self): return self.api.LocalLB.ProfileClientSSL.get_authenticate_once_state(self.profiles) def get_ca_file(self): return self.api.LocalLB.ProfileClientSSL.get_ca_file_v2(self.profiles) def get_cache_size(self): return self.api.LocalLB.ProfileClientSSL.get_cache_size(self.profiles) def get_cache_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_cache_timeout(self.profiles) def get_certificate_file(self): return self.api.LocalLB.ProfileClientSSL.get_certificate_file_v2(self.profiles) def get_chain_file(self): return self.api.LocalLB.ProfileClientSSL.get_chain_file_v2(self.profiles) def get_cipher_list(self): return self.api.LocalLB.ProfileClientSSL.get_cipher_list(self.profiles) def get_client_certificate_ca_file(self): return self.api.LocalLB.ProfileClientSSL.get_client_certificate_ca_file_v2(self.profiles) def get_crl_file(self): return self.api.LocalLB.ProfileClientSSL.get_crl_file_v2(self.profiles) def get_default_profile(self): return self.api.LocalLB.ProfileClientSSL.get_default_profile(self.profiles) def get_description(self): return self.api.LocalLB.ProfileClientSSL.get_description(self.profiles) def get_forward_proxy_ca_certificate_file(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_certificate_file(self.profiles) def get_forward_proxy_ca_key_file(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_key_file(self.profiles) def get_forward_proxy_ca_passphrase(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_passphrase(self.profiles) def get_forward_proxy_certificate_extension_include(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_extension_include(self.profiles) def get_forward_proxy_certificate_lifespan(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_lifespan(self.profiles) def get_forward_proxy_enabled_state(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_enabled_state(self.profiles) def get_forward_proxy_lookup_by_ipaddr_port_state(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_lookup_by_ipaddr_port_state(self.profiles) def get_handshake_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_handshake_timeout(self.profiles) def get_key_file(self): return self.api.LocalLB.ProfileClientSSL.get_key_file_v2(self.profiles) def get_modssl_emulation_state(self): return self.api.LocalLB.ProfileClientSSL.get_modssl_emulation_state(self.profiles) def get_passphrase(self): return self.api.LocalLB.ProfileClientSSL.get_passphrase(self.profiles) def get_peer_certification_mode(self): return self.api.LocalLB.ProfileClientSSL.get_peer_certification_mode(self.profiles) def get_profile_mode(self): return self.api.LocalLB.ProfileClientSSL.get_profile_mode(self.profiles) def get_renegotiation_maximum_record_delay(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_maximum_record_delay(self.profiles) def get_renegotiation_period(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_period(self.profiles) def get_renegotiation_state(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_state(self.profiles) def get_renegotiation_throughput(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_throughput(self.profiles) def get_retain_certificate_state(self): return self.api.LocalLB.ProfileClientSSL.get_retain_certificate_state(self.profiles) def get_secure_renegotiation_mode(self): return self.api.LocalLB.ProfileClientSSL.get_secure_renegotiation_mode(self.profiles) def get_server_name(self): return self.api.LocalLB.ProfileClientSSL.get_server_name(self.profiles) def get_session_ticket_state(self): return self.api.LocalLB.ProfileClientSSL.get_session_ticket_state(self.profiles) def get_sni_default_state(self): return self.api.LocalLB.ProfileClientSSL.get_sni_default_state(self.profiles) def get_sni_require_state(self): return self.api.LocalLB.ProfileClientSSL.get_sni_require_state(self.profiles) def get_ssl_option(self): return self.api.LocalLB.ProfileClientSSL.get_ssl_option(self.profiles) def get_strict_resume_state(self): return self.api.LocalLB.ProfileClientSSL.get_strict_resume_state(self.profiles) def get_unclean_shutdown_state(self): return self.api.LocalLB.ProfileClientSSL.get_unclean_shutdown_state(self.profiles) def get_is_base_profile(self): return self.api.LocalLB.ProfileClientSSL.is_base_profile(self.profiles) def get_is_system_profile(self): return self.api.LocalLB.ProfileClientSSL.is_system_profile(self.profiles) class SystemInfo(object): """System information class. F5 BIG-IP system information class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_base_mac_address(self): return self.api.System.SystemInfo.get_base_mac_address() def get_blade_temperature(self): return self.api.System.SystemInfo.get_blade_temperature() def get_chassis_slot_information(self): return self.api.System.SystemInfo.get_chassis_slot_information() def get_globally_unique_identifier(self): return self.api.System.SystemInfo.get_globally_unique_identifier() def get_group_id(self): return self.api.System.SystemInfo.get_group_id() def get_hardware_information(self): return self.api.System.SystemInfo.get_hardware_information() def get_marketing_name(self): return self.api.System.SystemInfo.get_marketing_name() def get_product_information(self): return self.api.System.SystemInfo.get_product_information() def get_pva_version(self): return self.api.System.SystemInfo.get_pva_version() def get_system_id(self): return self.api.System.SystemInfo.get_system_id() def get_system_information(self): return self.api.System.SystemInfo.get_system_information() def get_time(self): return self.api.System.SystemInfo.get_time() def get_time_zone(self): return self.api.System.SystemInfo.get_time_zone() def get_uptime(self): return self.api.System.SystemInfo.get_uptime() class ProvisionInfo(object): """Provision information class. F5 BIG-IP provision information class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_list(self): result = [] list = self.api.Management.Provision.get_list() for item in list: item = item.lower().replace('tmos_module_', '') result.append(item) return result def get_provisioned_list(self): result = [] list = self.api.Management.Provision.get_provisioned_list() for item in list: item = item.lower().replace('tmos_module_', '') result.append(item) return result def generate_dict(api_obj, fields): result_dict = {} lists = [] supported_fields = [] if api_obj.get_list(): for field in fields: try: api_response = getattr(api_obj, "get_" + field)() except (MethodNotFound, WebFault): pass else: lists.append(api_response) supported_fields.append(field) for i, j in enumerate(api_obj.get_list()): temp = {} temp.update([(item[0], item[1][i]) for item in zip(supported_fields, lists)]) result_dict[j] = temp return result_dict def generate_simple_dict(api_obj, fields): result_dict = {} for field in fields: try: api_response = getattr(api_obj, "get_" + field)() except (MethodNotFound, WebFault): pass else: result_dict[field] = api_response return result_dict def generate_interface_dict(f5, regex): interfaces = Interfaces(f5.get_api(), regex) fields = ['active_media', 'actual_flow_control', 'bundle_state', 'description', 'dual_media_state', 'enabled_state', 'if_index', 'learning_mode', 'lldp_admin_status', 'lldp_tlvmap', 'mac_address', 'media', 'media_option', 'media_option_sfp', 'media_sfp', 'media_speed', 'media_status', 'mtu', 'phy_master_slave_mode', 'prefer_sfp_state', 'flow_control', 'sflow_poll_interval', 'sflow_poll_interval_global', 'sfp_media_state', 'stp_active_edge_port_state', 'stp_enabled_state', 'stp_link_type', 'stp_protocol_detection_reset_state'] return generate_dict(interfaces, fields) def generate_self_ip_dict(f5, regex): self_ips = SelfIPs(f5.get_api(), regex) fields = ['address', 'allow_access_list', 'description', 'enforced_firewall_policy', 'floating_state', 'fw_rule', 'netmask', 'staged_firewall_policy', 'traffic_group', 'vlan', 'is_traffic_group_inherited'] return generate_dict(self_ips, fields) def generate_trunk_dict(f5, regex): trunks = Trunks(f5.get_api(), regex) fields = ['active_lacp_state', 'configured_member_count', 'description', 'distribution_hash_option', 'interface', 'lacp_enabled_state', 'lacp_timeout_option', 'link_selection_policy', 'media_speed', 'media_status', 'operational_member_count', 'stp_enabled_state', 'stp_protocol_detection_reset_state'] return generate_dict(trunks, fields) def generate_vlan_dict(f5, regex): vlans = Vlans(f5.get_api(), regex) fields = ['auto_lasthop', 'cmp_hash_algorithm', 'description', 'dynamic_forwarding', 'failsafe_action', 'failsafe_state', 'failsafe_timeout', 'if_index', 'learning_mode', 'mac_masquerade_address', 'member', 'mtu', 'sflow_poll_interval', 'sflow_poll_interval_global', 'sflow_sampling_rate', 'sflow_sampling_rate_global', 'source_check_state', 'true_mac_address', 'vlan_id'] return generate_dict(vlans, fields) def generate_vs_dict(f5, regex): virtual_servers = VirtualServers(f5.get_api(), regex) fields = ['actual_hardware_acceleration', 'authentication_profile', 'auto_lasthop', 'bw_controller_policy', 'clone_pool', 'cmp_enable_mode', 'connection_limit', 'connection_mirror_state', 'default_pool_name', 'description', 'destination', 'enabled_state', 'enforced_firewall_policy', 'fallback_persistence_profile', 'fw_rule', 'gtm_score', 'last_hop_pool', 'nat64_state', 'object_status', 'persistence_profile', 'profile', 'protocol', 'rate_class', 'rate_limit', 'rate_limit_destination_mask', 'rate_limit_mode', 'rate_limit_source_mask', 'related_rule', 'rule', 'security_log_profile', 'snat_pool', 'snat_type', 'source_address', 'source_address_translation_lsn_pool', 'source_address_translation_snat_pool', 'source_address_translation_type', 'source_port_behavior', 'staged_firewall_policy', 'translate_address_state', 'translate_port_state', 'type', 'vlan', 'wildmask', 'name'] return generate_dict(virtual_servers, fields) def generate_pool_dict(f5, regex): pools = Pools(f5.get_api(), regex) fields = ['action_on_service_down', 'active_member_count', 'aggregate_dynamic_ratio', 'allow_nat_state', 'allow_snat_state', 'client_ip_tos', 'client_link_qos', 'description', 'gateway_failsafe_device', 'ignore_persisted_weight_state', 'lb_method', 'member', 'minimum_active_member', 'minimum_up_member', 'minimum_up_member_action', 'minimum_up_member_enabled_state', 'monitor_association', 'monitor_instance', 'object_status', 'profile', 'queue_depth_limit', 'queue_on_connection_limit_state', 'queue_time_limit', 'reselect_tries', 'server_ip_tos', 'server_link_qos', 'simple_timeout', 'slow_ramp_time', 'name'] return generate_dict(pools, fields) def generate_device_dict(f5, regex): devices = Devices(f5.get_api(), regex) fields = ['active_modules', 'base_mac_address', 'blade_addresses', 'build', 'chassis_id', 'chassis_type', 'comment', 'configsync_address', 'contact', 'description', 'edition', 'failover_state', 'hostname', 'inactive_modules', 'location', 'management_address', 'marketing_name', 'multicast_address', 'optional_modules', 'platform_id', 'primary_mirror_address', 'product', 'secondary_mirror_address', 'software_version', 'timelimited_modules', 'timezone', 'unicast_addresses'] return generate_dict(devices, fields) def generate_device_group_dict(f5, regex): device_groups = DeviceGroups(f5.get_api(), regex) fields = ['all_preferred_active', 'autosync_enabled_state', 'description', 'device', 'full_load_on_sync_state', 'incremental_config_sync_size_maximum', 'network_failover_enabled_state', 'sync_status', 'type'] return generate_dict(device_groups, fields) def generate_traffic_group_dict(f5, regex): traffic_groups = TrafficGroups(f5.get_api(), regex) fields = ['auto_failback_enabled_state', 'auto_failback_time', 'default_device', 'description', 'ha_load_factor', 'ha_order', 'is_floating', 'mac_masquerade_address', 'unit_id'] return generate_dict(traffic_groups, fields) def generate_rule_dict(f5, regex): rules = Rules(f5.get_api(), regex) fields = ['definition', 'description', 'ignore_vertification', 'verification_status'] return generate_dict(rules, fields) def generate_node_dict(f5, regex): nodes = Nodes(f5.get_api(), regex) fields = ['name', 'address', 'connection_limit', 'description', 'dynamic_ratio', 'monitor_instance', 'monitor_rule', 'monitor_status', 'object_status', 'rate_limit', 'ratio', 'session_status'] return generate_dict(nodes, fields) def generate_virtual_address_dict(f5, regex): virtual_addresses = VirtualAddresses(f5.get_api(), regex) fields = ['address', 'arp_state', 'auto_delete_state', 'connection_limit', 'description', 'enabled_state', 'icmp_echo_state', 'is_floating_state', 'netmask', 'object_status', 'route_advertisement_state', 'traffic_group'] return generate_dict(virtual_addresses, fields) def generate_address_class_dict(f5, regex): address_classes = AddressClasses(f5.get_api(), regex) fields = ['address_class', 'description'] return generate_dict(address_classes, fields) def generate_certificate_dict(f5, regex): certificates = Certificates(f5.get_api(), regex) return dict(zip(certificates.get_list(), certificates.get_certificate_list())) def generate_key_dict(f5, regex): keys = Keys(f5.get_api(), regex) return dict(zip(keys.get_list(), keys.get_key_list())) def generate_client_ssl_profile_dict(f5, regex): profiles = ProfileClientSSL(f5.get_api(), regex) fields = ['alert_timeout', 'allow_nonssl_state', 'authenticate_depth', 'authenticate_once_state', 'ca_file', 'cache_size', 'cache_timeout', 'certificate_file', 'chain_file', 'cipher_list', 'client_certificate_ca_file', 'crl_file', 'default_profile', 'description', 'forward_proxy_ca_certificate_file', 'forward_proxy_ca_key_file', 'forward_proxy_ca_passphrase', 'forward_proxy_certificate_extension_include', 'forward_proxy_certificate_lifespan', 'forward_proxy_enabled_state', 'forward_proxy_lookup_by_ipaddr_port_state', 'handshake_timeout', 'key_file', 'modssl_emulation_state', 'passphrase', 'peer_certification_mode', 'profile_mode', 'renegotiation_maximum_record_delay', 'renegotiation_period', 'renegotiation_state', 'renegotiation_throughput', 'retain_certificate_state', 'secure_renegotiation_mode', 'server_name', 'session_ticket_state', 'sni_default_state', 'sni_require_state', 'ssl_option', 'strict_resume_state', 'unclean_shutdown_state', 'is_base_profile', 'is_system_profile'] return generate_dict(profiles, fields) def generate_system_info_dict(f5): system_info = SystemInfo(f5.get_api()) fields = ['base_mac_address', 'blade_temperature', 'chassis_slot_information', 'globally_unique_identifier', 'group_id', 'hardware_information', 'marketing_name', 'product_information', 'pva_version', 'system_id', 'system_information', 'time', 'time_zone', 'uptime'] return generate_simple_dict(system_info, fields) def generate_software_list(f5): software = Software(f5.get_api()) software_list = software.get_all_software_status() return software_list def generate_provision_dict(f5): provisioned = ProvisionInfo(f5.get_api()) fields = ['list', 'provisioned_list'] return generate_simple_dict(provisioned, fields) def main(): argument_spec = f5_argument_spec meta_args = dict( session=dict(type='bool', default='no'), include=dict( type='raw', required=True, choices=[ 'address_class', 'certificate', 'client_ssl_profile', 'device', 'device_group', 'interface', 'key', 'node', 'pool', 'provision', 'rule', 'self_ip', 'software', 'system_info', 'traffic_group', 'trunk', 'virtual_address', 'virtual_server', 'vlan' ] ), filter=dict(type='str'), ) argument_spec.update(meta_args) module = AnsibleModule( argument_spec=argument_spec ) if not bigsuds_found: module.fail_json(msg="the python suds and bigsuds modules are required") server = module.params['server'] server_port = module.params['server_port'] user = module.params['user'] password = module.params['password'] validate_certs = module.params['validate_certs'] session = module.params['session'] fact_filter = module.params['filter'] if validate_certs: import ssl if not hasattr(ssl, 'SSLContext'): module.fail_json( msg='bigsuds does not support verifying certificates with python < 2.7.9. Either update python or set validate_certs=False on the task' ) if fact_filter: regex = fnmatch.translate(fact_filter) else: regex = None if isinstance(module.params['include'], string_types): includes = module.params['include'].split(',') else: includes = module.params['include'] include = [x.lower() for x in includes] valid_includes = ('address_class', 'certificate', 'client_ssl_profile', 'device', 'device_group', 'interface', 'key', 'node', 'pool', 'provision', 'rule', 'self_ip', 'software', 'system_info', 'traffic_group', 'trunk', 'virtual_address', 'virtual_server', 'vlan') include_test = (x in valid_includes for x in include) if not all(include_test): module.fail_json(msg="Value of include must be one or more of: %s, got: %s" % (",".join(valid_includes), ",".join(include))) try: facts = {} if len(include) > 0: f5 = F5(server, user, password, session, validate_certs, server_port) saved_active_folder = f5.get_active_folder() saved_recursive_query_state = f5.get_recursive_query_state() if saved_active_folder != "/": f5.set_active_folder("/") if saved_recursive_query_state != "STATE_ENABLED": f5.enable_recursive_query_state() if 'interface' in include: facts['interface'] = generate_interface_dict(f5, regex) if 'self_ip' in include: facts['self_ip'] = generate_self_ip_dict(f5, regex) if 'trunk' in include: facts['trunk'] = generate_trunk_dict(f5, regex) if 'vlan' in include: facts['vlan'] = generate_vlan_dict(f5, regex) if 'virtual_server' in include: facts['virtual_server'] = generate_vs_dict(f5, regex) if 'pool' in include: facts['pool'] = generate_pool_dict(f5, regex) if 'provision' in include: facts['provision'] = generate_provision_dict(f5) if 'device' in include: facts['device'] = generate_device_dict(f5, regex) if 'device_group' in include: facts['device_group'] = generate_device_group_dict(f5, regex) if 'traffic_group' in include: facts['traffic_group'] = generate_traffic_group_dict(f5, regex) if 'rule' in include: facts['rule'] = generate_rule_dict(f5, regex) if 'node' in include: facts['node'] = generate_node_dict(f5, regex) if 'virtual_address' in include: facts['virtual_address'] = generate_virtual_address_dict(f5, regex) if 'address_class' in include: facts['address_class'] = generate_address_class_dict(f5, regex) if 'software' in include: facts['software'] = generate_software_list(f5) if 'certificate' in include: facts['certificate'] = generate_certificate_dict(f5, regex) if 'key' in include: facts['key'] = generate_key_dict(f5, regex) if 'client_ssl_profile' in include: facts['client_ssl_profile'] = generate_client_ssl_profile_dict(f5, regex) if 'system_info' in include: facts['system_info'] = generate_system_info_dict(f5) # restore saved state if saved_active_folder and saved_active_folder != "/": f5.set_active_folder(saved_active_folder) if saved_recursive_query_state and \ saved_recursive_query_state != "STATE_ENABLED": f5.set_recursive_query_state(saved_recursive_query_state) result = dict( ansible_facts=facts, ) result.update(**facts) except Exception as e: module.fail_json(msg="received exception: %s\ntraceback: %s" % (e, traceback.format_exc())) module.exit_json(**result) if __name__ == '__main__': main() Fixes: #871 #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # Copyright (c) 2013 Matt Hite <mhite@hotmail.com> # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: bigip_facts short_description: Collect facts from F5 BIG-IP devices description: - Collect facts from F5 BIG-IP devices via iControl SOAP API version_added: 1.6 author: - Matt Hite (@mhite) - Tim Rupp (@caphrim007) notes: - Requires BIG-IP software version >= 11.4 - F5 developed module 'bigsuds' required (see http://devcentral.f5.com) - Best run as a local_action in your playbook - Tested with manager and above account privilege level - C(provision) facts were added in 2.2 - This module is deprecated. Use the C(bigip_device_facts) module instead. requirements: - bigsuds options: session: description: - BIG-IP session support; may be useful to avoid concurrency issues in certain circumstances. default: no type: bool include: description: - Fact category or list of categories to collect required: True choices: - address_class - certificate - client_ssl_profile - device - device_group - interface - key - node - pool - provision - rule - self_ip - software - system_info - traffic_group - trunk - virtual_address - virtual_server - vlan filter: description: - Shell-style glob matching string used to filter fact keys. Not applicable for software, provision, and system_info fact categories. extends_documentation_fragment: f5 ''' EXAMPLES = r''' - name: Collect BIG-IP facts bigip_facts: server: lb.mydomain.com user: admin password: secret include: - interface - vlan delegate_to: localhost ''' import fnmatch import re import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import string_types from ansible.module_utils.six.moves import map, zip try: from library.module_utils.network.f5.legacy import bigip_api, bigsuds_found from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.common import F5BaseClient except ImportError: from ansible.module_utils.network.f5.legacy import bigip_api, bigsuds_found from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.common import F5BaseClient try: from suds import MethodNotFound, WebFault except ImportError: pass # Handle via f5_utils.bigsuds_found class F5(object): """F5 iControl class. F5 BIG-IP iControl API class. Attributes: api: iControl API instance. """ def __init__(self, host, user, password, session=False, validate_certs=True, port=443): self.api = bigip_api(host, user, password, validate_certs, port) if session: self.start_session() def start_session(self): self.api = self.api.with_session_id() def get_api(self): return self.api def set_recursive_query_state(self, state): self.api.System.Session.set_recursive_query_state(state) def get_recursive_query_state(self): return self.api.System.Session.get_recursive_query_state() def enable_recursive_query_state(self): self.set_recursive_query_state('STATE_ENABLED') def disable_recursive_query_state(self): self.set_recursive_query_state('STATE_DISABLED') def set_active_folder(self, folder): self.api.System.Session.set_active_folder(folder=folder) def get_active_folder(self): return self.api.System.Session.get_active_folder() class Interfaces(object): """Interfaces class. F5 BIG-IP interfaces class. Attributes: api: iControl API instance. interfaces: A list of BIG-IP interface names. """ def __init__(self, api, regex=None): self.api = api self.interfaces = api.Networking.Interfaces.get_list() if regex: re_filter = re.compile(regex) self.interfaces = filter(re_filter.search, self.interfaces) def get_list(self): return self.interfaces def get_active_media(self): return self.api.Networking.Interfaces.get_active_media(self.interfaces) def get_actual_flow_control(self): return self.api.Networking.Interfaces.get_actual_flow_control(self.interfaces) def get_bundle_state(self): return self.api.Networking.Interfaces.get_bundle_state(self.interfaces) def get_description(self): return self.api.Networking.Interfaces.get_description(self.interfaces) def get_dual_media_state(self): return self.api.Networking.Interfaces.get_dual_media_state(self.interfaces) def get_enabled_state(self): return self.api.Networking.Interfaces.get_enabled_state(self.interfaces) def get_if_index(self): return self.api.Networking.Interfaces.get_if_index(self.interfaces) def get_learning_mode(self): return self.api.Networking.Interfaces.get_learning_mode(self.interfaces) def get_lldp_admin_status(self): return self.api.Networking.Interfaces.get_lldp_admin_status(self.interfaces) def get_lldp_tlvmap(self): return self.api.Networking.Interfaces.get_lldp_tlvmap(self.interfaces) def get_mac_address(self): return self.api.Networking.Interfaces.get_mac_address(self.interfaces) def get_media(self): return self.api.Networking.Interfaces.get_media(self.interfaces) def get_media_option(self): return self.api.Networking.Interfaces.get_media_option(self.interfaces) def get_media_option_sfp(self): return self.api.Networking.Interfaces.get_media_option_sfp(self.interfaces) def get_media_sfp(self): return self.api.Networking.Interfaces.get_media_sfp(self.interfaces) def get_media_speed(self): return self.api.Networking.Interfaces.get_media_speed(self.interfaces) def get_media_status(self): return self.api.Networking.Interfaces.get_media_status(self.interfaces) def get_mtu(self): return self.api.Networking.Interfaces.get_mtu(self.interfaces) def get_phy_master_slave_mode(self): return self.api.Networking.Interfaces.get_phy_master_slave_mode(self.interfaces) def get_prefer_sfp_state(self): return self.api.Networking.Interfaces.get_prefer_sfp_state(self.interfaces) def get_flow_control(self): return self.api.Networking.Interfaces.get_requested_flow_control(self.interfaces) def get_sflow_poll_interval(self): return self.api.Networking.Interfaces.get_sflow_poll_interval(self.interfaces) def get_sflow_poll_interval_global(self): return self.api.Networking.Interfaces.get_sflow_poll_interval_global(self.interfaces) def get_sfp_media_state(self): return self.api.Networking.Interfaces.get_sfp_media_state(self.interfaces) def get_stp_active_edge_port_state(self): return self.api.Networking.Interfaces.get_stp_active_edge_port_state(self.interfaces) def get_stp_enabled_state(self): return self.api.Networking.Interfaces.get_stp_enabled_state(self.interfaces) def get_stp_link_type(self): return self.api.Networking.Interfaces.get_stp_link_type(self.interfaces) def get_stp_protocol_detection_reset_state(self): return self.api.Networking.Interfaces.get_stp_protocol_detection_reset_state(self.interfaces) class SelfIPs(object): """Self IPs class. F5 BIG-IP Self IPs class. Attributes: api: iControl API instance. self_ips: List of self IPs. """ def __init__(self, api, regex=None): self.api = api self.self_ips = api.Networking.SelfIPV2.get_list() if regex: re_filter = re.compile(regex) self.self_ips = filter(re_filter.search, self.self_ips) def get_list(self): return self.self_ips def get_address(self): return self.api.Networking.SelfIPV2.get_address(self.self_ips) def get_allow_access_list(self): return self.api.Networking.SelfIPV2.get_allow_access_list(self.self_ips) def get_description(self): return self.api.Networking.SelfIPV2.get_description(self.self_ips) def get_enforced_firewall_policy(self): return self.api.Networking.SelfIPV2.get_enforced_firewall_policy(self.self_ips) def get_floating_state(self): return self.api.Networking.SelfIPV2.get_floating_state(self.self_ips) def get_fw_rule(self): return self.api.Networking.SelfIPV2.get_fw_rule(self.self_ips) def get_netmask(self): return self.api.Networking.SelfIPV2.get_netmask(self.self_ips) def get_staged_firewall_policy(self): return self.api.Networking.SelfIPV2.get_staged_firewall_policy(self.self_ips) def get_traffic_group(self): return self.api.Networking.SelfIPV2.get_traffic_group(self.self_ips) def get_vlan(self): return self.api.Networking.SelfIPV2.get_vlan(self.self_ips) def get_is_traffic_group_inherited(self): return self.api.Networking.SelfIPV2.is_traffic_group_inherited(self.self_ips) class Trunks(object): """Trunks class. F5 BIG-IP trunks class. Attributes: api: iControl API instance. trunks: List of trunks. """ def __init__(self, api, regex=None): self.api = api self.trunks = api.Networking.Trunk.get_list() if regex: re_filter = re.compile(regex) self.trunks = filter(re_filter.search, self.trunks) def get_list(self): return self.trunks def get_active_lacp_state(self): return self.api.Networking.Trunk.get_active_lacp_state(self.trunks) def get_configured_member_count(self): return self.api.Networking.Trunk.get_configured_member_count(self.trunks) def get_description(self): return self.api.Networking.Trunk.get_description(self.trunks) def get_distribution_hash_option(self): return self.api.Networking.Trunk.get_distribution_hash_option(self.trunks) def get_interface(self): return self.api.Networking.Trunk.get_interface(self.trunks) def get_lacp_enabled_state(self): return self.api.Networking.Trunk.get_lacp_enabled_state(self.trunks) def get_lacp_timeout_option(self): return self.api.Networking.Trunk.get_lacp_timeout_option(self.trunks) def get_link_selection_policy(self): return self.api.Networking.Trunk.get_link_selection_policy(self.trunks) def get_media_speed(self): return self.api.Networking.Trunk.get_media_speed(self.trunks) def get_media_status(self): return self.api.Networking.Trunk.get_media_status(self.trunks) def get_operational_member_count(self): return self.api.Networking.Trunk.get_operational_member_count(self.trunks) def get_stp_enabled_state(self): return self.api.Networking.Trunk.get_stp_enabled_state(self.trunks) def get_stp_protocol_detection_reset_state(self): return self.api.Networking.Trunk.get_stp_protocol_detection_reset_state(self.trunks) class Vlans(object): """Vlans class. F5 BIG-IP Vlans class. Attributes: api: iControl API instance. vlans: List of VLANs. """ def __init__(self, api, regex=None): self.api = api self.vlans = api.Networking.VLAN.get_list() if regex: re_filter = re.compile(regex) self.vlans = filter(re_filter.search, self.vlans) def get_list(self): return self.vlans def get_auto_lasthop(self): return self.api.Networking.VLAN.get_auto_lasthop(self.vlans) def get_cmp_hash_algorithm(self): return self.api.Networking.VLAN.get_cmp_hash_algorithm(self.vlans) def get_description(self): return self.api.Networking.VLAN.get_description(self.vlans) def get_dynamic_forwarding(self): return self.api.Networking.VLAN.get_dynamic_forwarding(self.vlans) def get_failsafe_action(self): return self.api.Networking.VLAN.get_failsafe_action(self.vlans) def get_failsafe_state(self): return self.api.Networking.VLAN.get_failsafe_state(self.vlans) def get_failsafe_timeout(self): return self.api.Networking.VLAN.get_failsafe_timeout(self.vlans) def get_if_index(self): return self.api.Networking.VLAN.get_if_index(self.vlans) def get_learning_mode(self): return self.api.Networking.VLAN.get_learning_mode(self.vlans) def get_mac_masquerade_address(self): return self.api.Networking.VLAN.get_mac_masquerade_address(self.vlans) def get_member(self): return self.api.Networking.VLAN.get_member(self.vlans) def get_mtu(self): return self.api.Networking.VLAN.get_mtu(self.vlans) def get_sflow_poll_interval(self): return self.api.Networking.VLAN.get_sflow_poll_interval(self.vlans) def get_sflow_poll_interval_global(self): return self.api.Networking.VLAN.get_sflow_poll_interval_global(self.vlans) def get_sflow_sampling_rate(self): return self.api.Networking.VLAN.get_sflow_sampling_rate(self.vlans) def get_sflow_sampling_rate_global(self): return self.api.Networking.VLAN.get_sflow_sampling_rate_global(self.vlans) def get_source_check_state(self): return self.api.Networking.VLAN.get_source_check_state(self.vlans) def get_true_mac_address(self): return self.api.Networking.VLAN.get_true_mac_address(self.vlans) def get_vlan_id(self): return self.api.Networking.VLAN.get_vlan_id(self.vlans) class Software(object): """Software class. F5 BIG-IP software class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_all_software_status(self): return self.api.System.SoftwareManagement.get_all_software_status() class VirtualServers(object): """Virtual servers class. F5 BIG-IP virtual servers class. Attributes: api: iControl API instance. virtual_servers: List of virtual servers. """ def __init__(self, api, regex=None): self.api = api self.virtual_servers = api.LocalLB.VirtualServer.get_list() if regex: re_filter = re.compile(regex) self.virtual_servers = filter(re_filter.search, self.virtual_servers) def get_list(self): return self.virtual_servers def get_name(self): return [x[x.rfind('/') + 1:] for x in self.virtual_servers] def get_actual_hardware_acceleration(self): return self.api.LocalLB.VirtualServer.get_actual_hardware_acceleration(self.virtual_servers) def get_authentication_profile(self): return self.api.LocalLB.VirtualServer.get_authentication_profile(self.virtual_servers) def get_auto_lasthop(self): return self.api.LocalLB.VirtualServer.get_auto_lasthop(self.virtual_servers) def get_bw_controller_policy(self): return self.api.LocalLB.VirtualServer.get_bw_controller_policy(self.virtual_servers) def get_clone_pool(self): return self.api.LocalLB.VirtualServer.get_clone_pool(self.virtual_servers) def get_cmp_enable_mode(self): return self.api.LocalLB.VirtualServer.get_cmp_enable_mode(self.virtual_servers) def get_connection_limit(self): return self.api.LocalLB.VirtualServer.get_connection_limit(self.virtual_servers) def get_connection_mirror_state(self): return self.api.LocalLB.VirtualServer.get_connection_mirror_state(self.virtual_servers) def get_default_pool_name(self): return self.api.LocalLB.VirtualServer.get_default_pool_name(self.virtual_servers) def get_description(self): return self.api.LocalLB.VirtualServer.get_description(self.virtual_servers) def get_destination(self): return self.api.LocalLB.VirtualServer.get_destination_v2(self.virtual_servers) def get_enabled_state(self): return self.api.LocalLB.VirtualServer.get_enabled_state(self.virtual_servers) def get_enforced_firewall_policy(self): return self.api.LocalLB.VirtualServer.get_enforced_firewall_policy(self.virtual_servers) def get_fallback_persistence_profile(self): return self.api.LocalLB.VirtualServer.get_fallback_persistence_profile(self.virtual_servers) def get_fw_rule(self): return self.api.LocalLB.VirtualServer.get_fw_rule(self.virtual_servers) def get_gtm_score(self): return self.api.LocalLB.VirtualServer.get_gtm_score(self.virtual_servers) def get_last_hop_pool(self): return self.api.LocalLB.VirtualServer.get_last_hop_pool(self.virtual_servers) def get_nat64_state(self): return self.api.LocalLB.VirtualServer.get_nat64_state(self.virtual_servers) def get_object_status(self): return self.api.LocalLB.VirtualServer.get_object_status(self.virtual_servers) def get_persistence_profile(self): return self.api.LocalLB.VirtualServer.get_persistence_profile(self.virtual_servers) def get_profile(self): return self.api.LocalLB.VirtualServer.get_profile(self.virtual_servers) def get_protocol(self): return self.api.LocalLB.VirtualServer.get_protocol(self.virtual_servers) def get_rate_class(self): return self.api.LocalLB.VirtualServer.get_rate_class(self.virtual_servers) def get_rate_limit(self): return self.api.LocalLB.VirtualServer.get_rate_limit(self.virtual_servers) def get_rate_limit_destination_mask(self): return self.api.LocalLB.VirtualServer.get_rate_limit_destination_mask(self.virtual_servers) def get_rate_limit_mode(self): return self.api.LocalLB.VirtualServer.get_rate_limit_mode(self.virtual_servers) def get_rate_limit_source_mask(self): return self.api.LocalLB.VirtualServer.get_rate_limit_source_mask(self.virtual_servers) def get_related_rule(self): return self.api.LocalLB.VirtualServer.get_related_rule(self.virtual_servers) def get_rule(self): return self.api.LocalLB.VirtualServer.get_rule(self.virtual_servers) def get_security_log_profile(self): return self.api.LocalLB.VirtualServer.get_security_log_profile(self.virtual_servers) def get_snat_pool(self): return self.api.LocalLB.VirtualServer.get_snat_pool(self.virtual_servers) def get_snat_type(self): return self.api.LocalLB.VirtualServer.get_snat_type(self.virtual_servers) def get_source_address(self): return self.api.LocalLB.VirtualServer.get_source_address(self.virtual_servers) def get_source_address_translation_lsn_pool(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_lsn_pool(self.virtual_servers) def get_source_address_translation_snat_pool(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_snat_pool(self.virtual_servers) def get_source_address_translation_type(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_type(self.virtual_servers) def get_source_port_behavior(self): return self.api.LocalLB.VirtualServer.get_source_port_behavior(self.virtual_servers) def get_staged_firewall_policy(self): return self.api.LocalLB.VirtualServer.get_staged_firewall_policy(self.virtual_servers) def get_translate_address_state(self): return self.api.LocalLB.VirtualServer.get_translate_address_state(self.virtual_servers) def get_translate_port_state(self): return self.api.LocalLB.VirtualServer.get_translate_port_state(self.virtual_servers) def get_type(self): return self.api.LocalLB.VirtualServer.get_type(self.virtual_servers) def get_vlan(self): return self.api.LocalLB.VirtualServer.get_vlan(self.virtual_servers) def get_wildmask(self): return self.api.LocalLB.VirtualServer.get_wildmask(self.virtual_servers) class Pools(object): """Pools class. F5 BIG-IP pools class. Attributes: api: iControl API instance. pool_names: List of pool names. """ def __init__(self, api, regex=None): self.api = api self.pool_names = api.LocalLB.Pool.get_list() if regex: re_filter = re.compile(regex) self.pool_names = filter(re_filter.search, self.pool_names) def get_list(self): return self.pool_names def get_name(self): return [x[x.rfind('/') + 1:] for x in self.pool_names] def get_action_on_service_down(self): return self.api.LocalLB.Pool.get_action_on_service_down(self.pool_names) def get_active_member_count(self): return self.api.LocalLB.Pool.get_active_member_count(self.pool_names) def get_aggregate_dynamic_ratio(self): return self.api.LocalLB.Pool.get_aggregate_dynamic_ratio(self.pool_names) def get_allow_nat_state(self): return self.api.LocalLB.Pool.get_allow_nat_state(self.pool_names) def get_allow_snat_state(self): return self.api.LocalLB.Pool.get_allow_snat_state(self.pool_names) def get_client_ip_tos(self): return self.api.LocalLB.Pool.get_client_ip_tos(self.pool_names) def get_client_link_qos(self): return self.api.LocalLB.Pool.get_client_link_qos(self.pool_names) def get_description(self): return self.api.LocalLB.Pool.get_description(self.pool_names) def get_gateway_failsafe_device(self): return self.api.LocalLB.Pool.get_gateway_failsafe_device(self.pool_names) def get_ignore_persisted_weight_state(self): return self.api.LocalLB.Pool.get_ignore_persisted_weight_state(self.pool_names) def get_lb_method(self): result = [] lb_choice = dict( LB_METHOD_DYNAMIC_RATIO_MEMBER='dynamic-ratio-member', LB_METHOD_DYNAMIC_RATIO='dynamic-ratio-node', LB_METHOD_FASTEST_APP_RESPONSE='fastest-app-response', LB_METHOD_FASTEST_NODE_ADDRESS='fastest-node', LB_METHOD_LEAST_CONNECTION_MEMBER='least-connections-member', LB_METHOD_LEAST_CONNECTION_NODE_ADDRESS='least-connections-node', LB_METHOD_LEAST_SESSIONS='least-sessions', LB_METHOD_OBSERVED_MEMBER='observed-member', LB_METHOD_OBSERVED_NODE_ADDRESS='observed-node', LB_METHOD_PREDICTIVE_MEMBER='predictive-member', LB_METHOD_PREDICTIVE_NODE_ADDRESS='predictive-node', LB_METHOD_RATIO_LEAST_CONNECTION_MEMBER='ratio-least-connections-member', LB_METHOD_RATIO_LEAST_CONNECTION_NODE_ADDRESS='ratio-least-connections-node', LB_METHOD_RATIO_MEMBER='ratio-member', LB_METHOD_RATIO_NODE_ADDRESS='ratio-node', LB_METHOD_RATIO_SESSION='ratio-session', LB_METHOD_ROUND_ROBIN='round-robin', LB_METHOD_WEIGHTED_LEAST_CONNECTION_MEMBER='weighted-least-connections-member', LB_METHOD_WEIGHTED_LEAST_CONNECTION_NODE_ADDRESS='weighted-least-connections-node' ) methods = self.api.LocalLB.Pool.get_lb_method(self.pool_names) for method in methods: result.append(lb_choice.get(method, method)) return result def get_member(self): return self.api.LocalLB.Pool.get_member_v2(self.pool_names) def get_minimum_active_member(self): return self.api.LocalLB.Pool.get_minimum_active_member(self.pool_names) def get_minimum_up_member(self): return self.api.LocalLB.Pool.get_minimum_up_member(self.pool_names) def get_minimum_up_member_action(self): return self.api.LocalLB.Pool.get_minimum_up_member_action(self.pool_names) def get_minimum_up_member_enabled_state(self): return self.api.LocalLB.Pool.get_minimum_up_member_enabled_state(self.pool_names) def get_monitor_association(self): return self.api.LocalLB.Pool.get_monitor_association(self.pool_names) def get_monitor_instance(self): return self.api.LocalLB.Pool.get_monitor_instance(self.pool_names) def get_object_status(self): return self.api.LocalLB.Pool.get_object_status(self.pool_names) def get_profile(self): return self.api.LocalLB.Pool.get_profile(self.pool_names) def get_queue_depth_limit(self): return self.api.LocalLB.Pool.get_queue_depth_limit(self.pool_names) def get_queue_on_connection_limit_state(self): return self.api.LocalLB.Pool.get_queue_on_connection_limit_state(self.pool_names) def get_queue_time_limit(self): return self.api.LocalLB.Pool.get_queue_time_limit(self.pool_names) def get_reselect_tries(self): return self.api.LocalLB.Pool.get_reselect_tries(self.pool_names) def get_server_ip_tos(self): return self.api.LocalLB.Pool.get_server_ip_tos(self.pool_names) def get_server_link_qos(self): return self.api.LocalLB.Pool.get_server_link_qos(self.pool_names) def get_simple_timeout(self): return self.api.LocalLB.Pool.get_simple_timeout(self.pool_names) def get_slow_ramp_time(self): return self.api.LocalLB.Pool.get_slow_ramp_time(self.pool_names) class Devices(object): """Devices class. F5 BIG-IP devices class. Attributes: api: iControl API instance. devices: List of devices. """ def __init__(self, api, regex=None): self.api = api self.devices = api.Management.Device.get_list() if regex: re_filter = re.compile(regex) self.devices = filter(re_filter.search, self.devices) def get_list(self): return self.devices def get_active_modules(self): return self.api.Management.Device.get_active_modules(self.devices) def get_base_mac_address(self): return self.api.Management.Device.get_base_mac_address(self.devices) def get_blade_addresses(self): return self.api.Management.Device.get_blade_addresses(self.devices) def get_build(self): return self.api.Management.Device.get_build(self.devices) def get_chassis_id(self): return self.api.Management.Device.get_chassis_id(self.devices) def get_chassis_type(self): return self.api.Management.Device.get_chassis_type(self.devices) def get_comment(self): return self.api.Management.Device.get_comment(self.devices) def get_configsync_address(self): return self.api.Management.Device.get_configsync_address(self.devices) def get_contact(self): return self.api.Management.Device.get_contact(self.devices) def get_description(self): return self.api.Management.Device.get_description(self.devices) def get_edition(self): return self.api.Management.Device.get_edition(self.devices) def get_failover_state(self): return self.api.Management.Device.get_failover_state(self.devices) def get_local_device(self): return self.api.Management.Device.get_local_device() def get_hostname(self): return self.api.Management.Device.get_hostname(self.devices) def get_inactive_modules(self): return self.api.Management.Device.get_inactive_modules(self.devices) def get_location(self): return self.api.Management.Device.get_location(self.devices) def get_management_address(self): return self.api.Management.Device.get_management_address(self.devices) def get_marketing_name(self): return self.api.Management.Device.get_marketing_name(self.devices) def get_multicast_address(self): return self.api.Management.Device.get_multicast_address(self.devices) def get_optional_modules(self): return self.api.Management.Device.get_optional_modules(self.devices) def get_platform_id(self): return self.api.Management.Device.get_platform_id(self.devices) def get_primary_mirror_address(self): return self.api.Management.Device.get_primary_mirror_address(self.devices) def get_product(self): return self.api.Management.Device.get_product(self.devices) def get_secondary_mirror_address(self): return self.api.Management.Device.get_secondary_mirror_address(self.devices) def get_software_version(self): return self.api.Management.Device.get_software_version(self.devices) def get_timelimited_modules(self): return self.api.Management.Device.get_timelimited_modules(self.devices) def get_timezone(self): return self.api.Management.Device.get_timezone(self.devices) def get_unicast_addresses(self): return self.api.Management.Device.get_unicast_addresses(self.devices) class DeviceGroups(object): """Device groups class. F5 BIG-IP device groups class. Attributes: api: iControl API instance. device_groups: List of device groups. """ def __init__(self, api, regex=None): self.api = api self.device_groups = api.Management.DeviceGroup.get_list() if regex: re_filter = re.compile(regex) self.device_groups = filter(re_filter.search, self.device_groups) def get_list(self): return self.device_groups def get_all_preferred_active(self): return self.api.Management.DeviceGroup.get_all_preferred_active(self.device_groups) def get_autosync_enabled_state(self): return self.api.Management.DeviceGroup.get_autosync_enabled_state(self.device_groups) def get_description(self): return self.api.Management.DeviceGroup.get_description(self.device_groups) def get_device(self): return self.api.Management.DeviceGroup.get_device(self.device_groups) def get_full_load_on_sync_state(self): return self.api.Management.DeviceGroup.get_full_load_on_sync_state(self.device_groups) def get_incremental_config_sync_size_maximum(self): return self.api.Management.DeviceGroup.get_incremental_config_sync_size_maximum(self.device_groups) def get_network_failover_enabled_state(self): return self.api.Management.DeviceGroup.get_network_failover_enabled_state(self.device_groups) def get_sync_status(self): return self.api.Management.DeviceGroup.get_sync_status(self.device_groups) def get_type(self): return self.api.Management.DeviceGroup.get_type(self.device_groups) class TrafficGroups(object): """Traffic groups class. F5 BIG-IP traffic groups class. Attributes: api: iControl API instance. traffic_groups: List of traffic groups. """ def __init__(self, api, regex=None): self.api = api self.traffic_groups = api.Management.TrafficGroup.get_list() if regex: re_filter = re.compile(regex) self.traffic_groups = filter(re_filter.search, self.traffic_groups) def get_list(self): return self.traffic_groups def get_auto_failback_enabled_state(self): return self.api.Management.TrafficGroup.get_auto_failback_enabled_state(self.traffic_groups) def get_auto_failback_time(self): return self.api.Management.TrafficGroup.get_auto_failback_time(self.traffic_groups) def get_default_device(self): return self.api.Management.TrafficGroup.get_default_device(self.traffic_groups) def get_description(self): return self.api.Management.TrafficGroup.get_description(self.traffic_groups) def get_ha_load_factor(self): return self.api.Management.TrafficGroup.get_ha_load_factor(self.traffic_groups) def get_ha_order(self): return self.api.Management.TrafficGroup.get_ha_order(self.traffic_groups) def get_is_floating(self): return self.api.Management.TrafficGroup.get_is_floating(self.traffic_groups) def get_mac_masquerade_address(self): return self.api.Management.TrafficGroup.get_mac_masquerade_address(self.traffic_groups) def get_unit_id(self): return self.api.Management.TrafficGroup.get_unit_id(self.traffic_groups) class Rules(object): """Rules class. F5 BIG-IP iRules class. Attributes: api: iControl API instance. rules: List of iRules. """ def __init__(self, api, regex=None): self.api = api self.rules = api.LocalLB.Rule.get_list() if regex: re_filter = re.compile(regex) self.traffic_groups = filter(re_filter.search, self.rules) def get_list(self): return self.rules def get_description(self): return self.api.LocalLB.Rule.get_description(rule_names=self.rules) def get_ignore_vertification(self): return self.api.LocalLB.Rule.get_ignore_vertification(rule_names=self.rules) def get_verification_status(self): return self.api.LocalLB.Rule.get_verification_status_v2(rule_names=self.rules) def get_definition(self): return [x['rule_definition'] for x in self.api.LocalLB.Rule.query_rule(rule_names=self.rules)] class Nodes(object): """Nodes class. F5 BIG-IP nodes class. Attributes: api: iControl API instance. nodes: List of nodes. """ def __init__(self, api, regex=None): self.api = api self.nodes = api.LocalLB.NodeAddressV2.get_list() if regex: re_filter = re.compile(regex) self.nodes = filter(re_filter.search, self.nodes) def get_list(self): return self.nodes def get_address(self): return self.api.LocalLB.NodeAddressV2.get_address(nodes=self.nodes) def get_name(self): return [x[x.rfind('/') + 1:] for x in self.nodes] def get_connection_limit(self): return self.api.LocalLB.NodeAddressV2.get_connection_limit(nodes=self.nodes) def get_description(self): return self.api.LocalLB.NodeAddressV2.get_description(nodes=self.nodes) def get_dynamic_ratio(self): return self.api.LocalLB.NodeAddressV2.get_dynamic_ratio_v2(nodes=self.nodes) def get_monitor_instance(self): return self.api.LocalLB.NodeAddressV2.get_monitor_instance(nodes=self.nodes) def get_monitor_rule(self): return self.api.LocalLB.NodeAddressV2.get_monitor_rule(nodes=self.nodes) def get_monitor_status(self): return self.api.LocalLB.NodeAddressV2.get_monitor_status(nodes=self.nodes) def get_object_status(self): return self.api.LocalLB.NodeAddressV2.get_object_status(nodes=self.nodes) def get_rate_limit(self): return self.api.LocalLB.NodeAddressV2.get_rate_limit(nodes=self.nodes) def get_ratio(self): return self.api.LocalLB.NodeAddressV2.get_ratio(nodes=self.nodes) def get_session_status(self): return self.api.LocalLB.NodeAddressV2.get_session_status(nodes=self.nodes) class VirtualAddresses(object): """Virtual addresses class. F5 BIG-IP virtual addresses class. Attributes: api: iControl API instance. virtual_addresses: List of virtual addresses. """ def __init__(self, api, regex=None): self.api = api self.virtual_addresses = api.LocalLB.VirtualAddressV2.get_list() if regex: re_filter = re.compile(regex) self.virtual_addresses = filter(re_filter.search, self.virtual_addresses) def get_list(self): return self.virtual_addresses def get_address(self): return self.api.LocalLB.VirtualAddressV2.get_address(self.virtual_addresses) def get_arp_state(self): return self.api.LocalLB.VirtualAddressV2.get_arp_state(self.virtual_addresses) def get_auto_delete_state(self): return self.api.LocalLB.VirtualAddressV2.get_auto_delete_state(self.virtual_addresses) def get_connection_limit(self): return self.api.LocalLB.VirtualAddressV2.get_connection_limit(self.virtual_addresses) def get_description(self): return self.api.LocalLB.VirtualAddressV2.get_description(self.virtual_addresses) def get_enabled_state(self): return self.api.LocalLB.VirtualAddressV2.get_enabled_state(self.virtual_addresses) def get_icmp_echo_state(self): return self.api.LocalLB.VirtualAddressV2.get_icmp_echo_state(self.virtual_addresses) def get_is_floating_state(self): return self.api.LocalLB.VirtualAddressV2.get_is_floating_state(self.virtual_addresses) def get_netmask(self): return self.api.LocalLB.VirtualAddressV2.get_netmask(self.virtual_addresses) def get_object_status(self): return self.api.LocalLB.VirtualAddressV2.get_object_status(self.virtual_addresses) def get_route_advertisement_state(self): return self.api.LocalLB.VirtualAddressV2.get_route_advertisement_state(self.virtual_addresses) def get_traffic_group(self): return self.api.LocalLB.VirtualAddressV2.get_traffic_group(self.virtual_addresses) class AddressClasses(object): """Address group/class class. F5 BIG-IP address group/class class. In TMUI these things are known as Address Data Groups. Examples that ship with the box include /Common/aol and /Common/private_net Attributes: api: iControl API instance. address_classes: List of address classes. """ def __init__(self, api, regex=None): self.api = api self.address_classes = api.LocalLB.Class.get_address_class_list() if regex: re_filter = re.compile(regex) self.address_classes = filter(re_filter.search, self.address_classes) def get_list(self): return self.address_classes def get_address_class(self): key = self.api.LocalLB.Class.get_address_class(self.address_classes) value = self.api.LocalLB.Class.get_address_class_member_data_value(key) result = [] for idx, v in enumerate(key): for idx2, member in enumerate(v['members']): dg_value = dict( value=value[idx][idx2] ) dg_value.update(member) result.append(dg_value) return result def get_description(self): return self.api.LocalLB.Class.get_description(self.address_classes) class Certificates(object): """Certificates class. F5 BIG-IP certificates class. Attributes: api: iControl API instance. certificates: List of certificate identifiers. certificate_list: List of certificate information structures. """ def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"): self.api = api self.certificate_list = api.Management.KeyCertificate.get_certificate_list(mode=mode) self.certificates = [x['certificate']['cert_info']['id'] for x in self.certificate_list] if regex: re_filter = re.compile(regex) self.certificates = filter(re_filter.search, self.certificates) self.certificate_list = [x for x in self.certificate_list if x['certificate']['cert_info']['id'] in self.certificates] def get_list(self): return self.certificates def get_certificate_list(self): return self.certificate_list class Keys(object): """Keys class. F5 BIG-IP keys class. Attributes: api: iControl API instance. keys: List of key identifiers. key_list: List of key information structures. """ def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"): self.api = api self.key_list = api.Management.KeyCertificate.get_key_list(mode=mode) self.keys = [x['key_info']['id'] for x in self.key_list] if regex: re_filter = re.compile(regex) self.keys = filter(re_filter.search, self.keys) self.key_list = [x for x in self.key_list if x['key_info']['id'] in self.keys] def get_list(self): return self.keys def get_key_list(self): return self.key_list class ProfileClientSSL(object): """Client SSL profiles class. F5 BIG-IP client SSL profiles class. Attributes: api: iControl API instance. profiles: List of client SSL profiles. """ def __init__(self, api, regex=None): self.api = api self.profiles = api.LocalLB.ProfileClientSSL.get_list() if regex: re_filter = re.compile(regex) self.profiles = filter(re_filter.search, self.profiles) def get_list(self): return self.profiles def get_alert_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_alert_timeout(self.profiles) def get_allow_nonssl_state(self): return self.api.LocalLB.ProfileClientSSL.get_allow_nonssl_state(self.profiles) def get_authenticate_depth(self): return self.api.LocalLB.ProfileClientSSL.get_authenticate_depth(self.profiles) def get_authenticate_once_state(self): return self.api.LocalLB.ProfileClientSSL.get_authenticate_once_state(self.profiles) def get_ca_file(self): return self.api.LocalLB.ProfileClientSSL.get_ca_file_v2(self.profiles) def get_cache_size(self): return self.api.LocalLB.ProfileClientSSL.get_cache_size(self.profiles) def get_cache_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_cache_timeout(self.profiles) def get_certificate_file(self): return self.api.LocalLB.ProfileClientSSL.get_certificate_file_v2(self.profiles) def get_chain_file(self): return self.api.LocalLB.ProfileClientSSL.get_chain_file_v2(self.profiles) def get_cipher_list(self): return self.api.LocalLB.ProfileClientSSL.get_cipher_list(self.profiles) def get_client_certificate_ca_file(self): return self.api.LocalLB.ProfileClientSSL.get_client_certificate_ca_file_v2(self.profiles) def get_crl_file(self): return self.api.LocalLB.ProfileClientSSL.get_crl_file_v2(self.profiles) def get_default_profile(self): return self.api.LocalLB.ProfileClientSSL.get_default_profile(self.profiles) def get_description(self): return self.api.LocalLB.ProfileClientSSL.get_description(self.profiles) def get_forward_proxy_ca_certificate_file(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_certificate_file(self.profiles) def get_forward_proxy_ca_key_file(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_key_file(self.profiles) def get_forward_proxy_ca_passphrase(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_passphrase(self.profiles) def get_forward_proxy_certificate_extension_include(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_extension_include(self.profiles) def get_forward_proxy_certificate_lifespan(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_lifespan(self.profiles) def get_forward_proxy_enabled_state(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_enabled_state(self.profiles) def get_forward_proxy_lookup_by_ipaddr_port_state(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_lookup_by_ipaddr_port_state(self.profiles) def get_handshake_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_handshake_timeout(self.profiles) def get_key_file(self): return self.api.LocalLB.ProfileClientSSL.get_key_file_v2(self.profiles) def get_modssl_emulation_state(self): return self.api.LocalLB.ProfileClientSSL.get_modssl_emulation_state(self.profiles) def get_passphrase(self): return self.api.LocalLB.ProfileClientSSL.get_passphrase(self.profiles) def get_peer_certification_mode(self): return self.api.LocalLB.ProfileClientSSL.get_peer_certification_mode(self.profiles) def get_profile_mode(self): return self.api.LocalLB.ProfileClientSSL.get_profile_mode(self.profiles) def get_renegotiation_maximum_record_delay(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_maximum_record_delay(self.profiles) def get_renegotiation_period(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_period(self.profiles) def get_renegotiation_state(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_state(self.profiles) def get_renegotiation_throughput(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_throughput(self.profiles) def get_retain_certificate_state(self): return self.api.LocalLB.ProfileClientSSL.get_retain_certificate_state(self.profiles) def get_secure_renegotiation_mode(self): return self.api.LocalLB.ProfileClientSSL.get_secure_renegotiation_mode(self.profiles) def get_server_name(self): return self.api.LocalLB.ProfileClientSSL.get_server_name(self.profiles) def get_session_ticket_state(self): return self.api.LocalLB.ProfileClientSSL.get_session_ticket_state(self.profiles) def get_sni_default_state(self): return self.api.LocalLB.ProfileClientSSL.get_sni_default_state(self.profiles) def get_sni_require_state(self): return self.api.LocalLB.ProfileClientSSL.get_sni_require_state(self.profiles) def get_ssl_option(self): return self.api.LocalLB.ProfileClientSSL.get_ssl_option(self.profiles) def get_strict_resume_state(self): return self.api.LocalLB.ProfileClientSSL.get_strict_resume_state(self.profiles) def get_unclean_shutdown_state(self): return self.api.LocalLB.ProfileClientSSL.get_unclean_shutdown_state(self.profiles) def get_is_base_profile(self): return self.api.LocalLB.ProfileClientSSL.is_base_profile(self.profiles) def get_is_system_profile(self): return self.api.LocalLB.ProfileClientSSL.is_system_profile(self.profiles) class SystemInfo(object): """System information class. F5 BIG-IP system information class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_base_mac_address(self): return self.api.System.SystemInfo.get_base_mac_address() def get_blade_temperature(self): return self.api.System.SystemInfo.get_blade_temperature() def get_chassis_slot_information(self): return self.api.System.SystemInfo.get_chassis_slot_information() def get_globally_unique_identifier(self): return self.api.System.SystemInfo.get_globally_unique_identifier() def get_group_id(self): return self.api.System.SystemInfo.get_group_id() def get_hardware_information(self): return self.api.System.SystemInfo.get_hardware_information() def get_marketing_name(self): return self.api.System.SystemInfo.get_marketing_name() def get_product_information(self): return self.api.System.SystemInfo.get_product_information() def get_pva_version(self): return self.api.System.SystemInfo.get_pva_version() def get_system_id(self): return self.api.System.SystemInfo.get_system_id() def get_system_information(self): return self.api.System.SystemInfo.get_system_information() def get_time(self): return self.api.System.SystemInfo.get_time() def get_time_zone(self): return self.api.System.SystemInfo.get_time_zone() def get_uptime(self): return self.api.System.SystemInfo.get_uptime() class ProvisionInfo(object): """Provision information class. F5 BIG-IP provision information class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_list(self): result = [] list = self.api.Management.Provision.get_list() for item in list: item = item.lower().replace('tmos_module_', '') result.append(item) return result def get_provisioned_list(self): result = [] list = self.api.Management.Provision.get_provisioned_list() for item in list: item = item.lower().replace('tmos_module_', '') result.append(item) return result def generate_dict(api_obj, fields): result_dict = {} lists = [] supported_fields = [] if api_obj.get_list(): for field in fields: try: api_response = getattr(api_obj, "get_" + field)() except (MethodNotFound, WebFault): pass else: lists.append(api_response) supported_fields.append(field) for i, j in enumerate(api_obj.get_list()): temp = {} temp.update([(item[0], item[1][i]) for item in zip(supported_fields, lists)]) result_dict[j] = temp return result_dict def generate_simple_dict(api_obj, fields): result_dict = {} for field in fields: try: api_response = getattr(api_obj, "get_" + field)() except (MethodNotFound, WebFault): pass else: result_dict[field] = api_response return result_dict def generate_interface_dict(f5, regex): interfaces = Interfaces(f5.get_api(), regex) fields = ['active_media', 'actual_flow_control', 'bundle_state', 'description', 'dual_media_state', 'enabled_state', 'if_index', 'learning_mode', 'lldp_admin_status', 'lldp_tlvmap', 'mac_address', 'media', 'media_option', 'media_option_sfp', 'media_sfp', 'media_speed', 'media_status', 'mtu', 'phy_master_slave_mode', 'prefer_sfp_state', 'flow_control', 'sflow_poll_interval', 'sflow_poll_interval_global', 'sfp_media_state', 'stp_active_edge_port_state', 'stp_enabled_state', 'stp_link_type', 'stp_protocol_detection_reset_state'] return generate_dict(interfaces, fields) def generate_self_ip_dict(f5, regex): self_ips = SelfIPs(f5.get_api(), regex) fields = ['address', 'allow_access_list', 'description', 'enforced_firewall_policy', 'floating_state', 'fw_rule', 'netmask', 'staged_firewall_policy', 'traffic_group', 'vlan', 'is_traffic_group_inherited'] return generate_dict(self_ips, fields) def generate_trunk_dict(f5, regex): trunks = Trunks(f5.get_api(), regex) fields = ['active_lacp_state', 'configured_member_count', 'description', 'distribution_hash_option', 'interface', 'lacp_enabled_state', 'lacp_timeout_option', 'link_selection_policy', 'media_speed', 'media_status', 'operational_member_count', 'stp_enabled_state', 'stp_protocol_detection_reset_state'] return generate_dict(trunks, fields) def generate_vlan_dict(f5, regex): vlans = Vlans(f5.get_api(), regex) fields = ['auto_lasthop', 'cmp_hash_algorithm', 'description', 'dynamic_forwarding', 'failsafe_action', 'failsafe_state', 'failsafe_timeout', 'if_index', 'learning_mode', 'mac_masquerade_address', 'member', 'mtu', 'sflow_poll_interval', 'sflow_poll_interval_global', 'sflow_sampling_rate', 'sflow_sampling_rate_global', 'source_check_state', 'true_mac_address', 'vlan_id'] return generate_dict(vlans, fields) def generate_vs_dict(f5, regex): virtual_servers = VirtualServers(f5.get_api(), regex) fields = ['actual_hardware_acceleration', 'authentication_profile', 'auto_lasthop', 'bw_controller_policy', 'clone_pool', 'cmp_enable_mode', 'connection_limit', 'connection_mirror_state', 'default_pool_name', 'description', 'destination', 'enabled_state', 'enforced_firewall_policy', 'fallback_persistence_profile', 'fw_rule', 'gtm_score', 'last_hop_pool', 'nat64_state', 'object_status', 'persistence_profile', 'profile', 'protocol', 'rate_class', 'rate_limit', 'rate_limit_destination_mask', 'rate_limit_mode', 'rate_limit_source_mask', 'related_rule', 'rule', 'security_log_profile', 'snat_pool', 'snat_type', 'source_address', 'source_address_translation_lsn_pool', 'source_address_translation_snat_pool', 'source_address_translation_type', 'source_port_behavior', 'staged_firewall_policy', 'translate_address_state', 'translate_port_state', 'type', 'vlan', 'wildmask', 'name'] return generate_dict(virtual_servers, fields) def generate_pool_dict(f5, regex): pools = Pools(f5.get_api(), regex) fields = ['action_on_service_down', 'active_member_count', 'aggregate_dynamic_ratio', 'allow_nat_state', 'allow_snat_state', 'client_ip_tos', 'client_link_qos', 'description', 'gateway_failsafe_device', 'ignore_persisted_weight_state', 'lb_method', 'member', 'minimum_active_member', 'minimum_up_member', 'minimum_up_member_action', 'minimum_up_member_enabled_state', 'monitor_association', 'monitor_instance', 'object_status', 'profile', 'queue_depth_limit', 'queue_on_connection_limit_state', 'queue_time_limit', 'reselect_tries', 'server_ip_tos', 'server_link_qos', 'simple_timeout', 'slow_ramp_time', 'name'] return generate_dict(pools, fields) def generate_device_dict(f5, regex): devices = Devices(f5.get_api(), regex) fields = ['active_modules', 'base_mac_address', 'blade_addresses', 'build', 'chassis_id', 'chassis_type', 'comment', 'configsync_address', 'contact', 'description', 'edition', 'failover_state', 'hostname', 'inactive_modules', 'location', 'management_address', 'marketing_name', 'multicast_address', 'optional_modules', 'platform_id', 'primary_mirror_address', 'product', 'secondary_mirror_address', 'software_version', 'timelimited_modules', 'timezone', 'unicast_addresses'] return generate_dict(devices, fields) def generate_device_group_dict(f5, regex): device_groups = DeviceGroups(f5.get_api(), regex) fields = ['all_preferred_active', 'autosync_enabled_state', 'description', 'device', 'full_load_on_sync_state', 'incremental_config_sync_size_maximum', 'network_failover_enabled_state', 'sync_status', 'type'] return generate_dict(device_groups, fields) def generate_traffic_group_dict(f5, regex): traffic_groups = TrafficGroups(f5.get_api(), regex) fields = ['auto_failback_enabled_state', 'auto_failback_time', 'default_device', 'description', 'ha_load_factor', 'ha_order', 'is_floating', 'mac_masquerade_address', 'unit_id'] return generate_dict(traffic_groups, fields) def generate_rule_dict(f5, regex): rules = Rules(f5.get_api(), regex) fields = ['definition', 'description', 'ignore_vertification', 'verification_status'] return generate_dict(rules, fields) def generate_node_dict(f5, regex): nodes = Nodes(f5.get_api(), regex) fields = ['name', 'address', 'connection_limit', 'description', 'dynamic_ratio', 'monitor_instance', 'monitor_rule', 'monitor_status', 'object_status', 'rate_limit', 'ratio', 'session_status'] return generate_dict(nodes, fields) def generate_virtual_address_dict(f5, regex): virtual_addresses = VirtualAddresses(f5.get_api(), regex) fields = ['address', 'arp_state', 'auto_delete_state', 'connection_limit', 'description', 'enabled_state', 'icmp_echo_state', 'is_floating_state', 'netmask', 'object_status', 'route_advertisement_state', 'traffic_group'] return generate_dict(virtual_addresses, fields) def generate_address_class_dict(f5, regex): address_classes = AddressClasses(f5.get_api(), regex) fields = ['address_class', 'description'] return generate_dict(address_classes, fields) def generate_certificate_dict(f5, regex): certificates = Certificates(f5.get_api(), regex) return dict(zip(certificates.get_list(), certificates.get_certificate_list())) def generate_key_dict(f5, regex): keys = Keys(f5.get_api(), regex) return dict(zip(keys.get_list(), keys.get_key_list())) def generate_client_ssl_profile_dict(f5, regex): profiles = ProfileClientSSL(f5.get_api(), regex) fields = ['alert_timeout', 'allow_nonssl_state', 'authenticate_depth', 'authenticate_once_state', 'ca_file', 'cache_size', 'cache_timeout', 'certificate_file', 'chain_file', 'cipher_list', 'client_certificate_ca_file', 'crl_file', 'default_profile', 'description', 'forward_proxy_ca_certificate_file', 'forward_proxy_ca_key_file', 'forward_proxy_ca_passphrase', 'forward_proxy_certificate_extension_include', 'forward_proxy_certificate_lifespan', 'forward_proxy_enabled_state', 'forward_proxy_lookup_by_ipaddr_port_state', 'handshake_timeout', 'key_file', 'modssl_emulation_state', 'passphrase', 'peer_certification_mode', 'profile_mode', 'renegotiation_maximum_record_delay', 'renegotiation_period', 'renegotiation_state', 'renegotiation_throughput', 'retain_certificate_state', 'secure_renegotiation_mode', 'server_name', 'session_ticket_state', 'sni_default_state', 'sni_require_state', 'ssl_option', 'strict_resume_state', 'unclean_shutdown_state', 'is_base_profile', 'is_system_profile'] return generate_dict(profiles, fields) def generate_system_info_dict(f5): system_info = SystemInfo(f5.get_api()) fields = ['base_mac_address', 'blade_temperature', 'chassis_slot_information', 'globally_unique_identifier', 'group_id', 'hardware_information', 'marketing_name', 'product_information', 'pva_version', 'system_id', 'system_information', 'time', 'time_zone', 'uptime'] return generate_simple_dict(system_info, fields) def generate_software_list(f5): software = Software(f5.get_api()) software_list = software.get_all_software_status() return software_list def generate_provision_dict(f5): provisioned = ProvisionInfo(f5.get_api()) fields = ['list', 'provisioned_list'] return generate_simple_dict(provisioned, fields) class ArgumentSpec(object): def __init__(self): self.supports_check_mode = False argument_spec = dict( session=dict(type='bool', default='no'), include=dict( type='raw', required=True, choices=[ 'address_class', 'certificate', 'client_ssl_profile', 'device', 'device_group', 'interface', 'key', 'node', 'pool', 'provision', 'rule', 'self_ip', 'software', 'system_info', 'traffic_group', 'trunk', 'virtual_address', 'virtual_server', 'vlan' ] ), filter=dict(type='str'), ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) def main(): spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec ) client = F5BaseClient(**module.params) provider = client.merge_provider_params() if not bigsuds_found: module.fail_json(msg="the python suds and bigsuds modules are required") server = provider['server'] server_port = provider['server_port'] user = provider['user'] password = provider['password'] validate_certs = provider['validate_certs'] session = module.params['session'] fact_filter = module.params['filter'] if validate_certs: import ssl if not hasattr(ssl, 'SSLContext'): module.fail_json( msg='bigsuds does not support verifying certificates with python < 2.7.9. Either update python or set validate_certs=False on the task' ) if fact_filter: regex = fnmatch.translate(fact_filter) else: regex = None if isinstance(module.params['include'], string_types): includes = module.params['include'].split(',') else: includes = module.params['include'] include = [x.lower() for x in includes] valid_includes = ('address_class', 'certificate', 'client_ssl_profile', 'device', 'device_group', 'interface', 'key', 'node', 'pool', 'provision', 'rule', 'self_ip', 'software', 'system_info', 'traffic_group', 'trunk', 'virtual_address', 'virtual_server', 'vlan') include_test = (x in valid_includes for x in include) if not all(include_test): module.fail_json(msg="Value of include must be one or more of: %s, got: %s" % (",".join(valid_includes), ",".join(include))) try: facts = {} if len(include) > 0: f5 = F5(server, user, password, session, validate_certs, server_port) saved_active_folder = f5.get_active_folder() saved_recursive_query_state = f5.get_recursive_query_state() if saved_active_folder != "/": f5.set_active_folder("/") if saved_recursive_query_state != "STATE_ENABLED": f5.enable_recursive_query_state() if 'interface' in include: facts['interface'] = generate_interface_dict(f5, regex) if 'self_ip' in include: facts['self_ip'] = generate_self_ip_dict(f5, regex) if 'trunk' in include: facts['trunk'] = generate_trunk_dict(f5, regex) if 'vlan' in include: facts['vlan'] = generate_vlan_dict(f5, regex) if 'virtual_server' in include: facts['virtual_server'] = generate_vs_dict(f5, regex) if 'pool' in include: facts['pool'] = generate_pool_dict(f5, regex) if 'provision' in include: facts['provision'] = generate_provision_dict(f5) if 'device' in include: facts['device'] = generate_device_dict(f5, regex) if 'device_group' in include: facts['device_group'] = generate_device_group_dict(f5, regex) if 'traffic_group' in include: facts['traffic_group'] = generate_traffic_group_dict(f5, regex) if 'rule' in include: facts['rule'] = generate_rule_dict(f5, regex) if 'node' in include: facts['node'] = generate_node_dict(f5, regex) if 'virtual_address' in include: facts['virtual_address'] = generate_virtual_address_dict(f5, regex) if 'address_class' in include: facts['address_class'] = generate_address_class_dict(f5, regex) if 'software' in include: facts['software'] = generate_software_list(f5) if 'certificate' in include: facts['certificate'] = generate_certificate_dict(f5, regex) if 'key' in include: facts['key'] = generate_key_dict(f5, regex) if 'client_ssl_profile' in include: facts['client_ssl_profile'] = generate_client_ssl_profile_dict(f5, regex) if 'system_info' in include: facts['system_info'] = generate_system_info_dict(f5) # restore saved state if saved_active_folder and saved_active_folder != "/": f5.set_active_folder(saved_active_folder) if saved_recursive_query_state and \ saved_recursive_query_state != "STATE_ENABLED": f5.set_recursive_query_state(saved_recursive_query_state) result = dict( ansible_facts=facts, ) result.update(**facts) except Exception as e: module.fail_json(msg="received exception: %s\ntraceback: %s" % (e, traceback.format_exc())) module.exit_json(**result) if __name__ == '__main__': main()
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # Copyright (c) 2013 Matt Hite <mhite@hotmail.com> # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: bigip_facts short_description: Collect facts from F5 BIG-IP devices description: - Collect facts from F5 BIG-IP devices via iControl SOAP API version_added: 1.6 author: - Matt Hite (@mhite) - Tim Rupp (@caphrim007) notes: - Requires BIG-IP software version >= 11.4 - F5 developed module 'bigsuds' required (see http://devcentral.f5.com) - Best run as a local_action in your playbook - Tested with manager and above account privilege level - C(provision) facts were added in 2.2 requirements: - bigsuds options: session: description: - BIG-IP session support; may be useful to avoid concurrency issues in certain circumstances. default: no type: bool include: description: - Fact category or list of categories to collect required: True choices: - address_class - certificate - client_ssl_profile - device - device_group - interface - key - node - pool - provision - rule - self_ip - software - system_info - traffic_group - trunk - virtual_address - virtual_server - vlan filter: description: - Shell-style glob matching string used to filter fact keys. Not applicable for software, provision, and system_info fact categories. extends_documentation_fragment: f5 ''' EXAMPLES = r''' - name: Collect BIG-IP facts bigip_facts: server: lb.mydomain.com user: admin password: secret include: - interface - vlan delegate_to: localhost ''' import fnmatch import re import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import string_types from ansible.module_utils.six.moves import map, zip try: from library.module_utils.network.f5.legacy import bigip_api, bigsuds_found from library.module_utils.network.f5.common import f5_argument_spec except ImportError: from ansible.module_utils.network.f5.legacy import bigip_api, bigsuds_found from ansible.module_utils.network.f5.common import f5_argument_spec try: from suds import MethodNotFound, WebFault except ImportError: pass # Handle via f5_utils.bigsuds_found class F5(object): """F5 iControl class. F5 BIG-IP iControl API class. Attributes: api: iControl API instance. """ def __init__(self, host, user, password, session=False, validate_certs=True, port=443): self.api = bigip_api(host, user, password, validate_certs, port) if session: self.start_session() def start_session(self): self.api = self.api.with_session_id() def get_api(self): return self.api def set_recursive_query_state(self, state): self.api.System.Session.set_recursive_query_state(state) def get_recursive_query_state(self): return self.api.System.Session.get_recursive_query_state() def enable_recursive_query_state(self): self.set_recursive_query_state('STATE_ENABLED') def disable_recursive_query_state(self): self.set_recursive_query_state('STATE_DISABLED') def set_active_folder(self, folder): self.api.System.Session.set_active_folder(folder=folder) def get_active_folder(self): return self.api.System.Session.get_active_folder() class Interfaces(object): """Interfaces class. F5 BIG-IP interfaces class. Attributes: api: iControl API instance. interfaces: A list of BIG-IP interface names. """ def __init__(self, api, regex=None): self.api = api self.interfaces = api.Networking.Interfaces.get_list() if regex: re_filter = re.compile(regex) self.interfaces = filter(re_filter.search, self.interfaces) def get_list(self): return self.interfaces def get_active_media(self): return self.api.Networking.Interfaces.get_active_media(self.interfaces) def get_actual_flow_control(self): return self.api.Networking.Interfaces.get_actual_flow_control(self.interfaces) def get_bundle_state(self): return self.api.Networking.Interfaces.get_bundle_state(self.interfaces) def get_description(self): return self.api.Networking.Interfaces.get_description(self.interfaces) def get_dual_media_state(self): return self.api.Networking.Interfaces.get_dual_media_state(self.interfaces) def get_enabled_state(self): return self.api.Networking.Interfaces.get_enabled_state(self.interfaces) def get_if_index(self): return self.api.Networking.Interfaces.get_if_index(self.interfaces) def get_learning_mode(self): return self.api.Networking.Interfaces.get_learning_mode(self.interfaces) def get_lldp_admin_status(self): return self.api.Networking.Interfaces.get_lldp_admin_status(self.interfaces) def get_lldp_tlvmap(self): return self.api.Networking.Interfaces.get_lldp_tlvmap(self.interfaces) def get_mac_address(self): return self.api.Networking.Interfaces.get_mac_address(self.interfaces) def get_media(self): return self.api.Networking.Interfaces.get_media(self.interfaces) def get_media_option(self): return self.api.Networking.Interfaces.get_media_option(self.interfaces) def get_media_option_sfp(self): return self.api.Networking.Interfaces.get_media_option_sfp(self.interfaces) def get_media_sfp(self): return self.api.Networking.Interfaces.get_media_sfp(self.interfaces) def get_media_speed(self): return self.api.Networking.Interfaces.get_media_speed(self.interfaces) def get_media_status(self): return self.api.Networking.Interfaces.get_media_status(self.interfaces) def get_mtu(self): return self.api.Networking.Interfaces.get_mtu(self.interfaces) def get_phy_master_slave_mode(self): return self.api.Networking.Interfaces.get_phy_master_slave_mode(self.interfaces) def get_prefer_sfp_state(self): return self.api.Networking.Interfaces.get_prefer_sfp_state(self.interfaces) def get_flow_control(self): return self.api.Networking.Interfaces.get_requested_flow_control(self.interfaces) def get_sflow_poll_interval(self): return self.api.Networking.Interfaces.get_sflow_poll_interval(self.interfaces) def get_sflow_poll_interval_global(self): return self.api.Networking.Interfaces.get_sflow_poll_interval_global(self.interfaces) def get_sfp_media_state(self): return self.api.Networking.Interfaces.get_sfp_media_state(self.interfaces) def get_stp_active_edge_port_state(self): return self.api.Networking.Interfaces.get_stp_active_edge_port_state(self.interfaces) def get_stp_enabled_state(self): return self.api.Networking.Interfaces.get_stp_enabled_state(self.interfaces) def get_stp_link_type(self): return self.api.Networking.Interfaces.get_stp_link_type(self.interfaces) def get_stp_protocol_detection_reset_state(self): return self.api.Networking.Interfaces.get_stp_protocol_detection_reset_state(self.interfaces) class SelfIPs(object): """Self IPs class. F5 BIG-IP Self IPs class. Attributes: api: iControl API instance. self_ips: List of self IPs. """ def __init__(self, api, regex=None): self.api = api self.self_ips = api.Networking.SelfIPV2.get_list() if regex: re_filter = re.compile(regex) self.self_ips = filter(re_filter.search, self.self_ips) def get_list(self): return self.self_ips def get_address(self): return self.api.Networking.SelfIPV2.get_address(self.self_ips) def get_allow_access_list(self): return self.api.Networking.SelfIPV2.get_allow_access_list(self.self_ips) def get_description(self): return self.api.Networking.SelfIPV2.get_description(self.self_ips) def get_enforced_firewall_policy(self): return self.api.Networking.SelfIPV2.get_enforced_firewall_policy(self.self_ips) def get_floating_state(self): return self.api.Networking.SelfIPV2.get_floating_state(self.self_ips) def get_fw_rule(self): return self.api.Networking.SelfIPV2.get_fw_rule(self.self_ips) def get_netmask(self): return self.api.Networking.SelfIPV2.get_netmask(self.self_ips) def get_staged_firewall_policy(self): return self.api.Networking.SelfIPV2.get_staged_firewall_policy(self.self_ips) def get_traffic_group(self): return self.api.Networking.SelfIPV2.get_traffic_group(self.self_ips) def get_vlan(self): return self.api.Networking.SelfIPV2.get_vlan(self.self_ips) def get_is_traffic_group_inherited(self): return self.api.Networking.SelfIPV2.is_traffic_group_inherited(self.self_ips) class Trunks(object): """Trunks class. F5 BIG-IP trunks class. Attributes: api: iControl API instance. trunks: List of trunks. """ def __init__(self, api, regex=None): self.api = api self.trunks = api.Networking.Trunk.get_list() if regex: re_filter = re.compile(regex) self.trunks = filter(re_filter.search, self.trunks) def get_list(self): return self.trunks def get_active_lacp_state(self): return self.api.Networking.Trunk.get_active_lacp_state(self.trunks) def get_configured_member_count(self): return self.api.Networking.Trunk.get_configured_member_count(self.trunks) def get_description(self): return self.api.Networking.Trunk.get_description(self.trunks) def get_distribution_hash_option(self): return self.api.Networking.Trunk.get_distribution_hash_option(self.trunks) def get_interface(self): return self.api.Networking.Trunk.get_interface(self.trunks) def get_lacp_enabled_state(self): return self.api.Networking.Trunk.get_lacp_enabled_state(self.trunks) def get_lacp_timeout_option(self): return self.api.Networking.Trunk.get_lacp_timeout_option(self.trunks) def get_link_selection_policy(self): return self.api.Networking.Trunk.get_link_selection_policy(self.trunks) def get_media_speed(self): return self.api.Networking.Trunk.get_media_speed(self.trunks) def get_media_status(self): return self.api.Networking.Trunk.get_media_status(self.trunks) def get_operational_member_count(self): return self.api.Networking.Trunk.get_operational_member_count(self.trunks) def get_stp_enabled_state(self): return self.api.Networking.Trunk.get_stp_enabled_state(self.trunks) def get_stp_protocol_detection_reset_state(self): return self.api.Networking.Trunk.get_stp_protocol_detection_reset_state(self.trunks) class Vlans(object): """Vlans class. F5 BIG-IP Vlans class. Attributes: api: iControl API instance. vlans: List of VLANs. """ def __init__(self, api, regex=None): self.api = api self.vlans = api.Networking.VLAN.get_list() if regex: re_filter = re.compile(regex) self.vlans = filter(re_filter.search, self.vlans) def get_list(self): return self.vlans def get_auto_lasthop(self): return self.api.Networking.VLAN.get_auto_lasthop(self.vlans) def get_cmp_hash_algorithm(self): return self.api.Networking.VLAN.get_cmp_hash_algorithm(self.vlans) def get_description(self): return self.api.Networking.VLAN.get_description(self.vlans) def get_dynamic_forwarding(self): return self.api.Networking.VLAN.get_dynamic_forwarding(self.vlans) def get_failsafe_action(self): return self.api.Networking.VLAN.get_failsafe_action(self.vlans) def get_failsafe_state(self): return self.api.Networking.VLAN.get_failsafe_state(self.vlans) def get_failsafe_timeout(self): return self.api.Networking.VLAN.get_failsafe_timeout(self.vlans) def get_if_index(self): return self.api.Networking.VLAN.get_if_index(self.vlans) def get_learning_mode(self): return self.api.Networking.VLAN.get_learning_mode(self.vlans) def get_mac_masquerade_address(self): return self.api.Networking.VLAN.get_mac_masquerade_address(self.vlans) def get_member(self): return self.api.Networking.VLAN.get_member(self.vlans) def get_mtu(self): return self.api.Networking.VLAN.get_mtu(self.vlans) def get_sflow_poll_interval(self): return self.api.Networking.VLAN.get_sflow_poll_interval(self.vlans) def get_sflow_poll_interval_global(self): return self.api.Networking.VLAN.get_sflow_poll_interval_global(self.vlans) def get_sflow_sampling_rate(self): return self.api.Networking.VLAN.get_sflow_sampling_rate(self.vlans) def get_sflow_sampling_rate_global(self): return self.api.Networking.VLAN.get_sflow_sampling_rate_global(self.vlans) def get_source_check_state(self): return self.api.Networking.VLAN.get_source_check_state(self.vlans) def get_true_mac_address(self): return self.api.Networking.VLAN.get_true_mac_address(self.vlans) def get_vlan_id(self): return self.api.Networking.VLAN.get_vlan_id(self.vlans) class Software(object): """Software class. F5 BIG-IP software class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_all_software_status(self): return self.api.System.SoftwareManagement.get_all_software_status() class VirtualServers(object): """Virtual servers class. F5 BIG-IP virtual servers class. Attributes: api: iControl API instance. virtual_servers: List of virtual servers. """ def __init__(self, api, regex=None): self.api = api self.virtual_servers = api.LocalLB.VirtualServer.get_list() if regex: re_filter = re.compile(regex) self.virtual_servers = filter(re_filter.search, self.virtual_servers) def get_list(self): return self.virtual_servers def get_name(self): return [x[x.rfind('/') + 1:] for x in self.virtual_servers] def get_actual_hardware_acceleration(self): return self.api.LocalLB.VirtualServer.get_actual_hardware_acceleration(self.virtual_servers) def get_authentication_profile(self): return self.api.LocalLB.VirtualServer.get_authentication_profile(self.virtual_servers) def get_auto_lasthop(self): return self.api.LocalLB.VirtualServer.get_auto_lasthop(self.virtual_servers) def get_bw_controller_policy(self): return self.api.LocalLB.VirtualServer.get_bw_controller_policy(self.virtual_servers) def get_clone_pool(self): return self.api.LocalLB.VirtualServer.get_clone_pool(self.virtual_servers) def get_cmp_enable_mode(self): return self.api.LocalLB.VirtualServer.get_cmp_enable_mode(self.virtual_servers) def get_connection_limit(self): return self.api.LocalLB.VirtualServer.get_connection_limit(self.virtual_servers) def get_connection_mirror_state(self): return self.api.LocalLB.VirtualServer.get_connection_mirror_state(self.virtual_servers) def get_default_pool_name(self): return self.api.LocalLB.VirtualServer.get_default_pool_name(self.virtual_servers) def get_description(self): return self.api.LocalLB.VirtualServer.get_description(self.virtual_servers) def get_destination(self): return self.api.LocalLB.VirtualServer.get_destination_v2(self.virtual_servers) def get_enabled_state(self): return self.api.LocalLB.VirtualServer.get_enabled_state(self.virtual_servers) def get_enforced_firewall_policy(self): return self.api.LocalLB.VirtualServer.get_enforced_firewall_policy(self.virtual_servers) def get_fallback_persistence_profile(self): return self.api.LocalLB.VirtualServer.get_fallback_persistence_profile(self.virtual_servers) def get_fw_rule(self): return self.api.LocalLB.VirtualServer.get_fw_rule(self.virtual_servers) def get_gtm_score(self): return self.api.LocalLB.VirtualServer.get_gtm_score(self.virtual_servers) def get_last_hop_pool(self): return self.api.LocalLB.VirtualServer.get_last_hop_pool(self.virtual_servers) def get_nat64_state(self): return self.api.LocalLB.VirtualServer.get_nat64_state(self.virtual_servers) def get_object_status(self): return self.api.LocalLB.VirtualServer.get_object_status(self.virtual_servers) def get_persistence_profile(self): return self.api.LocalLB.VirtualServer.get_persistence_profile(self.virtual_servers) def get_profile(self): return self.api.LocalLB.VirtualServer.get_profile(self.virtual_servers) def get_protocol(self): return self.api.LocalLB.VirtualServer.get_protocol(self.virtual_servers) def get_rate_class(self): return self.api.LocalLB.VirtualServer.get_rate_class(self.virtual_servers) def get_rate_limit(self): return self.api.LocalLB.VirtualServer.get_rate_limit(self.virtual_servers) def get_rate_limit_destination_mask(self): return self.api.LocalLB.VirtualServer.get_rate_limit_destination_mask(self.virtual_servers) def get_rate_limit_mode(self): return self.api.LocalLB.VirtualServer.get_rate_limit_mode(self.virtual_servers) def get_rate_limit_source_mask(self): return self.api.LocalLB.VirtualServer.get_rate_limit_source_mask(self.virtual_servers) def get_related_rule(self): return self.api.LocalLB.VirtualServer.get_related_rule(self.virtual_servers) def get_rule(self): return self.api.LocalLB.VirtualServer.get_rule(self.virtual_servers) def get_security_log_profile(self): return self.api.LocalLB.VirtualServer.get_security_log_profile(self.virtual_servers) def get_snat_pool(self): return self.api.LocalLB.VirtualServer.get_snat_pool(self.virtual_servers) def get_snat_type(self): return self.api.LocalLB.VirtualServer.get_snat_type(self.virtual_servers) def get_source_address(self): return self.api.LocalLB.VirtualServer.get_source_address(self.virtual_servers) def get_source_address_translation_lsn_pool(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_lsn_pool(self.virtual_servers) def get_source_address_translation_snat_pool(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_snat_pool(self.virtual_servers) def get_source_address_translation_type(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_type(self.virtual_servers) def get_source_port_behavior(self): return self.api.LocalLB.VirtualServer.get_source_port_behavior(self.virtual_servers) def get_staged_firewall_policy(self): return self.api.LocalLB.VirtualServer.get_staged_firewall_policy(self.virtual_servers) def get_translate_address_state(self): return self.api.LocalLB.VirtualServer.get_translate_address_state(self.virtual_servers) def get_translate_port_state(self): return self.api.LocalLB.VirtualServer.get_translate_port_state(self.virtual_servers) def get_type(self): return self.api.LocalLB.VirtualServer.get_type(self.virtual_servers) def get_vlan(self): return self.api.LocalLB.VirtualServer.get_vlan(self.virtual_servers) def get_wildmask(self): return self.api.LocalLB.VirtualServer.get_wildmask(self.virtual_servers) class Pools(object): """Pools class. F5 BIG-IP pools class. Attributes: api: iControl API instance. pool_names: List of pool names. """ def __init__(self, api, regex=None): self.api = api self.pool_names = api.LocalLB.Pool.get_list() if regex: re_filter = re.compile(regex) self.pool_names = filter(re_filter.search, self.pool_names) def get_list(self): return self.pool_names def get_name(self): return [x[x.rfind('/') + 1:] for x in self.pool_names] def get_action_on_service_down(self): return self.api.LocalLB.Pool.get_action_on_service_down(self.pool_names) def get_active_member_count(self): return self.api.LocalLB.Pool.get_active_member_count(self.pool_names) def get_aggregate_dynamic_ratio(self): return self.api.LocalLB.Pool.get_aggregate_dynamic_ratio(self.pool_names) def get_allow_nat_state(self): return self.api.LocalLB.Pool.get_allow_nat_state(self.pool_names) def get_allow_snat_state(self): return self.api.LocalLB.Pool.get_allow_snat_state(self.pool_names) def get_client_ip_tos(self): return self.api.LocalLB.Pool.get_client_ip_tos(self.pool_names) def get_client_link_qos(self): return self.api.LocalLB.Pool.get_client_link_qos(self.pool_names) def get_description(self): return self.api.LocalLB.Pool.get_description(self.pool_names) def get_gateway_failsafe_device(self): return self.api.LocalLB.Pool.get_gateway_failsafe_device(self.pool_names) def get_ignore_persisted_weight_state(self): return self.api.LocalLB.Pool.get_ignore_persisted_weight_state(self.pool_names) def get_lb_method(self): result = [] lb_choice = dict( LB_METHOD_DYNAMIC_RATIO_MEMBER='dynamic-ratio-member', LB_METHOD_DYNAMIC_RATIO='dynamic-ratio-node', LB_METHOD_FASTEST_APP_RESPONSE='fastest-app-response', LB_METHOD_FASTEST_NODE_ADDRESS='fastest-node', LB_METHOD_LEAST_CONNECTION_MEMBER='least-connections-member', LB_METHOD_LEAST_CONNECTION_NODE_ADDRESS='least-connections-node', LB_METHOD_LEAST_SESSIONS='least-sessions', LB_METHOD_OBSERVED_MEMBER='observed-member', LB_METHOD_OBSERVED_NODE_ADDRESS='observed-node', LB_METHOD_PREDICTIVE_MEMBER='predictive-member', LB_METHOD_PREDICTIVE_NODE_ADDRESS='predictive-node', LB_METHOD_RATIO_LEAST_CONNECTION_MEMBER='ratio-least-connections-member', LB_METHOD_RATIO_LEAST_CONNECTION_NODE_ADDRESS='ratio-least-connections-node', LB_METHOD_RATIO_MEMBER='ratio-member', LB_METHOD_RATIO_NODE_ADDRESS='ratio-node', LB_METHOD_RATIO_SESSION='ratio-session', LB_METHOD_ROUND_ROBIN='round-robin', LB_METHOD_WEIGHTED_LEAST_CONNECTION_MEMBER='weighted-least-connections-member', LB_METHOD_WEIGHTED_LEAST_CONNECTION_NODE_ADDRESS='weighted-least-connections-node' ) methods = self.api.LocalLB.Pool.get_lb_method(self.pool_names) for method in methods: result.append(lb_choice.get(method, method)) return result def get_member(self): return self.api.LocalLB.Pool.get_member_v2(self.pool_names) def get_minimum_active_member(self): return self.api.LocalLB.Pool.get_minimum_active_member(self.pool_names) def get_minimum_up_member(self): return self.api.LocalLB.Pool.get_minimum_up_member(self.pool_names) def get_minimum_up_member_action(self): return self.api.LocalLB.Pool.get_minimum_up_member_action(self.pool_names) def get_minimum_up_member_enabled_state(self): return self.api.LocalLB.Pool.get_minimum_up_member_enabled_state(self.pool_names) def get_monitor_association(self): return self.api.LocalLB.Pool.get_monitor_association(self.pool_names) def get_monitor_instance(self): return self.api.LocalLB.Pool.get_monitor_instance(self.pool_names) def get_object_status(self): return self.api.LocalLB.Pool.get_object_status(self.pool_names) def get_profile(self): return self.api.LocalLB.Pool.get_profile(self.pool_names) def get_queue_depth_limit(self): return self.api.LocalLB.Pool.get_queue_depth_limit(self.pool_names) def get_queue_on_connection_limit_state(self): return self.api.LocalLB.Pool.get_queue_on_connection_limit_state(self.pool_names) def get_queue_time_limit(self): return self.api.LocalLB.Pool.get_queue_time_limit(self.pool_names) def get_reselect_tries(self): return self.api.LocalLB.Pool.get_reselect_tries(self.pool_names) def get_server_ip_tos(self): return self.api.LocalLB.Pool.get_server_ip_tos(self.pool_names) def get_server_link_qos(self): return self.api.LocalLB.Pool.get_server_link_qos(self.pool_names) def get_simple_timeout(self): return self.api.LocalLB.Pool.get_simple_timeout(self.pool_names) def get_slow_ramp_time(self): return self.api.LocalLB.Pool.get_slow_ramp_time(self.pool_names) class Devices(object): """Devices class. F5 BIG-IP devices class. Attributes: api: iControl API instance. devices: List of devices. """ def __init__(self, api, regex=None): self.api = api self.devices = api.Management.Device.get_list() if regex: re_filter = re.compile(regex) self.devices = filter(re_filter.search, self.devices) def get_list(self): return self.devices def get_active_modules(self): return self.api.Management.Device.get_active_modules(self.devices) def get_base_mac_address(self): return self.api.Management.Device.get_base_mac_address(self.devices) def get_blade_addresses(self): return self.api.Management.Device.get_blade_addresses(self.devices) def get_build(self): return self.api.Management.Device.get_build(self.devices) def get_chassis_id(self): return self.api.Management.Device.get_chassis_id(self.devices) def get_chassis_type(self): return self.api.Management.Device.get_chassis_type(self.devices) def get_comment(self): return self.api.Management.Device.get_comment(self.devices) def get_configsync_address(self): return self.api.Management.Device.get_configsync_address(self.devices) def get_contact(self): return self.api.Management.Device.get_contact(self.devices) def get_description(self): return self.api.Management.Device.get_description(self.devices) def get_edition(self): return self.api.Management.Device.get_edition(self.devices) def get_failover_state(self): return self.api.Management.Device.get_failover_state(self.devices) def get_local_device(self): return self.api.Management.Device.get_local_device() def get_hostname(self): return self.api.Management.Device.get_hostname(self.devices) def get_inactive_modules(self): return self.api.Management.Device.get_inactive_modules(self.devices) def get_location(self): return self.api.Management.Device.get_location(self.devices) def get_management_address(self): return self.api.Management.Device.get_management_address(self.devices) def get_marketing_name(self): return self.api.Management.Device.get_marketing_name(self.devices) def get_multicast_address(self): return self.api.Management.Device.get_multicast_address(self.devices) def get_optional_modules(self): return self.api.Management.Device.get_optional_modules(self.devices) def get_platform_id(self): return self.api.Management.Device.get_platform_id(self.devices) def get_primary_mirror_address(self): return self.api.Management.Device.get_primary_mirror_address(self.devices) def get_product(self): return self.api.Management.Device.get_product(self.devices) def get_secondary_mirror_address(self): return self.api.Management.Device.get_secondary_mirror_address(self.devices) def get_software_version(self): return self.api.Management.Device.get_software_version(self.devices) def get_timelimited_modules(self): return self.api.Management.Device.get_timelimited_modules(self.devices) def get_timezone(self): return self.api.Management.Device.get_timezone(self.devices) def get_unicast_addresses(self): return self.api.Management.Device.get_unicast_addresses(self.devices) class DeviceGroups(object): """Device groups class. F5 BIG-IP device groups class. Attributes: api: iControl API instance. device_groups: List of device groups. """ def __init__(self, api, regex=None): self.api = api self.device_groups = api.Management.DeviceGroup.get_list() if regex: re_filter = re.compile(regex) self.device_groups = filter(re_filter.search, self.device_groups) def get_list(self): return self.device_groups def get_all_preferred_active(self): return self.api.Management.DeviceGroup.get_all_preferred_active(self.device_groups) def get_autosync_enabled_state(self): return self.api.Management.DeviceGroup.get_autosync_enabled_state(self.device_groups) def get_description(self): return self.api.Management.DeviceGroup.get_description(self.device_groups) def get_device(self): return self.api.Management.DeviceGroup.get_device(self.device_groups) def get_full_load_on_sync_state(self): return self.api.Management.DeviceGroup.get_full_load_on_sync_state(self.device_groups) def get_incremental_config_sync_size_maximum(self): return self.api.Management.DeviceGroup.get_incremental_config_sync_size_maximum(self.device_groups) def get_network_failover_enabled_state(self): return self.api.Management.DeviceGroup.get_network_failover_enabled_state(self.device_groups) def get_sync_status(self): return self.api.Management.DeviceGroup.get_sync_status(self.device_groups) def get_type(self): return self.api.Management.DeviceGroup.get_type(self.device_groups) class TrafficGroups(object): """Traffic groups class. F5 BIG-IP traffic groups class. Attributes: api: iControl API instance. traffic_groups: List of traffic groups. """ def __init__(self, api, regex=None): self.api = api self.traffic_groups = api.Management.TrafficGroup.get_list() if regex: re_filter = re.compile(regex) self.traffic_groups = filter(re_filter.search, self.traffic_groups) def get_list(self): return self.traffic_groups def get_auto_failback_enabled_state(self): return self.api.Management.TrafficGroup.get_auto_failback_enabled_state(self.traffic_groups) def get_auto_failback_time(self): return self.api.Management.TrafficGroup.get_auto_failback_time(self.traffic_groups) def get_default_device(self): return self.api.Management.TrafficGroup.get_default_device(self.traffic_groups) def get_description(self): return self.api.Management.TrafficGroup.get_description(self.traffic_groups) def get_ha_load_factor(self): return self.api.Management.TrafficGroup.get_ha_load_factor(self.traffic_groups) def get_ha_order(self): return self.api.Management.TrafficGroup.get_ha_order(self.traffic_groups) def get_is_floating(self): return self.api.Management.TrafficGroup.get_is_floating(self.traffic_groups) def get_mac_masquerade_address(self): return self.api.Management.TrafficGroup.get_mac_masquerade_address(self.traffic_groups) def get_unit_id(self): return self.api.Management.TrafficGroup.get_unit_id(self.traffic_groups) class Rules(object): """Rules class. F5 BIG-IP iRules class. Attributes: api: iControl API instance. rules: List of iRules. """ def __init__(self, api, regex=None): self.api = api self.rules = api.LocalLB.Rule.get_list() if regex: re_filter = re.compile(regex) self.traffic_groups = filter(re_filter.search, self.rules) def get_list(self): return self.rules def get_description(self): return self.api.LocalLB.Rule.get_description(rule_names=self.rules) def get_ignore_vertification(self): return self.api.LocalLB.Rule.get_ignore_vertification(rule_names=self.rules) def get_verification_status(self): return self.api.LocalLB.Rule.get_verification_status_v2(rule_names=self.rules) def get_definition(self): return [x['rule_definition'] for x in self.api.LocalLB.Rule.query_rule(rule_names=self.rules)] class Nodes(object): """Nodes class. F5 BIG-IP nodes class. Attributes: api: iControl API instance. nodes: List of nodes. """ def __init__(self, api, regex=None): self.api = api self.nodes = api.LocalLB.NodeAddressV2.get_list() if regex: re_filter = re.compile(regex) self.nodes = filter(re_filter.search, self.nodes) def get_list(self): return self.nodes def get_address(self): return self.api.LocalLB.NodeAddressV2.get_address(nodes=self.nodes) def get_name(self): return [x[x.rfind('/') + 1:] for x in self.nodes] def get_connection_limit(self): return self.api.LocalLB.NodeAddressV2.get_connection_limit(nodes=self.nodes) def get_description(self): return self.api.LocalLB.NodeAddressV2.get_description(nodes=self.nodes) def get_dynamic_ratio(self): return self.api.LocalLB.NodeAddressV2.get_dynamic_ratio_v2(nodes=self.nodes) def get_monitor_instance(self): return self.api.LocalLB.NodeAddressV2.get_monitor_instance(nodes=self.nodes) def get_monitor_rule(self): return self.api.LocalLB.NodeAddressV2.get_monitor_rule(nodes=self.nodes) def get_monitor_status(self): return self.api.LocalLB.NodeAddressV2.get_monitor_status(nodes=self.nodes) def get_object_status(self): return self.api.LocalLB.NodeAddressV2.get_object_status(nodes=self.nodes) def get_rate_limit(self): return self.api.LocalLB.NodeAddressV2.get_rate_limit(nodes=self.nodes) def get_ratio(self): return self.api.LocalLB.NodeAddressV2.get_ratio(nodes=self.nodes) def get_session_status(self): return self.api.LocalLB.NodeAddressV2.get_session_status(nodes=self.nodes) class VirtualAddresses(object): """Virtual addresses class. F5 BIG-IP virtual addresses class. Attributes: api: iControl API instance. virtual_addresses: List of virtual addresses. """ def __init__(self, api, regex=None): self.api = api self.virtual_addresses = api.LocalLB.VirtualAddressV2.get_list() if regex: re_filter = re.compile(regex) self.virtual_addresses = filter(re_filter.search, self.virtual_addresses) def get_list(self): return self.virtual_addresses def get_address(self): return self.api.LocalLB.VirtualAddressV2.get_address(self.virtual_addresses) def get_arp_state(self): return self.api.LocalLB.VirtualAddressV2.get_arp_state(self.virtual_addresses) def get_auto_delete_state(self): return self.api.LocalLB.VirtualAddressV2.get_auto_delete_state(self.virtual_addresses) def get_connection_limit(self): return self.api.LocalLB.VirtualAddressV2.get_connection_limit(self.virtual_addresses) def get_description(self): return self.api.LocalLB.VirtualAddressV2.get_description(self.virtual_addresses) def get_enabled_state(self): return self.api.LocalLB.VirtualAddressV2.get_enabled_state(self.virtual_addresses) def get_icmp_echo_state(self): return self.api.LocalLB.VirtualAddressV2.get_icmp_echo_state(self.virtual_addresses) def get_is_floating_state(self): return self.api.LocalLB.VirtualAddressV2.get_is_floating_state(self.virtual_addresses) def get_netmask(self): return self.api.LocalLB.VirtualAddressV2.get_netmask(self.virtual_addresses) def get_object_status(self): return self.api.LocalLB.VirtualAddressV2.get_object_status(self.virtual_addresses) def get_route_advertisement_state(self): return self.api.LocalLB.VirtualAddressV2.get_route_advertisement_state(self.virtual_addresses) def get_traffic_group(self): return self.api.LocalLB.VirtualAddressV2.get_traffic_group(self.virtual_addresses) class AddressClasses(object): """Address group/class class. F5 BIG-IP address group/class class. In TMUI these things are known as Address Data Groups. Examples that ship with the box include /Common/aol and /Common/private_net Attributes: api: iControl API instance. address_classes: List of address classes. """ def __init__(self, api, regex=None): self.api = api self.address_classes = api.LocalLB.Class.get_address_class_list() if regex: re_filter = re.compile(regex) self.address_classes = filter(re_filter.search, self.address_classes) def get_list(self): return self.address_classes def get_address_class(self): key = self.api.LocalLB.Class.get_address_class(self.address_classes) value = self.api.LocalLB.Class.get_address_class_member_data_value(key) result = [] for idx, v in enumerate(key): for idx2, member in enumerate(v['members']): dg_value = dict( value=value[idx][idx2] ) dg_value.update(member) result.append(dg_value) return result def get_description(self): return self.api.LocalLB.Class.get_description(self.address_classes) class Certificates(object): """Certificates class. F5 BIG-IP certificates class. Attributes: api: iControl API instance. certificates: List of certificate identifiers. certificate_list: List of certificate information structures. """ def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"): self.api = api self.certificate_list = api.Management.KeyCertificate.get_certificate_list(mode=mode) self.certificates = [x['certificate']['cert_info']['id'] for x in self.certificate_list] if regex: re_filter = re.compile(regex) self.certificates = filter(re_filter.search, self.certificates) self.certificate_list = [x for x in self.certificate_list if x['certificate']['cert_info']['id'] in self.certificates] def get_list(self): return self.certificates def get_certificate_list(self): return self.certificate_list class Keys(object): """Keys class. F5 BIG-IP keys class. Attributes: api: iControl API instance. keys: List of key identifiers. key_list: List of key information structures. """ def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"): self.api = api self.key_list = api.Management.KeyCertificate.get_key_list(mode=mode) self.keys = [x['key_info']['id'] for x in self.key_list] if regex: re_filter = re.compile(regex) self.keys = filter(re_filter.search, self.keys) self.key_list = [x for x in self.key_list if x['key_info']['id'] in self.keys] def get_list(self): return self.keys def get_key_list(self): return self.key_list class ProfileClientSSL(object): """Client SSL profiles class. F5 BIG-IP client SSL profiles class. Attributes: api: iControl API instance. profiles: List of client SSL profiles. """ def __init__(self, api, regex=None): self.api = api self.profiles = api.LocalLB.ProfileClientSSL.get_list() if regex: re_filter = re.compile(regex) self.profiles = filter(re_filter.search, self.profiles) def get_list(self): return self.profiles def get_alert_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_alert_timeout(self.profiles) def get_allow_nonssl_state(self): return self.api.LocalLB.ProfileClientSSL.get_allow_nonssl_state(self.profiles) def get_authenticate_depth(self): return self.api.LocalLB.ProfileClientSSL.get_authenticate_depth(self.profiles) def get_authenticate_once_state(self): return self.api.LocalLB.ProfileClientSSL.get_authenticate_once_state(self.profiles) def get_ca_file(self): return self.api.LocalLB.ProfileClientSSL.get_ca_file_v2(self.profiles) def get_cache_size(self): return self.api.LocalLB.ProfileClientSSL.get_cache_size(self.profiles) def get_cache_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_cache_timeout(self.profiles) def get_certificate_file(self): return self.api.LocalLB.ProfileClientSSL.get_certificate_file_v2(self.profiles) def get_chain_file(self): return self.api.LocalLB.ProfileClientSSL.get_chain_file_v2(self.profiles) def get_cipher_list(self): return self.api.LocalLB.ProfileClientSSL.get_cipher_list(self.profiles) def get_client_certificate_ca_file(self): return self.api.LocalLB.ProfileClientSSL.get_client_certificate_ca_file_v2(self.profiles) def get_crl_file(self): return self.api.LocalLB.ProfileClientSSL.get_crl_file_v2(self.profiles) def get_default_profile(self): return self.api.LocalLB.ProfileClientSSL.get_default_profile(self.profiles) def get_description(self): return self.api.LocalLB.ProfileClientSSL.get_description(self.profiles) def get_forward_proxy_ca_certificate_file(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_certificate_file(self.profiles) def get_forward_proxy_ca_key_file(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_key_file(self.profiles) def get_forward_proxy_ca_passphrase(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_passphrase(self.profiles) def get_forward_proxy_certificate_extension_include(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_extension_include(self.profiles) def get_forward_proxy_certificate_lifespan(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_lifespan(self.profiles) def get_forward_proxy_enabled_state(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_enabled_state(self.profiles) def get_forward_proxy_lookup_by_ipaddr_port_state(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_lookup_by_ipaddr_port_state(self.profiles) def get_handshake_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_handshake_timeout(self.profiles) def get_key_file(self): return self.api.LocalLB.ProfileClientSSL.get_key_file_v2(self.profiles) def get_modssl_emulation_state(self): return self.api.LocalLB.ProfileClientSSL.get_modssl_emulation_state(self.profiles) def get_passphrase(self): return self.api.LocalLB.ProfileClientSSL.get_passphrase(self.profiles) def get_peer_certification_mode(self): return self.api.LocalLB.ProfileClientSSL.get_peer_certification_mode(self.profiles) def get_profile_mode(self): return self.api.LocalLB.ProfileClientSSL.get_profile_mode(self.profiles) def get_renegotiation_maximum_record_delay(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_maximum_record_delay(self.profiles) def get_renegotiation_period(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_period(self.profiles) def get_renegotiation_state(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_state(self.profiles) def get_renegotiation_throughput(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_throughput(self.profiles) def get_retain_certificate_state(self): return self.api.LocalLB.ProfileClientSSL.get_retain_certificate_state(self.profiles) def get_secure_renegotiation_mode(self): return self.api.LocalLB.ProfileClientSSL.get_secure_renegotiation_mode(self.profiles) def get_server_name(self): return self.api.LocalLB.ProfileClientSSL.get_server_name(self.profiles) def get_session_ticket_state(self): return self.api.LocalLB.ProfileClientSSL.get_session_ticket_state(self.profiles) def get_sni_default_state(self): return self.api.LocalLB.ProfileClientSSL.get_sni_default_state(self.profiles) def get_sni_require_state(self): return self.api.LocalLB.ProfileClientSSL.get_sni_require_state(self.profiles) def get_ssl_option(self): return self.api.LocalLB.ProfileClientSSL.get_ssl_option(self.profiles) def get_strict_resume_state(self): return self.api.LocalLB.ProfileClientSSL.get_strict_resume_state(self.profiles) def get_unclean_shutdown_state(self): return self.api.LocalLB.ProfileClientSSL.get_unclean_shutdown_state(self.profiles) def get_is_base_profile(self): return self.api.LocalLB.ProfileClientSSL.is_base_profile(self.profiles) def get_is_system_profile(self): return self.api.LocalLB.ProfileClientSSL.is_system_profile(self.profiles) class SystemInfo(object): """System information class. F5 BIG-IP system information class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_base_mac_address(self): return self.api.System.SystemInfo.get_base_mac_address() def get_blade_temperature(self): return self.api.System.SystemInfo.get_blade_temperature() def get_chassis_slot_information(self): return self.api.System.SystemInfo.get_chassis_slot_information() def get_globally_unique_identifier(self): return self.api.System.SystemInfo.get_globally_unique_identifier() def get_group_id(self): return self.api.System.SystemInfo.get_group_id() def get_hardware_information(self): return self.api.System.SystemInfo.get_hardware_information() def get_marketing_name(self): return self.api.System.SystemInfo.get_marketing_name() def get_product_information(self): return self.api.System.SystemInfo.get_product_information() def get_pva_version(self): return self.api.System.SystemInfo.get_pva_version() def get_system_id(self): return self.api.System.SystemInfo.get_system_id() def get_system_information(self): return self.api.System.SystemInfo.get_system_information() def get_time(self): return self.api.System.SystemInfo.get_time() def get_time_zone(self): return self.api.System.SystemInfo.get_time_zone() def get_uptime(self): return self.api.System.SystemInfo.get_uptime() class ProvisionInfo(object): """Provision information class. F5 BIG-IP provision information class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_list(self): result = [] list = self.api.Management.Provision.get_list() for item in list: item = item.lower().replace('tmos_module_', '') result.append(item) return result def get_provisioned_list(self): result = [] list = self.api.Management.Provision.get_provisioned_list() for item in list: item = item.lower().replace('tmos_module_', '') result.append(item) return result def generate_dict(api_obj, fields): result_dict = {} lists = [] supported_fields = [] if api_obj.get_list(): for field in fields: try: api_response = getattr(api_obj, "get_" + field)() except (MethodNotFound, WebFault): pass else: lists.append(api_response) supported_fields.append(field) for i, j in enumerate(api_obj.get_list()): temp = {} temp.update([(item[0], item[1][i]) for item in zip(supported_fields, lists)]) result_dict[j] = temp return result_dict def generate_simple_dict(api_obj, fields): result_dict = {} for field in fields: try: api_response = getattr(api_obj, "get_" + field)() except (MethodNotFound, WebFault): pass else: result_dict[field] = api_response return result_dict def generate_interface_dict(f5, regex): interfaces = Interfaces(f5.get_api(), regex) fields = ['active_media', 'actual_flow_control', 'bundle_state', 'description', 'dual_media_state', 'enabled_state', 'if_index', 'learning_mode', 'lldp_admin_status', 'lldp_tlvmap', 'mac_address', 'media', 'media_option', 'media_option_sfp', 'media_sfp', 'media_speed', 'media_status', 'mtu', 'phy_master_slave_mode', 'prefer_sfp_state', 'flow_control', 'sflow_poll_interval', 'sflow_poll_interval_global', 'sfp_media_state', 'stp_active_edge_port_state', 'stp_enabled_state', 'stp_link_type', 'stp_protocol_detection_reset_state'] return generate_dict(interfaces, fields) def generate_self_ip_dict(f5, regex): self_ips = SelfIPs(f5.get_api(), regex) fields = ['address', 'allow_access_list', 'description', 'enforced_firewall_policy', 'floating_state', 'fw_rule', 'netmask', 'staged_firewall_policy', 'traffic_group', 'vlan', 'is_traffic_group_inherited'] return generate_dict(self_ips, fields) def generate_trunk_dict(f5, regex): trunks = Trunks(f5.get_api(), regex) fields = ['active_lacp_state', 'configured_member_count', 'description', 'distribution_hash_option', 'interface', 'lacp_enabled_state', 'lacp_timeout_option', 'link_selection_policy', 'media_speed', 'media_status', 'operational_member_count', 'stp_enabled_state', 'stp_protocol_detection_reset_state'] return generate_dict(trunks, fields) def generate_vlan_dict(f5, regex): vlans = Vlans(f5.get_api(), regex) fields = ['auto_lasthop', 'cmp_hash_algorithm', 'description', 'dynamic_forwarding', 'failsafe_action', 'failsafe_state', 'failsafe_timeout', 'if_index', 'learning_mode', 'mac_masquerade_address', 'member', 'mtu', 'sflow_poll_interval', 'sflow_poll_interval_global', 'sflow_sampling_rate', 'sflow_sampling_rate_global', 'source_check_state', 'true_mac_address', 'vlan_id'] return generate_dict(vlans, fields) def generate_vs_dict(f5, regex): virtual_servers = VirtualServers(f5.get_api(), regex) fields = ['actual_hardware_acceleration', 'authentication_profile', 'auto_lasthop', 'bw_controller_policy', 'clone_pool', 'cmp_enable_mode', 'connection_limit', 'connection_mirror_state', 'default_pool_name', 'description', 'destination', 'enabled_state', 'enforced_firewall_policy', 'fallback_persistence_profile', 'fw_rule', 'gtm_score', 'last_hop_pool', 'nat64_state', 'object_status', 'persistence_profile', 'profile', 'protocol', 'rate_class', 'rate_limit', 'rate_limit_destination_mask', 'rate_limit_mode', 'rate_limit_source_mask', 'related_rule', 'rule', 'security_log_profile', 'snat_pool', 'snat_type', 'source_address', 'source_address_translation_lsn_pool', 'source_address_translation_snat_pool', 'source_address_translation_type', 'source_port_behavior', 'staged_firewall_policy', 'translate_address_state', 'translate_port_state', 'type', 'vlan', 'wildmask', 'name'] return generate_dict(virtual_servers, fields) def generate_pool_dict(f5, regex): pools = Pools(f5.get_api(), regex) fields = ['action_on_service_down', 'active_member_count', 'aggregate_dynamic_ratio', 'allow_nat_state', 'allow_snat_state', 'client_ip_tos', 'client_link_qos', 'description', 'gateway_failsafe_device', 'ignore_persisted_weight_state', 'lb_method', 'member', 'minimum_active_member', 'minimum_up_member', 'minimum_up_member_action', 'minimum_up_member_enabled_state', 'monitor_association', 'monitor_instance', 'object_status', 'profile', 'queue_depth_limit', 'queue_on_connection_limit_state', 'queue_time_limit', 'reselect_tries', 'server_ip_tos', 'server_link_qos', 'simple_timeout', 'slow_ramp_time', 'name'] return generate_dict(pools, fields) def generate_device_dict(f5, regex): devices = Devices(f5.get_api(), regex) fields = ['active_modules', 'base_mac_address', 'blade_addresses', 'build', 'chassis_id', 'chassis_type', 'comment', 'configsync_address', 'contact', 'description', 'edition', 'failover_state', 'hostname', 'inactive_modules', 'location', 'management_address', 'marketing_name', 'multicast_address', 'optional_modules', 'platform_id', 'primary_mirror_address', 'product', 'secondary_mirror_address', 'software_version', 'timelimited_modules', 'timezone', 'unicast_addresses'] return generate_dict(devices, fields) def generate_device_group_dict(f5, regex): device_groups = DeviceGroups(f5.get_api(), regex) fields = ['all_preferred_active', 'autosync_enabled_state', 'description', 'device', 'full_load_on_sync_state', 'incremental_config_sync_size_maximum', 'network_failover_enabled_state', 'sync_status', 'type'] return generate_dict(device_groups, fields) def generate_traffic_group_dict(f5, regex): traffic_groups = TrafficGroups(f5.get_api(), regex) fields = ['auto_failback_enabled_state', 'auto_failback_time', 'default_device', 'description', 'ha_load_factor', 'ha_order', 'is_floating', 'mac_masquerade_address', 'unit_id'] return generate_dict(traffic_groups, fields) def generate_rule_dict(f5, regex): rules = Rules(f5.get_api(), regex) fields = ['definition', 'description', 'ignore_vertification', 'verification_status'] return generate_dict(rules, fields) def generate_node_dict(f5, regex): nodes = Nodes(f5.get_api(), regex) fields = ['name', 'address', 'connection_limit', 'description', 'dynamic_ratio', 'monitor_instance', 'monitor_rule', 'monitor_status', 'object_status', 'rate_limit', 'ratio', 'session_status'] return generate_dict(nodes, fields) def generate_virtual_address_dict(f5, regex): virtual_addresses = VirtualAddresses(f5.get_api(), regex) fields = ['address', 'arp_state', 'auto_delete_state', 'connection_limit', 'description', 'enabled_state', 'icmp_echo_state', 'is_floating_state', 'netmask', 'object_status', 'route_advertisement_state', 'traffic_group'] return generate_dict(virtual_addresses, fields) def generate_address_class_dict(f5, regex): address_classes = AddressClasses(f5.get_api(), regex) fields = ['address_class', 'description'] return generate_dict(address_classes, fields) def generate_certificate_dict(f5, regex): certificates = Certificates(f5.get_api(), regex) return dict(zip(certificates.get_list(), certificates.get_certificate_list())) def generate_key_dict(f5, regex): keys = Keys(f5.get_api(), regex) return dict(zip(keys.get_list(), keys.get_key_list())) def generate_client_ssl_profile_dict(f5, regex): profiles = ProfileClientSSL(f5.get_api(), regex) fields = ['alert_timeout', 'allow_nonssl_state', 'authenticate_depth', 'authenticate_once_state', 'ca_file', 'cache_size', 'cache_timeout', 'certificate_file', 'chain_file', 'cipher_list', 'client_certificate_ca_file', 'crl_file', 'default_profile', 'description', 'forward_proxy_ca_certificate_file', 'forward_proxy_ca_key_file', 'forward_proxy_ca_passphrase', 'forward_proxy_certificate_extension_include', 'forward_proxy_certificate_lifespan', 'forward_proxy_enabled_state', 'forward_proxy_lookup_by_ipaddr_port_state', 'handshake_timeout', 'key_file', 'modssl_emulation_state', 'passphrase', 'peer_certification_mode', 'profile_mode', 'renegotiation_maximum_record_delay', 'renegotiation_period', 'renegotiation_state', 'renegotiation_throughput', 'retain_certificate_state', 'secure_renegotiation_mode', 'server_name', 'session_ticket_state', 'sni_default_state', 'sni_require_state', 'ssl_option', 'strict_resume_state', 'unclean_shutdown_state', 'is_base_profile', 'is_system_profile'] return generate_dict(profiles, fields) def generate_system_info_dict(f5): system_info = SystemInfo(f5.get_api()) fields = ['base_mac_address', 'blade_temperature', 'chassis_slot_information', 'globally_unique_identifier', 'group_id', 'hardware_information', 'marketing_name', 'product_information', 'pva_version', 'system_id', 'system_information', 'time', 'time_zone', 'uptime'] return generate_simple_dict(system_info, fields) def generate_software_list(f5): software = Software(f5.get_api()) software_list = software.get_all_software_status() return software_list def generate_provision_dict(f5): provisioned = ProvisionInfo(f5.get_api()) fields = ['list', 'provisioned_list'] return generate_simple_dict(provisioned, fields) def main(): argument_spec = f5_argument_spec meta_args = dict( session=dict(type='bool', default='no'), include=dict( type='raw', required=True, choices=[ 'address_class', 'certificate', 'client_ssl_profile', 'device', 'device_group', 'interface', 'key', 'node', 'pool', 'provision', 'rule', 'self_ip', 'software', 'system_info', 'traffic_group', 'trunk', 'virtual_address', 'virtual_server', 'vlan' ] ), filter=dict(type='str'), ) argument_spec.update(meta_args) module = AnsibleModule( argument_spec=argument_spec ) if not bigsuds_found: module.fail_json(msg="the python suds and bigsuds modules are required") server = module.params['server'] server_port = module.params['server_port'] user = module.params['user'] password = module.params['password'] validate_certs = module.params['validate_certs'] session = module.params['session'] fact_filter = module.params['filter'] if validate_certs: import ssl if not hasattr(ssl, 'SSLContext'): module.fail_json( msg='bigsuds does not support verifying certificates with python < 2.7.9. Either update python or set validate_certs=False on the task' ) if fact_filter: regex = fnmatch.translate(fact_filter) else: regex = None if isinstance(module.params['include'], string_types): includes = module.params['include'].split(',') else: includes = module.params['include'] include = [x.lower() for x in includes] valid_includes = ('address_class', 'certificate', 'client_ssl_profile', 'device', 'device_group', 'interface', 'key', 'node', 'pool', 'provision', 'rule', 'self_ip', 'software', 'system_info', 'traffic_group', 'trunk', 'virtual_address', 'virtual_server', 'vlan') include_test = (x in valid_includes for x in include) if not all(include_test): module.fail_json(msg="Value of include must be one or more of: %s, got: %s" % (",".join(valid_includes), ",".join(include))) try: facts = {} if len(include) > 0: f5 = F5(server, user, password, session, validate_certs, server_port) saved_active_folder = f5.get_active_folder() saved_recursive_query_state = f5.get_recursive_query_state() if saved_active_folder != "/": f5.set_active_folder("/") if saved_recursive_query_state != "STATE_ENABLED": f5.enable_recursive_query_state() if 'interface' in include: facts['interface'] = generate_interface_dict(f5, regex) if 'self_ip' in include: facts['self_ip'] = generate_self_ip_dict(f5, regex) if 'trunk' in include: facts['trunk'] = generate_trunk_dict(f5, regex) if 'vlan' in include: facts['vlan'] = generate_vlan_dict(f5, regex) if 'virtual_server' in include: facts['virtual_server'] = generate_vs_dict(f5, regex) if 'pool' in include: facts['pool'] = generate_pool_dict(f5, regex) if 'provision' in include: facts['provision'] = generate_provision_dict(f5) if 'device' in include: facts['device'] = generate_device_dict(f5, regex) if 'device_group' in include: facts['device_group'] = generate_device_group_dict(f5, regex) if 'traffic_group' in include: facts['traffic_group'] = generate_traffic_group_dict(f5, regex) if 'rule' in include: facts['rule'] = generate_rule_dict(f5, regex) if 'node' in include: facts['node'] = generate_node_dict(f5, regex) if 'virtual_address' in include: facts['virtual_address'] = generate_virtual_address_dict(f5, regex) if 'address_class' in include: facts['address_class'] = generate_address_class_dict(f5, regex) if 'software' in include: facts['software'] = generate_software_list(f5) if 'certificate' in include: facts['certificate'] = generate_certificate_dict(f5, regex) if 'key' in include: facts['key'] = generate_key_dict(f5, regex) if 'client_ssl_profile' in include: facts['client_ssl_profile'] = generate_client_ssl_profile_dict(f5, regex) if 'system_info' in include: facts['system_info'] = generate_system_info_dict(f5) # restore saved state if saved_active_folder and saved_active_folder != "/": f5.set_active_folder(saved_active_folder) if saved_recursive_query_state and \ saved_recursive_query_state != "STATE_ENABLED": f5.set_recursive_query_state(saved_recursive_query_state) result = dict( ansible_facts=facts, ) result.update(**facts) except Exception as e: module.fail_json(msg="received exception: %s\ntraceback: %s" % (e, traceback.format_exc())) module.exit_json(**result) if __name__ == '__main__': main() added deprecation note #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # Copyright (c) 2013 Matt Hite <mhite@hotmail.com> # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: bigip_facts short_description: Collect facts from F5 BIG-IP devices description: - Collect facts from F5 BIG-IP devices via iControl SOAP API version_added: 1.6 author: - Matt Hite (@mhite) - Tim Rupp (@caphrim007) notes: - Requires BIG-IP software version >= 11.4 - F5 developed module 'bigsuds' required (see http://devcentral.f5.com) - Best run as a local_action in your playbook - Tested with manager and above account privilege level - C(provision) facts were added in 2.2 - This module is deprecated. Use the C(bigip_device_facts) module instead. requirements: - bigsuds options: session: description: - BIG-IP session support; may be useful to avoid concurrency issues in certain circumstances. default: no type: bool include: description: - Fact category or list of categories to collect required: True choices: - address_class - certificate - client_ssl_profile - device - device_group - interface - key - node - pool - provision - rule - self_ip - software - system_info - traffic_group - trunk - virtual_address - virtual_server - vlan filter: description: - Shell-style glob matching string used to filter fact keys. Not applicable for software, provision, and system_info fact categories. extends_documentation_fragment: f5 ''' EXAMPLES = r''' - name: Collect BIG-IP facts bigip_facts: server: lb.mydomain.com user: admin password: secret include: - interface - vlan delegate_to: localhost ''' import fnmatch import re import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import string_types from ansible.module_utils.six.moves import map, zip try: from library.module_utils.network.f5.legacy import bigip_api, bigsuds_found from library.module_utils.network.f5.common import f5_argument_spec except ImportError: from ansible.module_utils.network.f5.legacy import bigip_api, bigsuds_found from ansible.module_utils.network.f5.common import f5_argument_spec try: from suds import MethodNotFound, WebFault except ImportError: pass # Handle via f5_utils.bigsuds_found class F5(object): """F5 iControl class. F5 BIG-IP iControl API class. Attributes: api: iControl API instance. """ def __init__(self, host, user, password, session=False, validate_certs=True, port=443): self.api = bigip_api(host, user, password, validate_certs, port) if session: self.start_session() def start_session(self): self.api = self.api.with_session_id() def get_api(self): return self.api def set_recursive_query_state(self, state): self.api.System.Session.set_recursive_query_state(state) def get_recursive_query_state(self): return self.api.System.Session.get_recursive_query_state() def enable_recursive_query_state(self): self.set_recursive_query_state('STATE_ENABLED') def disable_recursive_query_state(self): self.set_recursive_query_state('STATE_DISABLED') def set_active_folder(self, folder): self.api.System.Session.set_active_folder(folder=folder) def get_active_folder(self): return self.api.System.Session.get_active_folder() class Interfaces(object): """Interfaces class. F5 BIG-IP interfaces class. Attributes: api: iControl API instance. interfaces: A list of BIG-IP interface names. """ def __init__(self, api, regex=None): self.api = api self.interfaces = api.Networking.Interfaces.get_list() if regex: re_filter = re.compile(regex) self.interfaces = filter(re_filter.search, self.interfaces) def get_list(self): return self.interfaces def get_active_media(self): return self.api.Networking.Interfaces.get_active_media(self.interfaces) def get_actual_flow_control(self): return self.api.Networking.Interfaces.get_actual_flow_control(self.interfaces) def get_bundle_state(self): return self.api.Networking.Interfaces.get_bundle_state(self.interfaces) def get_description(self): return self.api.Networking.Interfaces.get_description(self.interfaces) def get_dual_media_state(self): return self.api.Networking.Interfaces.get_dual_media_state(self.interfaces) def get_enabled_state(self): return self.api.Networking.Interfaces.get_enabled_state(self.interfaces) def get_if_index(self): return self.api.Networking.Interfaces.get_if_index(self.interfaces) def get_learning_mode(self): return self.api.Networking.Interfaces.get_learning_mode(self.interfaces) def get_lldp_admin_status(self): return self.api.Networking.Interfaces.get_lldp_admin_status(self.interfaces) def get_lldp_tlvmap(self): return self.api.Networking.Interfaces.get_lldp_tlvmap(self.interfaces) def get_mac_address(self): return self.api.Networking.Interfaces.get_mac_address(self.interfaces) def get_media(self): return self.api.Networking.Interfaces.get_media(self.interfaces) def get_media_option(self): return self.api.Networking.Interfaces.get_media_option(self.interfaces) def get_media_option_sfp(self): return self.api.Networking.Interfaces.get_media_option_sfp(self.interfaces) def get_media_sfp(self): return self.api.Networking.Interfaces.get_media_sfp(self.interfaces) def get_media_speed(self): return self.api.Networking.Interfaces.get_media_speed(self.interfaces) def get_media_status(self): return self.api.Networking.Interfaces.get_media_status(self.interfaces) def get_mtu(self): return self.api.Networking.Interfaces.get_mtu(self.interfaces) def get_phy_master_slave_mode(self): return self.api.Networking.Interfaces.get_phy_master_slave_mode(self.interfaces) def get_prefer_sfp_state(self): return self.api.Networking.Interfaces.get_prefer_sfp_state(self.interfaces) def get_flow_control(self): return self.api.Networking.Interfaces.get_requested_flow_control(self.interfaces) def get_sflow_poll_interval(self): return self.api.Networking.Interfaces.get_sflow_poll_interval(self.interfaces) def get_sflow_poll_interval_global(self): return self.api.Networking.Interfaces.get_sflow_poll_interval_global(self.interfaces) def get_sfp_media_state(self): return self.api.Networking.Interfaces.get_sfp_media_state(self.interfaces) def get_stp_active_edge_port_state(self): return self.api.Networking.Interfaces.get_stp_active_edge_port_state(self.interfaces) def get_stp_enabled_state(self): return self.api.Networking.Interfaces.get_stp_enabled_state(self.interfaces) def get_stp_link_type(self): return self.api.Networking.Interfaces.get_stp_link_type(self.interfaces) def get_stp_protocol_detection_reset_state(self): return self.api.Networking.Interfaces.get_stp_protocol_detection_reset_state(self.interfaces) class SelfIPs(object): """Self IPs class. F5 BIG-IP Self IPs class. Attributes: api: iControl API instance. self_ips: List of self IPs. """ def __init__(self, api, regex=None): self.api = api self.self_ips = api.Networking.SelfIPV2.get_list() if regex: re_filter = re.compile(regex) self.self_ips = filter(re_filter.search, self.self_ips) def get_list(self): return self.self_ips def get_address(self): return self.api.Networking.SelfIPV2.get_address(self.self_ips) def get_allow_access_list(self): return self.api.Networking.SelfIPV2.get_allow_access_list(self.self_ips) def get_description(self): return self.api.Networking.SelfIPV2.get_description(self.self_ips) def get_enforced_firewall_policy(self): return self.api.Networking.SelfIPV2.get_enforced_firewall_policy(self.self_ips) def get_floating_state(self): return self.api.Networking.SelfIPV2.get_floating_state(self.self_ips) def get_fw_rule(self): return self.api.Networking.SelfIPV2.get_fw_rule(self.self_ips) def get_netmask(self): return self.api.Networking.SelfIPV2.get_netmask(self.self_ips) def get_staged_firewall_policy(self): return self.api.Networking.SelfIPV2.get_staged_firewall_policy(self.self_ips) def get_traffic_group(self): return self.api.Networking.SelfIPV2.get_traffic_group(self.self_ips) def get_vlan(self): return self.api.Networking.SelfIPV2.get_vlan(self.self_ips) def get_is_traffic_group_inherited(self): return self.api.Networking.SelfIPV2.is_traffic_group_inherited(self.self_ips) class Trunks(object): """Trunks class. F5 BIG-IP trunks class. Attributes: api: iControl API instance. trunks: List of trunks. """ def __init__(self, api, regex=None): self.api = api self.trunks = api.Networking.Trunk.get_list() if regex: re_filter = re.compile(regex) self.trunks = filter(re_filter.search, self.trunks) def get_list(self): return self.trunks def get_active_lacp_state(self): return self.api.Networking.Trunk.get_active_lacp_state(self.trunks) def get_configured_member_count(self): return self.api.Networking.Trunk.get_configured_member_count(self.trunks) def get_description(self): return self.api.Networking.Trunk.get_description(self.trunks) def get_distribution_hash_option(self): return self.api.Networking.Trunk.get_distribution_hash_option(self.trunks) def get_interface(self): return self.api.Networking.Trunk.get_interface(self.trunks) def get_lacp_enabled_state(self): return self.api.Networking.Trunk.get_lacp_enabled_state(self.trunks) def get_lacp_timeout_option(self): return self.api.Networking.Trunk.get_lacp_timeout_option(self.trunks) def get_link_selection_policy(self): return self.api.Networking.Trunk.get_link_selection_policy(self.trunks) def get_media_speed(self): return self.api.Networking.Trunk.get_media_speed(self.trunks) def get_media_status(self): return self.api.Networking.Trunk.get_media_status(self.trunks) def get_operational_member_count(self): return self.api.Networking.Trunk.get_operational_member_count(self.trunks) def get_stp_enabled_state(self): return self.api.Networking.Trunk.get_stp_enabled_state(self.trunks) def get_stp_protocol_detection_reset_state(self): return self.api.Networking.Trunk.get_stp_protocol_detection_reset_state(self.trunks) class Vlans(object): """Vlans class. F5 BIG-IP Vlans class. Attributes: api: iControl API instance. vlans: List of VLANs. """ def __init__(self, api, regex=None): self.api = api self.vlans = api.Networking.VLAN.get_list() if regex: re_filter = re.compile(regex) self.vlans = filter(re_filter.search, self.vlans) def get_list(self): return self.vlans def get_auto_lasthop(self): return self.api.Networking.VLAN.get_auto_lasthop(self.vlans) def get_cmp_hash_algorithm(self): return self.api.Networking.VLAN.get_cmp_hash_algorithm(self.vlans) def get_description(self): return self.api.Networking.VLAN.get_description(self.vlans) def get_dynamic_forwarding(self): return self.api.Networking.VLAN.get_dynamic_forwarding(self.vlans) def get_failsafe_action(self): return self.api.Networking.VLAN.get_failsafe_action(self.vlans) def get_failsafe_state(self): return self.api.Networking.VLAN.get_failsafe_state(self.vlans) def get_failsafe_timeout(self): return self.api.Networking.VLAN.get_failsafe_timeout(self.vlans) def get_if_index(self): return self.api.Networking.VLAN.get_if_index(self.vlans) def get_learning_mode(self): return self.api.Networking.VLAN.get_learning_mode(self.vlans) def get_mac_masquerade_address(self): return self.api.Networking.VLAN.get_mac_masquerade_address(self.vlans) def get_member(self): return self.api.Networking.VLAN.get_member(self.vlans) def get_mtu(self): return self.api.Networking.VLAN.get_mtu(self.vlans) def get_sflow_poll_interval(self): return self.api.Networking.VLAN.get_sflow_poll_interval(self.vlans) def get_sflow_poll_interval_global(self): return self.api.Networking.VLAN.get_sflow_poll_interval_global(self.vlans) def get_sflow_sampling_rate(self): return self.api.Networking.VLAN.get_sflow_sampling_rate(self.vlans) def get_sflow_sampling_rate_global(self): return self.api.Networking.VLAN.get_sflow_sampling_rate_global(self.vlans) def get_source_check_state(self): return self.api.Networking.VLAN.get_source_check_state(self.vlans) def get_true_mac_address(self): return self.api.Networking.VLAN.get_true_mac_address(self.vlans) def get_vlan_id(self): return self.api.Networking.VLAN.get_vlan_id(self.vlans) class Software(object): """Software class. F5 BIG-IP software class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_all_software_status(self): return self.api.System.SoftwareManagement.get_all_software_status() class VirtualServers(object): """Virtual servers class. F5 BIG-IP virtual servers class. Attributes: api: iControl API instance. virtual_servers: List of virtual servers. """ def __init__(self, api, regex=None): self.api = api self.virtual_servers = api.LocalLB.VirtualServer.get_list() if regex: re_filter = re.compile(regex) self.virtual_servers = filter(re_filter.search, self.virtual_servers) def get_list(self): return self.virtual_servers def get_name(self): return [x[x.rfind('/') + 1:] for x in self.virtual_servers] def get_actual_hardware_acceleration(self): return self.api.LocalLB.VirtualServer.get_actual_hardware_acceleration(self.virtual_servers) def get_authentication_profile(self): return self.api.LocalLB.VirtualServer.get_authentication_profile(self.virtual_servers) def get_auto_lasthop(self): return self.api.LocalLB.VirtualServer.get_auto_lasthop(self.virtual_servers) def get_bw_controller_policy(self): return self.api.LocalLB.VirtualServer.get_bw_controller_policy(self.virtual_servers) def get_clone_pool(self): return self.api.LocalLB.VirtualServer.get_clone_pool(self.virtual_servers) def get_cmp_enable_mode(self): return self.api.LocalLB.VirtualServer.get_cmp_enable_mode(self.virtual_servers) def get_connection_limit(self): return self.api.LocalLB.VirtualServer.get_connection_limit(self.virtual_servers) def get_connection_mirror_state(self): return self.api.LocalLB.VirtualServer.get_connection_mirror_state(self.virtual_servers) def get_default_pool_name(self): return self.api.LocalLB.VirtualServer.get_default_pool_name(self.virtual_servers) def get_description(self): return self.api.LocalLB.VirtualServer.get_description(self.virtual_servers) def get_destination(self): return self.api.LocalLB.VirtualServer.get_destination_v2(self.virtual_servers) def get_enabled_state(self): return self.api.LocalLB.VirtualServer.get_enabled_state(self.virtual_servers) def get_enforced_firewall_policy(self): return self.api.LocalLB.VirtualServer.get_enforced_firewall_policy(self.virtual_servers) def get_fallback_persistence_profile(self): return self.api.LocalLB.VirtualServer.get_fallback_persistence_profile(self.virtual_servers) def get_fw_rule(self): return self.api.LocalLB.VirtualServer.get_fw_rule(self.virtual_servers) def get_gtm_score(self): return self.api.LocalLB.VirtualServer.get_gtm_score(self.virtual_servers) def get_last_hop_pool(self): return self.api.LocalLB.VirtualServer.get_last_hop_pool(self.virtual_servers) def get_nat64_state(self): return self.api.LocalLB.VirtualServer.get_nat64_state(self.virtual_servers) def get_object_status(self): return self.api.LocalLB.VirtualServer.get_object_status(self.virtual_servers) def get_persistence_profile(self): return self.api.LocalLB.VirtualServer.get_persistence_profile(self.virtual_servers) def get_profile(self): return self.api.LocalLB.VirtualServer.get_profile(self.virtual_servers) def get_protocol(self): return self.api.LocalLB.VirtualServer.get_protocol(self.virtual_servers) def get_rate_class(self): return self.api.LocalLB.VirtualServer.get_rate_class(self.virtual_servers) def get_rate_limit(self): return self.api.LocalLB.VirtualServer.get_rate_limit(self.virtual_servers) def get_rate_limit_destination_mask(self): return self.api.LocalLB.VirtualServer.get_rate_limit_destination_mask(self.virtual_servers) def get_rate_limit_mode(self): return self.api.LocalLB.VirtualServer.get_rate_limit_mode(self.virtual_servers) def get_rate_limit_source_mask(self): return self.api.LocalLB.VirtualServer.get_rate_limit_source_mask(self.virtual_servers) def get_related_rule(self): return self.api.LocalLB.VirtualServer.get_related_rule(self.virtual_servers) def get_rule(self): return self.api.LocalLB.VirtualServer.get_rule(self.virtual_servers) def get_security_log_profile(self): return self.api.LocalLB.VirtualServer.get_security_log_profile(self.virtual_servers) def get_snat_pool(self): return self.api.LocalLB.VirtualServer.get_snat_pool(self.virtual_servers) def get_snat_type(self): return self.api.LocalLB.VirtualServer.get_snat_type(self.virtual_servers) def get_source_address(self): return self.api.LocalLB.VirtualServer.get_source_address(self.virtual_servers) def get_source_address_translation_lsn_pool(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_lsn_pool(self.virtual_servers) def get_source_address_translation_snat_pool(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_snat_pool(self.virtual_servers) def get_source_address_translation_type(self): return self.api.LocalLB.VirtualServer.get_source_address_translation_type(self.virtual_servers) def get_source_port_behavior(self): return self.api.LocalLB.VirtualServer.get_source_port_behavior(self.virtual_servers) def get_staged_firewall_policy(self): return self.api.LocalLB.VirtualServer.get_staged_firewall_policy(self.virtual_servers) def get_translate_address_state(self): return self.api.LocalLB.VirtualServer.get_translate_address_state(self.virtual_servers) def get_translate_port_state(self): return self.api.LocalLB.VirtualServer.get_translate_port_state(self.virtual_servers) def get_type(self): return self.api.LocalLB.VirtualServer.get_type(self.virtual_servers) def get_vlan(self): return self.api.LocalLB.VirtualServer.get_vlan(self.virtual_servers) def get_wildmask(self): return self.api.LocalLB.VirtualServer.get_wildmask(self.virtual_servers) class Pools(object): """Pools class. F5 BIG-IP pools class. Attributes: api: iControl API instance. pool_names: List of pool names. """ def __init__(self, api, regex=None): self.api = api self.pool_names = api.LocalLB.Pool.get_list() if regex: re_filter = re.compile(regex) self.pool_names = filter(re_filter.search, self.pool_names) def get_list(self): return self.pool_names def get_name(self): return [x[x.rfind('/') + 1:] for x in self.pool_names] def get_action_on_service_down(self): return self.api.LocalLB.Pool.get_action_on_service_down(self.pool_names) def get_active_member_count(self): return self.api.LocalLB.Pool.get_active_member_count(self.pool_names) def get_aggregate_dynamic_ratio(self): return self.api.LocalLB.Pool.get_aggregate_dynamic_ratio(self.pool_names) def get_allow_nat_state(self): return self.api.LocalLB.Pool.get_allow_nat_state(self.pool_names) def get_allow_snat_state(self): return self.api.LocalLB.Pool.get_allow_snat_state(self.pool_names) def get_client_ip_tos(self): return self.api.LocalLB.Pool.get_client_ip_tos(self.pool_names) def get_client_link_qos(self): return self.api.LocalLB.Pool.get_client_link_qos(self.pool_names) def get_description(self): return self.api.LocalLB.Pool.get_description(self.pool_names) def get_gateway_failsafe_device(self): return self.api.LocalLB.Pool.get_gateway_failsafe_device(self.pool_names) def get_ignore_persisted_weight_state(self): return self.api.LocalLB.Pool.get_ignore_persisted_weight_state(self.pool_names) def get_lb_method(self): result = [] lb_choice = dict( LB_METHOD_DYNAMIC_RATIO_MEMBER='dynamic-ratio-member', LB_METHOD_DYNAMIC_RATIO='dynamic-ratio-node', LB_METHOD_FASTEST_APP_RESPONSE='fastest-app-response', LB_METHOD_FASTEST_NODE_ADDRESS='fastest-node', LB_METHOD_LEAST_CONNECTION_MEMBER='least-connections-member', LB_METHOD_LEAST_CONNECTION_NODE_ADDRESS='least-connections-node', LB_METHOD_LEAST_SESSIONS='least-sessions', LB_METHOD_OBSERVED_MEMBER='observed-member', LB_METHOD_OBSERVED_NODE_ADDRESS='observed-node', LB_METHOD_PREDICTIVE_MEMBER='predictive-member', LB_METHOD_PREDICTIVE_NODE_ADDRESS='predictive-node', LB_METHOD_RATIO_LEAST_CONNECTION_MEMBER='ratio-least-connections-member', LB_METHOD_RATIO_LEAST_CONNECTION_NODE_ADDRESS='ratio-least-connections-node', LB_METHOD_RATIO_MEMBER='ratio-member', LB_METHOD_RATIO_NODE_ADDRESS='ratio-node', LB_METHOD_RATIO_SESSION='ratio-session', LB_METHOD_ROUND_ROBIN='round-robin', LB_METHOD_WEIGHTED_LEAST_CONNECTION_MEMBER='weighted-least-connections-member', LB_METHOD_WEIGHTED_LEAST_CONNECTION_NODE_ADDRESS='weighted-least-connections-node' ) methods = self.api.LocalLB.Pool.get_lb_method(self.pool_names) for method in methods: result.append(lb_choice.get(method, method)) return result def get_member(self): return self.api.LocalLB.Pool.get_member_v2(self.pool_names) def get_minimum_active_member(self): return self.api.LocalLB.Pool.get_minimum_active_member(self.pool_names) def get_minimum_up_member(self): return self.api.LocalLB.Pool.get_minimum_up_member(self.pool_names) def get_minimum_up_member_action(self): return self.api.LocalLB.Pool.get_minimum_up_member_action(self.pool_names) def get_minimum_up_member_enabled_state(self): return self.api.LocalLB.Pool.get_minimum_up_member_enabled_state(self.pool_names) def get_monitor_association(self): return self.api.LocalLB.Pool.get_monitor_association(self.pool_names) def get_monitor_instance(self): return self.api.LocalLB.Pool.get_monitor_instance(self.pool_names) def get_object_status(self): return self.api.LocalLB.Pool.get_object_status(self.pool_names) def get_profile(self): return self.api.LocalLB.Pool.get_profile(self.pool_names) def get_queue_depth_limit(self): return self.api.LocalLB.Pool.get_queue_depth_limit(self.pool_names) def get_queue_on_connection_limit_state(self): return self.api.LocalLB.Pool.get_queue_on_connection_limit_state(self.pool_names) def get_queue_time_limit(self): return self.api.LocalLB.Pool.get_queue_time_limit(self.pool_names) def get_reselect_tries(self): return self.api.LocalLB.Pool.get_reselect_tries(self.pool_names) def get_server_ip_tos(self): return self.api.LocalLB.Pool.get_server_ip_tos(self.pool_names) def get_server_link_qos(self): return self.api.LocalLB.Pool.get_server_link_qos(self.pool_names) def get_simple_timeout(self): return self.api.LocalLB.Pool.get_simple_timeout(self.pool_names) def get_slow_ramp_time(self): return self.api.LocalLB.Pool.get_slow_ramp_time(self.pool_names) class Devices(object): """Devices class. F5 BIG-IP devices class. Attributes: api: iControl API instance. devices: List of devices. """ def __init__(self, api, regex=None): self.api = api self.devices = api.Management.Device.get_list() if regex: re_filter = re.compile(regex) self.devices = filter(re_filter.search, self.devices) def get_list(self): return self.devices def get_active_modules(self): return self.api.Management.Device.get_active_modules(self.devices) def get_base_mac_address(self): return self.api.Management.Device.get_base_mac_address(self.devices) def get_blade_addresses(self): return self.api.Management.Device.get_blade_addresses(self.devices) def get_build(self): return self.api.Management.Device.get_build(self.devices) def get_chassis_id(self): return self.api.Management.Device.get_chassis_id(self.devices) def get_chassis_type(self): return self.api.Management.Device.get_chassis_type(self.devices) def get_comment(self): return self.api.Management.Device.get_comment(self.devices) def get_configsync_address(self): return self.api.Management.Device.get_configsync_address(self.devices) def get_contact(self): return self.api.Management.Device.get_contact(self.devices) def get_description(self): return self.api.Management.Device.get_description(self.devices) def get_edition(self): return self.api.Management.Device.get_edition(self.devices) def get_failover_state(self): return self.api.Management.Device.get_failover_state(self.devices) def get_local_device(self): return self.api.Management.Device.get_local_device() def get_hostname(self): return self.api.Management.Device.get_hostname(self.devices) def get_inactive_modules(self): return self.api.Management.Device.get_inactive_modules(self.devices) def get_location(self): return self.api.Management.Device.get_location(self.devices) def get_management_address(self): return self.api.Management.Device.get_management_address(self.devices) def get_marketing_name(self): return self.api.Management.Device.get_marketing_name(self.devices) def get_multicast_address(self): return self.api.Management.Device.get_multicast_address(self.devices) def get_optional_modules(self): return self.api.Management.Device.get_optional_modules(self.devices) def get_platform_id(self): return self.api.Management.Device.get_platform_id(self.devices) def get_primary_mirror_address(self): return self.api.Management.Device.get_primary_mirror_address(self.devices) def get_product(self): return self.api.Management.Device.get_product(self.devices) def get_secondary_mirror_address(self): return self.api.Management.Device.get_secondary_mirror_address(self.devices) def get_software_version(self): return self.api.Management.Device.get_software_version(self.devices) def get_timelimited_modules(self): return self.api.Management.Device.get_timelimited_modules(self.devices) def get_timezone(self): return self.api.Management.Device.get_timezone(self.devices) def get_unicast_addresses(self): return self.api.Management.Device.get_unicast_addresses(self.devices) class DeviceGroups(object): """Device groups class. F5 BIG-IP device groups class. Attributes: api: iControl API instance. device_groups: List of device groups. """ def __init__(self, api, regex=None): self.api = api self.device_groups = api.Management.DeviceGroup.get_list() if regex: re_filter = re.compile(regex) self.device_groups = filter(re_filter.search, self.device_groups) def get_list(self): return self.device_groups def get_all_preferred_active(self): return self.api.Management.DeviceGroup.get_all_preferred_active(self.device_groups) def get_autosync_enabled_state(self): return self.api.Management.DeviceGroup.get_autosync_enabled_state(self.device_groups) def get_description(self): return self.api.Management.DeviceGroup.get_description(self.device_groups) def get_device(self): return self.api.Management.DeviceGroup.get_device(self.device_groups) def get_full_load_on_sync_state(self): return self.api.Management.DeviceGroup.get_full_load_on_sync_state(self.device_groups) def get_incremental_config_sync_size_maximum(self): return self.api.Management.DeviceGroup.get_incremental_config_sync_size_maximum(self.device_groups) def get_network_failover_enabled_state(self): return self.api.Management.DeviceGroup.get_network_failover_enabled_state(self.device_groups) def get_sync_status(self): return self.api.Management.DeviceGroup.get_sync_status(self.device_groups) def get_type(self): return self.api.Management.DeviceGroup.get_type(self.device_groups) class TrafficGroups(object): """Traffic groups class. F5 BIG-IP traffic groups class. Attributes: api: iControl API instance. traffic_groups: List of traffic groups. """ def __init__(self, api, regex=None): self.api = api self.traffic_groups = api.Management.TrafficGroup.get_list() if regex: re_filter = re.compile(regex) self.traffic_groups = filter(re_filter.search, self.traffic_groups) def get_list(self): return self.traffic_groups def get_auto_failback_enabled_state(self): return self.api.Management.TrafficGroup.get_auto_failback_enabled_state(self.traffic_groups) def get_auto_failback_time(self): return self.api.Management.TrafficGroup.get_auto_failback_time(self.traffic_groups) def get_default_device(self): return self.api.Management.TrafficGroup.get_default_device(self.traffic_groups) def get_description(self): return self.api.Management.TrafficGroup.get_description(self.traffic_groups) def get_ha_load_factor(self): return self.api.Management.TrafficGroup.get_ha_load_factor(self.traffic_groups) def get_ha_order(self): return self.api.Management.TrafficGroup.get_ha_order(self.traffic_groups) def get_is_floating(self): return self.api.Management.TrafficGroup.get_is_floating(self.traffic_groups) def get_mac_masquerade_address(self): return self.api.Management.TrafficGroup.get_mac_masquerade_address(self.traffic_groups) def get_unit_id(self): return self.api.Management.TrafficGroup.get_unit_id(self.traffic_groups) class Rules(object): """Rules class. F5 BIG-IP iRules class. Attributes: api: iControl API instance. rules: List of iRules. """ def __init__(self, api, regex=None): self.api = api self.rules = api.LocalLB.Rule.get_list() if regex: re_filter = re.compile(regex) self.traffic_groups = filter(re_filter.search, self.rules) def get_list(self): return self.rules def get_description(self): return self.api.LocalLB.Rule.get_description(rule_names=self.rules) def get_ignore_vertification(self): return self.api.LocalLB.Rule.get_ignore_vertification(rule_names=self.rules) def get_verification_status(self): return self.api.LocalLB.Rule.get_verification_status_v2(rule_names=self.rules) def get_definition(self): return [x['rule_definition'] for x in self.api.LocalLB.Rule.query_rule(rule_names=self.rules)] class Nodes(object): """Nodes class. F5 BIG-IP nodes class. Attributes: api: iControl API instance. nodes: List of nodes. """ def __init__(self, api, regex=None): self.api = api self.nodes = api.LocalLB.NodeAddressV2.get_list() if regex: re_filter = re.compile(regex) self.nodes = filter(re_filter.search, self.nodes) def get_list(self): return self.nodes def get_address(self): return self.api.LocalLB.NodeAddressV2.get_address(nodes=self.nodes) def get_name(self): return [x[x.rfind('/') + 1:] for x in self.nodes] def get_connection_limit(self): return self.api.LocalLB.NodeAddressV2.get_connection_limit(nodes=self.nodes) def get_description(self): return self.api.LocalLB.NodeAddressV2.get_description(nodes=self.nodes) def get_dynamic_ratio(self): return self.api.LocalLB.NodeAddressV2.get_dynamic_ratio_v2(nodes=self.nodes) def get_monitor_instance(self): return self.api.LocalLB.NodeAddressV2.get_monitor_instance(nodes=self.nodes) def get_monitor_rule(self): return self.api.LocalLB.NodeAddressV2.get_monitor_rule(nodes=self.nodes) def get_monitor_status(self): return self.api.LocalLB.NodeAddressV2.get_monitor_status(nodes=self.nodes) def get_object_status(self): return self.api.LocalLB.NodeAddressV2.get_object_status(nodes=self.nodes) def get_rate_limit(self): return self.api.LocalLB.NodeAddressV2.get_rate_limit(nodes=self.nodes) def get_ratio(self): return self.api.LocalLB.NodeAddressV2.get_ratio(nodes=self.nodes) def get_session_status(self): return self.api.LocalLB.NodeAddressV2.get_session_status(nodes=self.nodes) class VirtualAddresses(object): """Virtual addresses class. F5 BIG-IP virtual addresses class. Attributes: api: iControl API instance. virtual_addresses: List of virtual addresses. """ def __init__(self, api, regex=None): self.api = api self.virtual_addresses = api.LocalLB.VirtualAddressV2.get_list() if regex: re_filter = re.compile(regex) self.virtual_addresses = filter(re_filter.search, self.virtual_addresses) def get_list(self): return self.virtual_addresses def get_address(self): return self.api.LocalLB.VirtualAddressV2.get_address(self.virtual_addresses) def get_arp_state(self): return self.api.LocalLB.VirtualAddressV2.get_arp_state(self.virtual_addresses) def get_auto_delete_state(self): return self.api.LocalLB.VirtualAddressV2.get_auto_delete_state(self.virtual_addresses) def get_connection_limit(self): return self.api.LocalLB.VirtualAddressV2.get_connection_limit(self.virtual_addresses) def get_description(self): return self.api.LocalLB.VirtualAddressV2.get_description(self.virtual_addresses) def get_enabled_state(self): return self.api.LocalLB.VirtualAddressV2.get_enabled_state(self.virtual_addresses) def get_icmp_echo_state(self): return self.api.LocalLB.VirtualAddressV2.get_icmp_echo_state(self.virtual_addresses) def get_is_floating_state(self): return self.api.LocalLB.VirtualAddressV2.get_is_floating_state(self.virtual_addresses) def get_netmask(self): return self.api.LocalLB.VirtualAddressV2.get_netmask(self.virtual_addresses) def get_object_status(self): return self.api.LocalLB.VirtualAddressV2.get_object_status(self.virtual_addresses) def get_route_advertisement_state(self): return self.api.LocalLB.VirtualAddressV2.get_route_advertisement_state(self.virtual_addresses) def get_traffic_group(self): return self.api.LocalLB.VirtualAddressV2.get_traffic_group(self.virtual_addresses) class AddressClasses(object): """Address group/class class. F5 BIG-IP address group/class class. In TMUI these things are known as Address Data Groups. Examples that ship with the box include /Common/aol and /Common/private_net Attributes: api: iControl API instance. address_classes: List of address classes. """ def __init__(self, api, regex=None): self.api = api self.address_classes = api.LocalLB.Class.get_address_class_list() if regex: re_filter = re.compile(regex) self.address_classes = filter(re_filter.search, self.address_classes) def get_list(self): return self.address_classes def get_address_class(self): key = self.api.LocalLB.Class.get_address_class(self.address_classes) value = self.api.LocalLB.Class.get_address_class_member_data_value(key) result = [] for idx, v in enumerate(key): for idx2, member in enumerate(v['members']): dg_value = dict( value=value[idx][idx2] ) dg_value.update(member) result.append(dg_value) return result def get_description(self): return self.api.LocalLB.Class.get_description(self.address_classes) class Certificates(object): """Certificates class. F5 BIG-IP certificates class. Attributes: api: iControl API instance. certificates: List of certificate identifiers. certificate_list: List of certificate information structures. """ def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"): self.api = api self.certificate_list = api.Management.KeyCertificate.get_certificate_list(mode=mode) self.certificates = [x['certificate']['cert_info']['id'] for x in self.certificate_list] if regex: re_filter = re.compile(regex) self.certificates = filter(re_filter.search, self.certificates) self.certificate_list = [x for x in self.certificate_list if x['certificate']['cert_info']['id'] in self.certificates] def get_list(self): return self.certificates def get_certificate_list(self): return self.certificate_list class Keys(object): """Keys class. F5 BIG-IP keys class. Attributes: api: iControl API instance. keys: List of key identifiers. key_list: List of key information structures. """ def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"): self.api = api self.key_list = api.Management.KeyCertificate.get_key_list(mode=mode) self.keys = [x['key_info']['id'] for x in self.key_list] if regex: re_filter = re.compile(regex) self.keys = filter(re_filter.search, self.keys) self.key_list = [x for x in self.key_list if x['key_info']['id'] in self.keys] def get_list(self): return self.keys def get_key_list(self): return self.key_list class ProfileClientSSL(object): """Client SSL profiles class. F5 BIG-IP client SSL profiles class. Attributes: api: iControl API instance. profiles: List of client SSL profiles. """ def __init__(self, api, regex=None): self.api = api self.profiles = api.LocalLB.ProfileClientSSL.get_list() if regex: re_filter = re.compile(regex) self.profiles = filter(re_filter.search, self.profiles) def get_list(self): return self.profiles def get_alert_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_alert_timeout(self.profiles) def get_allow_nonssl_state(self): return self.api.LocalLB.ProfileClientSSL.get_allow_nonssl_state(self.profiles) def get_authenticate_depth(self): return self.api.LocalLB.ProfileClientSSL.get_authenticate_depth(self.profiles) def get_authenticate_once_state(self): return self.api.LocalLB.ProfileClientSSL.get_authenticate_once_state(self.profiles) def get_ca_file(self): return self.api.LocalLB.ProfileClientSSL.get_ca_file_v2(self.profiles) def get_cache_size(self): return self.api.LocalLB.ProfileClientSSL.get_cache_size(self.profiles) def get_cache_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_cache_timeout(self.profiles) def get_certificate_file(self): return self.api.LocalLB.ProfileClientSSL.get_certificate_file_v2(self.profiles) def get_chain_file(self): return self.api.LocalLB.ProfileClientSSL.get_chain_file_v2(self.profiles) def get_cipher_list(self): return self.api.LocalLB.ProfileClientSSL.get_cipher_list(self.profiles) def get_client_certificate_ca_file(self): return self.api.LocalLB.ProfileClientSSL.get_client_certificate_ca_file_v2(self.profiles) def get_crl_file(self): return self.api.LocalLB.ProfileClientSSL.get_crl_file_v2(self.profiles) def get_default_profile(self): return self.api.LocalLB.ProfileClientSSL.get_default_profile(self.profiles) def get_description(self): return self.api.LocalLB.ProfileClientSSL.get_description(self.profiles) def get_forward_proxy_ca_certificate_file(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_certificate_file(self.profiles) def get_forward_proxy_ca_key_file(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_key_file(self.profiles) def get_forward_proxy_ca_passphrase(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_passphrase(self.profiles) def get_forward_proxy_certificate_extension_include(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_extension_include(self.profiles) def get_forward_proxy_certificate_lifespan(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_lifespan(self.profiles) def get_forward_proxy_enabled_state(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_enabled_state(self.profiles) def get_forward_proxy_lookup_by_ipaddr_port_state(self): return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_lookup_by_ipaddr_port_state(self.profiles) def get_handshake_timeout(self): return self.api.LocalLB.ProfileClientSSL.get_handshake_timeout(self.profiles) def get_key_file(self): return self.api.LocalLB.ProfileClientSSL.get_key_file_v2(self.profiles) def get_modssl_emulation_state(self): return self.api.LocalLB.ProfileClientSSL.get_modssl_emulation_state(self.profiles) def get_passphrase(self): return self.api.LocalLB.ProfileClientSSL.get_passphrase(self.profiles) def get_peer_certification_mode(self): return self.api.LocalLB.ProfileClientSSL.get_peer_certification_mode(self.profiles) def get_profile_mode(self): return self.api.LocalLB.ProfileClientSSL.get_profile_mode(self.profiles) def get_renegotiation_maximum_record_delay(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_maximum_record_delay(self.profiles) def get_renegotiation_period(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_period(self.profiles) def get_renegotiation_state(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_state(self.profiles) def get_renegotiation_throughput(self): return self.api.LocalLB.ProfileClientSSL.get_renegotiation_throughput(self.profiles) def get_retain_certificate_state(self): return self.api.LocalLB.ProfileClientSSL.get_retain_certificate_state(self.profiles) def get_secure_renegotiation_mode(self): return self.api.LocalLB.ProfileClientSSL.get_secure_renegotiation_mode(self.profiles) def get_server_name(self): return self.api.LocalLB.ProfileClientSSL.get_server_name(self.profiles) def get_session_ticket_state(self): return self.api.LocalLB.ProfileClientSSL.get_session_ticket_state(self.profiles) def get_sni_default_state(self): return self.api.LocalLB.ProfileClientSSL.get_sni_default_state(self.profiles) def get_sni_require_state(self): return self.api.LocalLB.ProfileClientSSL.get_sni_require_state(self.profiles) def get_ssl_option(self): return self.api.LocalLB.ProfileClientSSL.get_ssl_option(self.profiles) def get_strict_resume_state(self): return self.api.LocalLB.ProfileClientSSL.get_strict_resume_state(self.profiles) def get_unclean_shutdown_state(self): return self.api.LocalLB.ProfileClientSSL.get_unclean_shutdown_state(self.profiles) def get_is_base_profile(self): return self.api.LocalLB.ProfileClientSSL.is_base_profile(self.profiles) def get_is_system_profile(self): return self.api.LocalLB.ProfileClientSSL.is_system_profile(self.profiles) class SystemInfo(object): """System information class. F5 BIG-IP system information class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_base_mac_address(self): return self.api.System.SystemInfo.get_base_mac_address() def get_blade_temperature(self): return self.api.System.SystemInfo.get_blade_temperature() def get_chassis_slot_information(self): return self.api.System.SystemInfo.get_chassis_slot_information() def get_globally_unique_identifier(self): return self.api.System.SystemInfo.get_globally_unique_identifier() def get_group_id(self): return self.api.System.SystemInfo.get_group_id() def get_hardware_information(self): return self.api.System.SystemInfo.get_hardware_information() def get_marketing_name(self): return self.api.System.SystemInfo.get_marketing_name() def get_product_information(self): return self.api.System.SystemInfo.get_product_information() def get_pva_version(self): return self.api.System.SystemInfo.get_pva_version() def get_system_id(self): return self.api.System.SystemInfo.get_system_id() def get_system_information(self): return self.api.System.SystemInfo.get_system_information() def get_time(self): return self.api.System.SystemInfo.get_time() def get_time_zone(self): return self.api.System.SystemInfo.get_time_zone() def get_uptime(self): return self.api.System.SystemInfo.get_uptime() class ProvisionInfo(object): """Provision information class. F5 BIG-IP provision information class. Attributes: api: iControl API instance. """ def __init__(self, api): self.api = api def get_list(self): result = [] list = self.api.Management.Provision.get_list() for item in list: item = item.lower().replace('tmos_module_', '') result.append(item) return result def get_provisioned_list(self): result = [] list = self.api.Management.Provision.get_provisioned_list() for item in list: item = item.lower().replace('tmos_module_', '') result.append(item) return result def generate_dict(api_obj, fields): result_dict = {} lists = [] supported_fields = [] if api_obj.get_list(): for field in fields: try: api_response = getattr(api_obj, "get_" + field)() except (MethodNotFound, WebFault): pass else: lists.append(api_response) supported_fields.append(field) for i, j in enumerate(api_obj.get_list()): temp = {} temp.update([(item[0], item[1][i]) for item in zip(supported_fields, lists)]) result_dict[j] = temp return result_dict def generate_simple_dict(api_obj, fields): result_dict = {} for field in fields: try: api_response = getattr(api_obj, "get_" + field)() except (MethodNotFound, WebFault): pass else: result_dict[field] = api_response return result_dict def generate_interface_dict(f5, regex): interfaces = Interfaces(f5.get_api(), regex) fields = ['active_media', 'actual_flow_control', 'bundle_state', 'description', 'dual_media_state', 'enabled_state', 'if_index', 'learning_mode', 'lldp_admin_status', 'lldp_tlvmap', 'mac_address', 'media', 'media_option', 'media_option_sfp', 'media_sfp', 'media_speed', 'media_status', 'mtu', 'phy_master_slave_mode', 'prefer_sfp_state', 'flow_control', 'sflow_poll_interval', 'sflow_poll_interval_global', 'sfp_media_state', 'stp_active_edge_port_state', 'stp_enabled_state', 'stp_link_type', 'stp_protocol_detection_reset_state'] return generate_dict(interfaces, fields) def generate_self_ip_dict(f5, regex): self_ips = SelfIPs(f5.get_api(), regex) fields = ['address', 'allow_access_list', 'description', 'enforced_firewall_policy', 'floating_state', 'fw_rule', 'netmask', 'staged_firewall_policy', 'traffic_group', 'vlan', 'is_traffic_group_inherited'] return generate_dict(self_ips, fields) def generate_trunk_dict(f5, regex): trunks = Trunks(f5.get_api(), regex) fields = ['active_lacp_state', 'configured_member_count', 'description', 'distribution_hash_option', 'interface', 'lacp_enabled_state', 'lacp_timeout_option', 'link_selection_policy', 'media_speed', 'media_status', 'operational_member_count', 'stp_enabled_state', 'stp_protocol_detection_reset_state'] return generate_dict(trunks, fields) def generate_vlan_dict(f5, regex): vlans = Vlans(f5.get_api(), regex) fields = ['auto_lasthop', 'cmp_hash_algorithm', 'description', 'dynamic_forwarding', 'failsafe_action', 'failsafe_state', 'failsafe_timeout', 'if_index', 'learning_mode', 'mac_masquerade_address', 'member', 'mtu', 'sflow_poll_interval', 'sflow_poll_interval_global', 'sflow_sampling_rate', 'sflow_sampling_rate_global', 'source_check_state', 'true_mac_address', 'vlan_id'] return generate_dict(vlans, fields) def generate_vs_dict(f5, regex): virtual_servers = VirtualServers(f5.get_api(), regex) fields = ['actual_hardware_acceleration', 'authentication_profile', 'auto_lasthop', 'bw_controller_policy', 'clone_pool', 'cmp_enable_mode', 'connection_limit', 'connection_mirror_state', 'default_pool_name', 'description', 'destination', 'enabled_state', 'enforced_firewall_policy', 'fallback_persistence_profile', 'fw_rule', 'gtm_score', 'last_hop_pool', 'nat64_state', 'object_status', 'persistence_profile', 'profile', 'protocol', 'rate_class', 'rate_limit', 'rate_limit_destination_mask', 'rate_limit_mode', 'rate_limit_source_mask', 'related_rule', 'rule', 'security_log_profile', 'snat_pool', 'snat_type', 'source_address', 'source_address_translation_lsn_pool', 'source_address_translation_snat_pool', 'source_address_translation_type', 'source_port_behavior', 'staged_firewall_policy', 'translate_address_state', 'translate_port_state', 'type', 'vlan', 'wildmask', 'name'] return generate_dict(virtual_servers, fields) def generate_pool_dict(f5, regex): pools = Pools(f5.get_api(), regex) fields = ['action_on_service_down', 'active_member_count', 'aggregate_dynamic_ratio', 'allow_nat_state', 'allow_snat_state', 'client_ip_tos', 'client_link_qos', 'description', 'gateway_failsafe_device', 'ignore_persisted_weight_state', 'lb_method', 'member', 'minimum_active_member', 'minimum_up_member', 'minimum_up_member_action', 'minimum_up_member_enabled_state', 'monitor_association', 'monitor_instance', 'object_status', 'profile', 'queue_depth_limit', 'queue_on_connection_limit_state', 'queue_time_limit', 'reselect_tries', 'server_ip_tos', 'server_link_qos', 'simple_timeout', 'slow_ramp_time', 'name'] return generate_dict(pools, fields) def generate_device_dict(f5, regex): devices = Devices(f5.get_api(), regex) fields = ['active_modules', 'base_mac_address', 'blade_addresses', 'build', 'chassis_id', 'chassis_type', 'comment', 'configsync_address', 'contact', 'description', 'edition', 'failover_state', 'hostname', 'inactive_modules', 'location', 'management_address', 'marketing_name', 'multicast_address', 'optional_modules', 'platform_id', 'primary_mirror_address', 'product', 'secondary_mirror_address', 'software_version', 'timelimited_modules', 'timezone', 'unicast_addresses'] return generate_dict(devices, fields) def generate_device_group_dict(f5, regex): device_groups = DeviceGroups(f5.get_api(), regex) fields = ['all_preferred_active', 'autosync_enabled_state', 'description', 'device', 'full_load_on_sync_state', 'incremental_config_sync_size_maximum', 'network_failover_enabled_state', 'sync_status', 'type'] return generate_dict(device_groups, fields) def generate_traffic_group_dict(f5, regex): traffic_groups = TrafficGroups(f5.get_api(), regex) fields = ['auto_failback_enabled_state', 'auto_failback_time', 'default_device', 'description', 'ha_load_factor', 'ha_order', 'is_floating', 'mac_masquerade_address', 'unit_id'] return generate_dict(traffic_groups, fields) def generate_rule_dict(f5, regex): rules = Rules(f5.get_api(), regex) fields = ['definition', 'description', 'ignore_vertification', 'verification_status'] return generate_dict(rules, fields) def generate_node_dict(f5, regex): nodes = Nodes(f5.get_api(), regex) fields = ['name', 'address', 'connection_limit', 'description', 'dynamic_ratio', 'monitor_instance', 'monitor_rule', 'monitor_status', 'object_status', 'rate_limit', 'ratio', 'session_status'] return generate_dict(nodes, fields) def generate_virtual_address_dict(f5, regex): virtual_addresses = VirtualAddresses(f5.get_api(), regex) fields = ['address', 'arp_state', 'auto_delete_state', 'connection_limit', 'description', 'enabled_state', 'icmp_echo_state', 'is_floating_state', 'netmask', 'object_status', 'route_advertisement_state', 'traffic_group'] return generate_dict(virtual_addresses, fields) def generate_address_class_dict(f5, regex): address_classes = AddressClasses(f5.get_api(), regex) fields = ['address_class', 'description'] return generate_dict(address_classes, fields) def generate_certificate_dict(f5, regex): certificates = Certificates(f5.get_api(), regex) return dict(zip(certificates.get_list(), certificates.get_certificate_list())) def generate_key_dict(f5, regex): keys = Keys(f5.get_api(), regex) return dict(zip(keys.get_list(), keys.get_key_list())) def generate_client_ssl_profile_dict(f5, regex): profiles = ProfileClientSSL(f5.get_api(), regex) fields = ['alert_timeout', 'allow_nonssl_state', 'authenticate_depth', 'authenticate_once_state', 'ca_file', 'cache_size', 'cache_timeout', 'certificate_file', 'chain_file', 'cipher_list', 'client_certificate_ca_file', 'crl_file', 'default_profile', 'description', 'forward_proxy_ca_certificate_file', 'forward_proxy_ca_key_file', 'forward_proxy_ca_passphrase', 'forward_proxy_certificate_extension_include', 'forward_proxy_certificate_lifespan', 'forward_proxy_enabled_state', 'forward_proxy_lookup_by_ipaddr_port_state', 'handshake_timeout', 'key_file', 'modssl_emulation_state', 'passphrase', 'peer_certification_mode', 'profile_mode', 'renegotiation_maximum_record_delay', 'renegotiation_period', 'renegotiation_state', 'renegotiation_throughput', 'retain_certificate_state', 'secure_renegotiation_mode', 'server_name', 'session_ticket_state', 'sni_default_state', 'sni_require_state', 'ssl_option', 'strict_resume_state', 'unclean_shutdown_state', 'is_base_profile', 'is_system_profile'] return generate_dict(profiles, fields) def generate_system_info_dict(f5): system_info = SystemInfo(f5.get_api()) fields = ['base_mac_address', 'blade_temperature', 'chassis_slot_information', 'globally_unique_identifier', 'group_id', 'hardware_information', 'marketing_name', 'product_information', 'pva_version', 'system_id', 'system_information', 'time', 'time_zone', 'uptime'] return generate_simple_dict(system_info, fields) def generate_software_list(f5): software = Software(f5.get_api()) software_list = software.get_all_software_status() return software_list def generate_provision_dict(f5): provisioned = ProvisionInfo(f5.get_api()) fields = ['list', 'provisioned_list'] return generate_simple_dict(provisioned, fields) def main(): argument_spec = f5_argument_spec meta_args = dict( session=dict(type='bool', default='no'), include=dict( type='raw', required=True, choices=[ 'address_class', 'certificate', 'client_ssl_profile', 'device', 'device_group', 'interface', 'key', 'node', 'pool', 'provision', 'rule', 'self_ip', 'software', 'system_info', 'traffic_group', 'trunk', 'virtual_address', 'virtual_server', 'vlan' ] ), filter=dict(type='str'), ) argument_spec.update(meta_args) module = AnsibleModule( argument_spec=argument_spec ) if not bigsuds_found: module.fail_json(msg="the python suds and bigsuds modules are required") server = module.params['server'] server_port = module.params['server_port'] user = module.params['user'] password = module.params['password'] validate_certs = module.params['validate_certs'] session = module.params['session'] fact_filter = module.params['filter'] if validate_certs: import ssl if not hasattr(ssl, 'SSLContext'): module.fail_json( msg='bigsuds does not support verifying certificates with python < 2.7.9. Either update python or set validate_certs=False on the task' ) if fact_filter: regex = fnmatch.translate(fact_filter) else: regex = None if isinstance(module.params['include'], string_types): includes = module.params['include'].split(',') else: includes = module.params['include'] include = [x.lower() for x in includes] valid_includes = ('address_class', 'certificate', 'client_ssl_profile', 'device', 'device_group', 'interface', 'key', 'node', 'pool', 'provision', 'rule', 'self_ip', 'software', 'system_info', 'traffic_group', 'trunk', 'virtual_address', 'virtual_server', 'vlan') include_test = (x in valid_includes for x in include) if not all(include_test): module.fail_json(msg="Value of include must be one or more of: %s, got: %s" % (",".join(valid_includes), ",".join(include))) try: facts = {} if len(include) > 0: f5 = F5(server, user, password, session, validate_certs, server_port) saved_active_folder = f5.get_active_folder() saved_recursive_query_state = f5.get_recursive_query_state() if saved_active_folder != "/": f5.set_active_folder("/") if saved_recursive_query_state != "STATE_ENABLED": f5.enable_recursive_query_state() if 'interface' in include: facts['interface'] = generate_interface_dict(f5, regex) if 'self_ip' in include: facts['self_ip'] = generate_self_ip_dict(f5, regex) if 'trunk' in include: facts['trunk'] = generate_trunk_dict(f5, regex) if 'vlan' in include: facts['vlan'] = generate_vlan_dict(f5, regex) if 'virtual_server' in include: facts['virtual_server'] = generate_vs_dict(f5, regex) if 'pool' in include: facts['pool'] = generate_pool_dict(f5, regex) if 'provision' in include: facts['provision'] = generate_provision_dict(f5) if 'device' in include: facts['device'] = generate_device_dict(f5, regex) if 'device_group' in include: facts['device_group'] = generate_device_group_dict(f5, regex) if 'traffic_group' in include: facts['traffic_group'] = generate_traffic_group_dict(f5, regex) if 'rule' in include: facts['rule'] = generate_rule_dict(f5, regex) if 'node' in include: facts['node'] = generate_node_dict(f5, regex) if 'virtual_address' in include: facts['virtual_address'] = generate_virtual_address_dict(f5, regex) if 'address_class' in include: facts['address_class'] = generate_address_class_dict(f5, regex) if 'software' in include: facts['software'] = generate_software_list(f5) if 'certificate' in include: facts['certificate'] = generate_certificate_dict(f5, regex) if 'key' in include: facts['key'] = generate_key_dict(f5, regex) if 'client_ssl_profile' in include: facts['client_ssl_profile'] = generate_client_ssl_profile_dict(f5, regex) if 'system_info' in include: facts['system_info'] = generate_system_info_dict(f5) # restore saved state if saved_active_folder and saved_active_folder != "/": f5.set_active_folder(saved_active_folder) if saved_recursive_query_state and \ saved_recursive_query_state != "STATE_ENABLED": f5.set_recursive_query_state(saved_recursive_query_state) result = dict( ansible_facts=facts, ) result.update(**facts) except Exception as e: module.fail_json(msg="received exception: %s\ntraceback: %s" % (e, traceback.format_exc())) module.exit_json(**result) if __name__ == '__main__': main()
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from UIObject import UIObject from TreeContentPanel import TreeContentPanel class TreeItem(UIObject): # also callable as TreeItem(widget) def __init__(self, html=None, **ka): self.children = [] self.contentPanel = None self.itemTable = None self.contentElem = None self.imgElem = None self.childSpanElem = None self.open = False self.parent = None self.selected = False self.tree = None self.userObject = None element = ka.pop('Element', None) or DOM.createDiv() self.setElement(element) self.itemTable = DOM.createTable() self.contentElem = DOM.createSpan() self.childSpanElem = DOM.createSpan() self.imgElem = DOM.createImg() tbody = DOM.createTBody() tr = DOM.createTR() tdImg = DOM.createTD() tdContent = DOM.createTD() DOM.appendChild(self.itemTable, tbody) DOM.appendChild(tbody, tr) DOM.appendChild(tr, tdImg) DOM.appendChild(tr, tdContent) DOM.setStyleAttribute(tdImg, "verticalAlign", "middle") DOM.setStyleAttribute(tdContent, "verticalAlign", "middle") DOM.setStyleAttribute(self.getElement(), "cursor", "pointer") DOM.appendChild(self.getElement(), self.itemTable) DOM.appendChild(self.getElement(), self.childSpanElem) DOM.appendChild(tdImg, self.imgElem) DOM.appendChild(tdContent, self.contentElem) # XXX - can't set pos relative on a div node, # or white_space on an HTML Table.. try: DOM.setAttribute(self.getElement(), "position", "relative") except: pass DOM.setStyleAttribute(self.contentElem, "display", "inline") DOM.setStyleAttribute(self.getElement(), "whiteSpace", "nowrap") try: DOM.setAttribute(self.itemTable, "whiteSpace", "nowrap") except: pass DOM.setStyleAttribute(self.childSpanElem, "whiteSpace", "nowrap") self.setStyleName(self.contentElem, "gwt-TreeItem", True) #if not ka.has_key('StyleName'): ka['StyleName']="gwt-TreeItem" if html is not None: if isinstance(html, str): ka['HTML'] = html else: ka['Widget'] = html UIObject.__init__(self, **ka) # also callable as addItem(widget) and addItem(itemText) def addItem(self, item): return self.insertItem(item) # also callable as addItem(widget) and addItem(itemText) def insertItem(self, item, index=None): if not hasattr(item, "getTree"): #if not item.getTree: item = TreeItem(item) if (item.getParentItem() is not None) or (item.getTree() is not None): item.remove() item.setTree(self.tree) item.setParentItem(self) if index is None: self.children.append(item) else: self.children.insert(index, item) DOM.setStyleAttribute(item.getElement(), "marginLeft", "16px") if index is None: DOM.appendChild(self.childSpanElem, item.getElement()) else: DOM.insertChild(self.childSpanElem, item.getElement(), index) if len(self.children) == 1: self.updateState() return item def getChild(self, index): if (index < 0) or (index >= len(self.children)): return None return self.children[index] def getChildCount(self): return len(self.children) def getChildIndex(self, child): return self.children.index(child) def getHTML(self): return DOM.getInnerHTML(self.contentElem) def getText(self): return DOM.getInnerText(self.contentElem) def getParentItem(self): return self.parent def getState(self): return self.open def getTree(self): return self.tree def getUserObject(self): return self.userObject def getWidget(self): if self.contentPanel is None: return None return self.contentPanel.getWidget() def isSelected(self): return self.selected def remove(self): if self.parent is not None: self.parent.removeItem(self) elif self.tree is not None: self.tree.removeItem(self) def removeItem(self, item): if item not in self.children: return item.setTree(None) item.setParentItem(None) self.children.remove(item) DOM.removeChild(self.childSpanElem, item.getElement()) if len(self.children) == 0: self.updateState() def removeItems(self): while self.getChildCount() > 0: self.removeItem(self.getChild(0)) def setHTML(self, html): self.clearContentPanel() DOM.setInnerHTML(self.contentElem, html) def setText(self, text): self.clearContentPanel() DOM.setInnerText(self.contentElem, text) def setSelected(self, selected): if self.selected == selected: return self.selected = selected self.setStyleName(self.contentElem, "gwt-TreeItem-selected", selected) def setState(self, open, fireEvents=True): # lkcl: experiment with allowing event state changed to be # fired even on items with no children. otherwise you never # get to find out if an end-item was selected! if not open or len(self.children) != 0: self.open = open self.updateState() if fireEvents: self.tree.fireStateChanged(self) def setUserObject(self, userObj): self.userObject = userObj def setWidget(self, widget): self.ensureContentPanel() self.contentPanel.setWidget(widget) def clearContentPanel(self): if self.contentPanel is not None: child = self.contentPanel.getWidget() if child is not None: self.contentPanel.remove(child) if self.tree is not None: self.tree.disown(self.contentPanel) self.contentPanel = None def ensureContentPanel(self): if self.contentPanel is None: DOM.setInnerHTML(self.contentElem, "") self.contentPanel = TreeContentPanel(self.contentElem) self.contentPanel.setTreeItem(self) if self.getTree() is not None: self.tree.adopt(self.contentPanel) def addTreeItems(self, accum): for item in self.children: accum.append(item) item.addTreeItems(accum) def getChildren(self): return self.children def getContentElem(self): return self.contentElem def getContentHeight(self): return DOM.getIntAttribute(self.itemTable, "offsetHeight") def getImageElement(self): return self.imgElem def getTreeTop(self): item = self ret = 0 while item is not None: ret += DOM.getIntAttribute(item.getElement(), "offsetTop") item = item.getParentItem() return ret def getFocusableWidget(self): widget = self.getWidget() if hasattr(widget, "setFocus"): return widget return None def imgSrc(self, img): if self.tree is None: return img src = self.tree.getImageBase() + img return src def setParentItem(self, parent): self.parent = parent def setTree(self, tree): if self.tree == tree: return if self.tree is not None: if self.tree.getSelectedItem() == self: self.tree.setSelectedItem(None) if self.contentPanel is not None: self.tree.disown(self.contentPanel) self.tree = tree for child in self.children: child.setTree(tree) self.updateState() if tree is not None and self.contentPanel is not None: tree.adopt(self.contentPanel) def updateState(self): if len(self.children) == 0: self.setVisible(self.childSpanElem, False) DOM.setAttribute(self.imgElem, "src", self.imgSrc("tree_white.gif")) return if self.open: self.setVisible(self.childSpanElem, True) DOM.setAttribute(self.imgElem, "src", self.imgSrc("tree_open.gif")) else: self.setVisible(self.childSpanElem, False) DOM.setAttribute(self.imgElem, "src", self.imgSrc("tree_closed.gif")) def updateStateRecursive(self): self.updateState() for i in range(len(self.children)): child = self.children[i] child.updateStateRecursive() class RootTreeItem(TreeItem): def addItem(self, item): self.insertItem(item) def insertItem(self, item, index=None): if (item.getParentItem() is not None) or (item.getTree() is not None): item.remove() item.setTree(self.getTree()) item.setParentItem(None) if index is None: self.children.append(item) else: self.children.insert(index, item) DOM.setIntStyleAttribute(item.getElement(), "marginLeft", 0) def removeItem(self, item): if item not in self.children: return item.setTree(None) item.setParentItem(None) self.children.remove(item) Factory.registerClass('pyjamas.ui.TreeItem', TreeItem) add TreeItem iterator # Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from UIObject import UIObject from TreeContentPanel import TreeContentPanel class TreeItem(UIObject): # also callable as TreeItem(widget) def __init__(self, html=None, **ka): self.children = [] self.contentPanel = None self.itemTable = None self.contentElem = None self.imgElem = None self.childSpanElem = None self.open = False self.parent = None self.selected = False self.tree = None self.userObject = None element = ka.pop('Element', None) or DOM.createDiv() self.setElement(element) self.itemTable = DOM.createTable() self.contentElem = DOM.createSpan() self.childSpanElem = DOM.createSpan() self.imgElem = DOM.createImg() tbody = DOM.createTBody() tr = DOM.createTR() tdImg = DOM.createTD() tdContent = DOM.createTD() DOM.appendChild(self.itemTable, tbody) DOM.appendChild(tbody, tr) DOM.appendChild(tr, tdImg) DOM.appendChild(tr, tdContent) DOM.setStyleAttribute(tdImg, "verticalAlign", "middle") DOM.setStyleAttribute(tdContent, "verticalAlign", "middle") DOM.setStyleAttribute(self.getElement(), "cursor", "pointer") DOM.appendChild(self.getElement(), self.itemTable) DOM.appendChild(self.getElement(), self.childSpanElem) DOM.appendChild(tdImg, self.imgElem) DOM.appendChild(tdContent, self.contentElem) # XXX - can't set pos relative on a div node, # or white_space on an HTML Table.. try: DOM.setAttribute(self.getElement(), "position", "relative") except: pass DOM.setStyleAttribute(self.contentElem, "display", "inline") DOM.setStyleAttribute(self.getElement(), "whiteSpace", "nowrap") try: DOM.setAttribute(self.itemTable, "whiteSpace", "nowrap") except: pass DOM.setStyleAttribute(self.childSpanElem, "whiteSpace", "nowrap") self.setStyleName(self.contentElem, "gwt-TreeItem", True) #if not ka.has_key('StyleName'): ka['StyleName']="gwt-TreeItem" if html is not None: if isinstance(html, str): ka['HTML'] = html else: ka['Widget'] = html UIObject.__init__(self, **ka) def __iter__(self): return self.getTree().__iter__() # also callable as addItem(widget) and addItem(itemText) def addItem(self, item): return self.insertItem(item) # also callable as addItem(widget) and addItem(itemText) def insertItem(self, item, index=None): if not hasattr(item, "getTree"): #if not item.getTree: item = TreeItem(item) if (item.getParentItem() is not None) or (item.getTree() is not None): item.remove() item.setTree(self.tree) item.setParentItem(self) if index is None: self.children.append(item) else: self.children.insert(index, item) DOM.setStyleAttribute(item.getElement(), "marginLeft", "16px") if index is None: DOM.appendChild(self.childSpanElem, item.getElement()) else: DOM.insertChild(self.childSpanElem, item.getElement(), index) if len(self.children) == 1: self.updateState() return item def getChild(self, index): if (index < 0) or (index >= len(self.children)): return None return self.children[index] def getChildCount(self): return len(self.children) def getChildIndex(self, child): return self.children.index(child) def getHTML(self): return DOM.getInnerHTML(self.contentElem) def getText(self): return DOM.getInnerText(self.contentElem) def getParentItem(self): return self.parent def getState(self): return self.open def getTree(self): return self.tree def getUserObject(self): return self.userObject def getWidget(self): if self.contentPanel is None: return None return self.contentPanel.getWidget() def isSelected(self): return self.selected def remove(self): if self.parent is not None: self.parent.removeItem(self) elif self.tree is not None: self.tree.removeItem(self) def removeItem(self, item): if item not in self.children: return item.setTree(None) item.setParentItem(None) self.children.remove(item) DOM.removeChild(self.childSpanElem, item.getElement()) if len(self.children) == 0: self.updateState() def removeItems(self): while self.getChildCount() > 0: self.removeItem(self.getChild(0)) def setHTML(self, html): self.clearContentPanel() DOM.setInnerHTML(self.contentElem, html) def setText(self, text): self.clearContentPanel() DOM.setInnerText(self.contentElem, text) def setSelected(self, selected): if self.selected == selected: return self.selected = selected self.setStyleName(self.contentElem, "gwt-TreeItem-selected", selected) def setState(self, open, fireEvents=True): # lkcl: experiment with allowing event state changed to be # fired even on items with no children. otherwise you never # get to find out if an end-item was selected! if not open or len(self.children) != 0: self.open = open self.updateState() if fireEvents: self.tree.fireStateChanged(self) def setUserObject(self, userObj): self.userObject = userObj def setWidget(self, widget): self.ensureContentPanel() self.contentPanel.setWidget(widget) def clearContentPanel(self): if self.contentPanel is not None: child = self.contentPanel.getWidget() if child is not None: self.contentPanel.remove(child) if self.tree is not None: self.tree.disown(self.contentPanel) self.contentPanel = None def ensureContentPanel(self): if self.contentPanel is None: DOM.setInnerHTML(self.contentElem, "") self.contentPanel = TreeContentPanel(self.contentElem) self.contentPanel.setTreeItem(self) if self.getTree() is not None: self.tree.adopt(self.contentPanel) def addTreeItems(self, accum): for item in self.children: accum.append(item) item.addTreeItems(accum) def getChildren(self): return self.children def getContentElem(self): return self.contentElem def getContentHeight(self): return DOM.getIntAttribute(self.itemTable, "offsetHeight") def getImageElement(self): return self.imgElem def getTreeTop(self): item = self ret = 0 while item is not None: ret += DOM.getIntAttribute(item.getElement(), "offsetTop") item = item.getParentItem() return ret def getFocusableWidget(self): widget = self.getWidget() if hasattr(widget, "setFocus"): return widget return None def imgSrc(self, img): if self.tree is None: return img src = self.tree.getImageBase() + img return src def setParentItem(self, parent): self.parent = parent def setTree(self, tree): if self.tree == tree: return if self.tree is not None: if self.tree.getSelectedItem() == self: self.tree.setSelectedItem(None) if self.contentPanel is not None: self.tree.disown(self.contentPanel) self.tree = tree for child in self.children: child.setTree(tree) self.updateState() if tree is not None and self.contentPanel is not None: tree.adopt(self.contentPanel) def updateState(self): if len(self.children) == 0: self.setVisible(self.childSpanElem, False) DOM.setAttribute(self.imgElem, "src", self.imgSrc("tree_white.gif")) return if self.open: self.setVisible(self.childSpanElem, True) DOM.setAttribute(self.imgElem, "src", self.imgSrc("tree_open.gif")) else: self.setVisible(self.childSpanElem, False) DOM.setAttribute(self.imgElem, "src", self.imgSrc("tree_closed.gif")) def updateStateRecursive(self): self.updateState() for i in range(len(self.children)): child = self.children[i] child.updateStateRecursive() class RootTreeItem(TreeItem): def addItem(self, item): self.insertItem(item) def insertItem(self, item, index=None): if (item.getParentItem() is not None) or (item.getTree() is not None): item.remove() item.setTree(self.getTree()) item.setParentItem(None) if index is None: self.children.append(item) else: self.children.insert(index, item) DOM.setIntStyleAttribute(item.getElement(), "marginLeft", 0) def removeItem(self, item): if item not in self.children: return item.setTree(None) item.setParentItem(None) self.children.remove(item) Factory.registerClass('pyjamas.ui.TreeItem', TreeItem)
# -*- coding: utf-8 -*- import datetime metric_short_description=\ _("вычисляет среднее время ожидания в очереди.") metric_description=\ _(""" Среднее время ожидания в очереди для задач пользователя. Выражает степень недовольства пользователей вычислительным кластером, поскольку никому не хочется находиться в очереди долго. требует параметров: count_mode - возможные значения: (user, group, class, day, total) """) class Metric_counter(object): """ Класс задающий метрику """ def __init__(self,tasks_list,parameters): """ Собственно конструирование объекта """ self.tasks_list=tasks_list self.parameters=dict() if parameters != "": for item in parameters.split(','): pair=item.strip().split('=') self.parameters[pair[0]]=pair[1].strip("'\"") if "count_mode" not in self.parameters.keys(): self.parameters["count_mode"]="user" def __str__(self): s="package %s: Metric_counter: " % __name__ s+="tasks_list=%s, " % str(self.tasks_list) s+="parameters=%s " % str(self.parameters) return s def get_metric_name(self): return __name__ def count_values(self,compression): """ Подсчитать и выдать число, словарь значений, и т.п. """ mes=_("\n\n\trun metric %s:") % self.get_metric_name() mes+=_("\tmetric parameters is: %s\n\n") % self.parameters print mes mode=self.parameters['count_mode'] tmp_result=dict() if mode == "user": for task in self.tasks_list: if task.user_name not in tmp_result.keys(): tmp_result[task.user_name]=(datetime.timedelta(minutes=0),0) if task.time_start > task.time_submit: waitings, ones = tmp_result[task.user_name] tmp_result[task.user_name]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) if mode == "group": for task in self.tasks_list: if task.group_name not in tmp_result.keys(): tmp_result[task.group_name]=(datetime.timedelta(minutes=0),0) if task.time_start > task.time_submit: waitings, ones = tmp_result[task.group_name] tmp_result[task.group_name]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) if mode == "class": for task in self.tasks_list: if task.task_class not in tmp_result.keys(): tmp_result[task.task_class]=(datetime.timedelta(minutes=0),0) if task.time_start > task.time_submit: waitings, ones = tmp_result[task.task_class] tmp_result[task.task_class]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) if mode == "day": first_day=self.tasks_list[0].time_submit.date() for task in self.tasks_list: if self.parameters['plot_format'] == 'true': date=(task.time_submit.date()-first_day).days else: date=task.time_submit.date() if date not in tmp_result.keys(): tmp_result[date]=(datetime.timedelta(minutes=0),0) if task.time_start > task.time_submit: waitings, ones = tmp_result[date] tmp_result[date]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) if mode == "total": tmp_result["total"]=(datetime.timedelta(minutes=0),0) for task in self.tasks_list: date=task.time_submit.date() if task.time_start > task.time_submit: waitings, ones = tmp_result["total"] tmp_result["total"]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) result=dict() for key, record in tmp_result.items(): if record[1]: ave_duration = ( record[0] * compression ) / record[1] result[key]=ave_duration.total_seconds() / 60 else: result[key] = 0 return result def get_header_string(self): """ Выдаём строку заголовок для печати всего в .csv файл """ mode=self.parameters['count_mode'] if mode == "user": return "\"%s\"\t\"%s\"" % (_("Users"), _("Duration (minutes)")) if mode == "group": return "\"%s\"\t\"%s\"" % (_("Groups"), _("Duration (minutes)")) if mode == "class": return "\"%s\"\t\"%s\"" % (_("Classes"), _("Duration (minutes)")) if mode == "day": return "\"%s\"\t\"%s\"" % (_("Date (YYYY-MM-DD)"), _("Duration (minutes)")) if mode == "total": return "\"%s\"\t\"%s\"" % (_("Totally"), _("Duration (minutes)")) return None def get_draw_type(self): """ Выдаёт: chart - если отображаемо как набор столбиков, plot - если кривая y=f(x) """ mode=self.parameters['count_mode'] if (mode == "user") or (mode == "group") or (mode == "class"): return "chart" if mode == "day": return "plot" return None def format_row(self,key,values_row): """ Форматирует запись к виду пригодному для печати в .csv формате. """ mode=self.parameters['count_mode'] if (mode == "user") or (mode == "group") or (mode == "class"): return "\"%s\"\t%d" % (key, values_row) if mode == "day": if self.parameters['plot_format'] == 'true': return "\"%s\"\t%d" % (key, values_row) else: return "\"%s\"\t%d" % (key.strftime("%Y-%m-%d"), values_row) if mode == "total": return "\"%s\"\t%d" % (key, values_row) return None Message changed # -*- coding: utf-8 -*- import datetime metric_short_description=\ _("вычисляет среднее время ожидания в очереди.") metric_description=\ _(""" Среднее время ожидания в очереди для задач пользователя. Выражает степень недовольства пользователей вычислительным кластером, поскольку никому не хочется находиться в очереди долго. требует параметров: count_mode - возможные значения: (user, group, class, day, total) """) class Metric_counter(object): """ Класс задающий метрику """ def __init__(self,tasks_list,parameters): """ Собственно конструирование объекта """ self.tasks_list=tasks_list self.parameters=dict() if parameters != "": for item in parameters.split(','): pair=item.strip().split('=') self.parameters[pair[0]]=pair[1].strip("'\"") if "count_mode" not in self.parameters.keys(): self.parameters["count_mode"]="user" def __str__(self): s="package %s: Metric_counter: " % __name__ s+="tasks_list=%s, " % str(self.tasks_list) s+="parameters=%s " % str(self.parameters) return s def get_metric_name(self): return __name__ def count_values(self,compression): """ Подсчитать и выдать число, словарь значений, и т.п. """ mes=_("\n\n\trun metric %s:") % self.get_metric_name() mes+=_("\tmetric parameters is: %s\n\n") % self.parameters print mes mode=self.parameters['count_mode'] tmp_result=dict() if mode == "user": for task in self.tasks_list: if task.user_name not in tmp_result.keys(): tmp_result[task.user_name]=(datetime.timedelta(minutes=0),0) if task.time_start > task.time_submit: waitings, ones = tmp_result[task.user_name] tmp_result[task.user_name]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) if mode == "group": for task in self.tasks_list: if task.group_name not in tmp_result.keys(): tmp_result[task.group_name]=(datetime.timedelta(minutes=0),0) if task.time_start > task.time_submit: waitings, ones = tmp_result[task.group_name] tmp_result[task.group_name]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) if mode == "class": for task in self.tasks_list: if task.task_class not in tmp_result.keys(): tmp_result[task.task_class]=(datetime.timedelta(minutes=0),0) if task.time_start > task.time_submit: waitings, ones = tmp_result[task.task_class] tmp_result[task.task_class]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) if mode == "day": first_day=self.tasks_list[0].time_submit.date() for task in self.tasks_list: if self.parameters['plot_format'] == 'true': date=(task.time_submit.date()-first_day).days else: date=task.time_submit.date() if date not in tmp_result.keys(): tmp_result[date]=(datetime.timedelta(minutes=0),0) if task.time_start > task.time_submit: waitings, ones = tmp_result[date] tmp_result[date]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) if mode == "total": tmp_result["total"]=(datetime.timedelta(minutes=0),0) for task in self.tasks_list: date=task.time_submit.date() if task.time_start > task.time_submit: waitings, ones = tmp_result["total"] tmp_result["total"]=( waitings + (task.time_start - task.time_submit) , ones + 1 ) result=dict() for key, record in tmp_result.items(): if record[1]: ave_duration = ( record[0] * compression ) / record[1] result[key]=ave_duration.total_seconds() / 60 else: result[key] = 0 return result def get_header_string(self): """ Выдаём строку заголовок для печати всего в .csv файл """ mode=self.parameters['count_mode'] if mode == "user": return "\"%s\"\t\"%s\"" % (_("Users"), _("Duration (minutes)")) if mode == "group": return "\"%s\"\t\"%s\"" % (_("Groups"), _("Duration (minutes)")) if mode == "class": return "\"%s\"\t\"%s\"" % (_("Classes"), _("Duration (minutes)")) if mode == "day": if self.parameters['plot_format'] == 'true': return "\"%s\"\t\"%s\"" % (_("Day number"), _("Duration (minutes)")) else: return "\"%s\"\t\"%s\"" % (_("Date (YYYY-MM-DD)"), _("Duration (minutes)")) if mode == "total": return "\"%s\"\t\"%s\"" % (_("Totally"), _("Duration (minutes)")) return None def get_draw_type(self): """ Выдаёт: chart - если отображаемо как набор столбиков, plot - если кривая y=f(x) """ mode=self.parameters['count_mode'] if (mode == "user") or (mode == "group") or (mode == "class"): return "chart" if mode == "day": return "plot" return None def format_row(self,key,values_row): """ Форматирует запись к виду пригодному для печати в .csv формате. """ mode=self.parameters['count_mode'] if (mode == "user") or (mode == "group") or (mode == "class"): return "\"%s\"\t%d" % (key, values_row) if mode == "day": if self.parameters['plot_format'] == 'true': return "\"%s\"\t%d" % (key, values_row) else: return "\"%s\"\t%d" % (key.strftime("%Y-%m-%d"), values_row) if mode == "total": return "\"%s\"\t%d" % (key, values_row) return None
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from pyjamas import Window from pyjamas.ui import Applier def setStyleName(element, style, add): oldStyle = DOM.getAttribute(element, "className") if oldStyle is None: oldStyle = "" idx = oldStyle.find(style) # Calculate matching index lastPos = len(oldStyle) while idx != -1: if idx == 0 or (oldStyle[idx - 1] == " "): last = idx + len(style) if (last == lastPos) or ((last < lastPos) and (oldStyle[last] == " ")): break idx = oldStyle.find(style, idx + 1) if add: if idx == -1: DOM.setAttribute(element, "className", oldStyle + " " + style) else: if idx != -1: if idx == 0: begin = '' else: begin = oldStyle[:idx-1] end = oldStyle[idx + len(style):] DOM.setAttribute(element, "className", begin + end) class UIObject(Applier): _props = [ ("visible", "Visibility", "Visible", None), ("stylename", "Style name", "StyleName", None), ("width", "Width", "Width", None), ("height", "Height", "Height", None), ("size", "Size", "Size", None), ("title", "Title", "Title", None), ("zindex", "Z Index", "zIndex", None), ] @classmethod def _getProps(self): return Applier._getProps() + self._props def __init__(self, **kwargs): # do not initialise element, here, to None, whatever you do. # there are circumstances where UIObject.__init__ is the last # thing that is done in derived classes, where self.setElement # will _already_ have been called. Applier.__init__(self, **kwargs) def getAbsoluteLeft(self): return DOM.getAbsoluteLeft(self.getElement()) def getAbsoluteTop(self): return DOM.getAbsoluteTop(self.getElement()) def getElement(self): """Get the DOM element associated with the UIObject, if any""" return self.element def getOffsetHeight(self): return DOM.getIntAttribute(self.element, "offsetHeight") def getOffsetWidth(self): return DOM.getIntAttribute(self.element, "offsetWidth") def getStyleName(self): return DOM.getAttribute(self.element, "className") def getStylePrimaryName(self): """Return with the first className if there are multiples""" fullClassName = self.getStyleName() if fullClassName: return fullClassName.split()[0] def getStyleAttribute(self, attribute): """ can be called with two forms: getStyleAttribute(self, attr) - returns value getStyleAttribute(self, (attr1,attr2,...)) - returns dictionary of attr:value pairs """ if isinstance(attribute, str): return DOM.getStyleAttribute(self.getElement(), attribute) # if attribute is not a string, assume it is iterable, # and return the multi-attribute form el = self.getElement() result = {} for attr in attribute: result[attr] = DOM.getStyleAttribute(el,attr) return result def getTitle(self): return DOM.getAttribute(self.element, "title") def setElement(self, element): """Set the DOM element associated with the UIObject.""" self.element = element def setHeight(self, height): """Set the height of the element associated with this UIObject. The value should be given as a CSS value, such as 100px, 30%, or 50pi """ DOM.setStyleAttribute(self.element, "height", str(height)) def getHeight(self): return DOM.getStyleAttribute(self.element, "height") def setPixelSize(self, width, height): """Set the width and height of the element associated with this UIObject in pixels. Width and height should be numbers. """ if width >= 0: self.setWidth("%dpx" % width) if height >= 0: self.setHeight("%dpx" % height) def setSize(self, width, height): """Set the width and height of the element associated with this UIObject. The values should be given as a CSS value, such as 100px, 30%, or 50pi """ self.setWidth(width) self.setHeight(height) def addStyleName(self, style): """Append a style to the element associated with this UIObject. This is a CSS class name. It will be added after any already-assigned CSS class for the element. """ self.setStyleName(self.element, style, True) def addStyleDependentName(self, styleSuffix): """Adds a secondary or dependent style name to this element. For example if the primary stylename is gwt-TextBox, self.addStyleDependentName("readonly") will return gwt-TextBox-readonly. """ self.addStyleName(self.getStylePrimaryName()+"-"+styleSuffix) def removeStyleName(self, style): """Remove a style from the element associated with this UIObject. This is a CSS class name.""" self.setStyleName(self.element, style, False) def removeStyleDependentName(self, styleSuffix): """Remove a dependent style name by specifying the style name's suffix. """ self.removeStyleName(self.getStylePrimaryName()+"-"+styleSuffix) # also callable as: setStyleName(self, style) def setStyleName(self, element, style=None, add=True): """When called with a single argument, this replaces all the CSS classes associated with this UIObject's element with the given parameter. Otherwise, this is assumed to be a worker function for addStyleName and removeStyleName. """ # emulate setStyleName(self, style) if style is None: style = element DOM.setAttribute(self.element, "className", style) return setStyleName(element, style, add) def setStyleAttribute(self, attribute, value=None): """ can be called with two forms: single attr: setStyleAttribute(self, attr, value) multi attr: setStyleAttribute(self, {attr1:val1, attr2:val2, ...}) """ if value is not None: # assume single attr form DOM.setStyleAttribute(self.getElement(), attribute, value) return # assume multi value form el = self.getElement() for attr, val in attribute.items(): DOM.setStyleAttribute(el, attr, val) def setTitle(self, title): DOM.setAttribute(self.element, "title", title) def setWidth(self, width): """Set the width of the element associated with this UIObject. The value should be given as a CSS value, such as 100px, 30%, or 50pi """ DOM.setStyleAttribute(self.element, "width", str(width)) def getWidth(self): return DOM.getStyleAttribute(self.element, "width") def sinkEvents(self, eventBitsToAdd): """Request that the given events be delivered to the event handler for this element. The event bits passed are added (using inclusive OR) to the events already "sunk" for the element associated with the UIObject. The event bits are a combination of values from class L{Event}. """ if self.element: DOM.sinkEvents(self.getElement(), eventBitsToAdd | DOM.getEventsSunk(self.getElement())) def setzIndex(self, index): DOM.setIntStyleAttribute(self.element, "zIndex", index) def isVisible(self, element=None): """ XXX DEPRECATED - use getVisible """ return self.getVisible(element) def getVisible(self, element=None): """Determine whether this element is currently visible, by checking the CSS property 'display' """ if not element: element = self.element try: # yuk! return element.style.display != "none" except AttributeError: # not been set (yet?) return True # also callable as: setVisible(visible) def setVisible(self, element, visible=None): """Set whether this element is visible or not. If a single parameter is given, the self.element is used. This modifies the CSS property 'display', which means that an invisible element not only is not drawn, but doesn't occupy any space on the page. """ if visible is None: visible = element element = self.element if visible: DOM.setStyleAttribute(element, 'display', "") else: DOM.setStyleAttribute(element, 'display', "none") def unsinkEvents(self, eventBitsToRemove): """Reverse the operation of sinkEvents. See L{UIObject.sinkevents}. """ DOM.sinkEvents(self.getElement(), ~eventBitsToRemove & DOM.getEventsSunk(self.getElement())) Factory.registerClass('pyjamas.ui.UIObject', 'UIObject', UIObject) line reduction # Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from pyjamas import Window from pyjamas.ui import Applier def setStyleName(element, style, add): oldStyle = DOM.getAttribute(element, "className") if oldStyle is None: oldStyle = "" idx = oldStyle.find(style) # Calculate matching index lastPos = len(oldStyle) while idx != -1: if idx == 0 or (oldStyle[idx - 1] == " "): last = idx + len(style) if (last == lastPos) or ((last < lastPos) and (oldStyle[last] == " ")): break idx = oldStyle.find(style, idx + 1) if add: if idx == -1: DOM.setAttribute(element, "className", oldStyle + " " + style) else: if idx != -1: if idx == 0: begin = '' else: begin = oldStyle[:idx-1] end = oldStyle[idx + len(style):] DOM.setAttribute(element, "className", begin + end) class UIObject(Applier): _props = [ ("visible", "Visibility", "Visible", None), ("stylename", "Style name", "StyleName", None), ("width", "Width", "Width", None), ("height", "Height", "Height", None), ("size", "Size", "Size", None), ("title", "Title", "Title", None), ("zindex", "Z Index", "zIndex", None), ] @classmethod def _getProps(self): return Applier._getProps() + self._props def __init__(self, **kwargs): # do not initialise element, here, to None, whatever you do. # there are circumstances where UIObject.__init__ is the last # thing that is done in derived classes, where self.setElement # will _already_ have been called. Applier.__init__(self, **kwargs) def getAbsoluteLeft(self): return DOM.getAbsoluteLeft(self.getElement()) def getAbsoluteTop(self): return DOM.getAbsoluteTop(self.getElement()) def getElement(self): """Get the DOM element associated with the UIObject, if any""" return self.element def getOffsetHeight(self): return DOM.getIntAttribute(self.element, "offsetHeight") def getOffsetWidth(self): return DOM.getIntAttribute(self.element, "offsetWidth") def getStyleName(self): return DOM.getAttribute(self.element, "className") def getStylePrimaryName(self): """Return with the first className if there are multiples""" fullClassName = self.getStyleName() if fullClassName: return fullClassName.split()[0] def getStyleAttribute(self, attribute): """ can be called with two forms: getStyleAttribute(self, attr) - returns value getStyleAttribute(self, (attr1,attr2,...)) - returns dictionary of attr:value pairs """ if isinstance(attribute, str): return DOM.getStyleAttribute(self.getElement(), attribute) # if attribute is not a string, assume it is iterable, # and return the multi-attribute form el = self.getElement() result = {} for attr in attribute: result[attr] = DOM.getStyleAttribute(el,attr) return result def getTitle(self): return DOM.getAttribute(self.element, "title") def setElement(self, element): """Set the DOM element associated with the UIObject.""" self.element = element def setHeight(self, height): """Set the height of the element associated with this UIObject. The value should be given as a CSS value, such as 100px, 30%, or 50pi """ DOM.setStyleAttribute(self.element, "height", str(height)) def getHeight(self): return DOM.getStyleAttribute(self.element, "height") def setPixelSize(self, width, height): """Set the width and height of the element associated with this UIObject in pixels. Width and height should be numbers. """ if width >= 0: self.setWidth("%dpx" % width) if height >= 0: self.setHeight("%dpx" % height) def setSize(self, width, height): """Set the width and height of the element associated with this UIObject. The values should be given as a CSS value, such as 100px, 30%, or 50pi """ self.setWidth(width) self.setHeight(height) def addStyleName(self, style): """Append a style to the element associated with this UIObject. This is a CSS class name. It will be added after any already-assigned CSS class for the element. """ self.setStyleName(self.element, style, True) def addStyleDependentName(self, styleSuffix): """Adds a secondary or dependent style name to this element. For example if the primary stylename is gwt-TextBox, self.addStyleDependentName("readonly") will return gwt-TextBox-readonly. """ self.addStyleName(self.getStylePrimaryName()+"-"+styleSuffix) def removeStyleName(self, style): """Remove a style from the element associated with this UIObject. This is a CSS class name.""" self.setStyleName(self.element, style, False) def removeStyleDependentName(self, styleSuffix): """Remove a dependent style name by specifying the style name's suffix. """ self.removeStyleName(self.getStylePrimaryName()+"-"+styleSuffix) # also callable as: setStyleName(self, style) def setStyleName(self, element, style=None, add=True): """When called with a single argument, this replaces all the CSS classes associated with this UIObject's element with the given parameter. Otherwise, this is assumed to be a worker function for addStyleName and removeStyleName. """ # emulate setStyleName(self, style) if style is not None: setStyleName(element, style, add) style = element DOM.setAttribute(self.element, "className", style) def setStyleAttribute(self, attribute, value=None): """ can be called with two forms: single attr: setStyleAttribute(self, attr, value) multi attr: setStyleAttribute(self, {attr1:val1, attr2:val2, ...}) """ if value is not None: # assume single attr form DOM.setStyleAttribute(self.getElement(), attribute, value) return # assume multi value form el = self.getElement() for attr, val in attribute.items(): DOM.setStyleAttribute(el, attr, val) def setTitle(self, title): DOM.setAttribute(self.element, "title", title) def setWidth(self, width): """Set the width of the element associated with this UIObject. The value should be given as a CSS value, such as 100px, 30%, or 50pi """ DOM.setStyleAttribute(self.element, "width", str(width)) def getWidth(self): return DOM.getStyleAttribute(self.element, "width") def sinkEvents(self, eventBitsToAdd): """Request that the given events be delivered to the event handler for this element. The event bits passed are added (using inclusive OR) to the events already "sunk" for the element associated with the UIObject. The event bits are a combination of values from class L{Event}. """ if self.element: DOM.sinkEvents(self.getElement(), eventBitsToAdd | DOM.getEventsSunk(self.getElement())) def setzIndex(self, index): DOM.setIntStyleAttribute(self.element, "zIndex", index) def isVisible(self, element=None): """ XXX DEPRECATED - use getVisible """ return self.getVisible(element) def getVisible(self, element=None): """Determine whether this element is currently visible, by checking the CSS property 'display' """ if not element: element = self.element try: # yuk! return element.style.display != "none" except AttributeError: # not been set (yet?) return True # also callable as: setVisible(visible) def setVisible(self, element, visible=None): """Set whether this element is visible or not. If a single parameter is given, the self.element is used. This modifies the CSS property 'display', which means that an invisible element not only is not drawn, but doesn't occupy any space on the page. """ if visible is None: visible = element element = self.element if visible: DOM.setStyleAttribute(element, 'display', "") else: DOM.setStyleAttribute(element, 'display', "none") def unsinkEvents(self, eventBitsToRemove): """Reverse the operation of sinkEvents. See L{UIObject.sinkevents}. """ DOM.sinkEvents(self.getElement(), ~eventBitsToRemove & DOM.getEventsSunk(self.getElement())) Factory.registerClass('pyjamas.ui.UIObject', 'UIObject', UIObject)
from rest_framework import serializers from rest_framework.exceptions import ValidationError from desecapi.models import Domain, Donation, User, RR, RRset, Token from djoser import serializers as djoserSerializers from django.db import models, transaction import django.core.exceptions from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin import re from rest_framework.fields import empty class TokenSerializer(serializers.ModelSerializer): value = serializers.ReadOnlyField(source='key') # note this overrides the original "id" field, which is the db primary key id = serializers.ReadOnlyField(source='user_specific_id') class Meta: model = Token fields = ('id', 'created', 'name', 'value',) read_only_fields = ('created', 'value', 'id') class RRSerializer(serializers.ModelSerializer): class Meta: model = RR fields = ('content',) def to_internal_value(self, data): if not isinstance(data, dict): data = {'content': data} return super().to_internal_value(data) class RRsetBulkListSerializer(BulkListSerializer): @transaction.atomic def update(self, queryset, validated_data): q = models.Q(pk__isnull=True) for data in validated_data: q |= models.Q(subname=data.get('subname', ''), type=data['type']) rrsets = {(obj.subname, obj.type): obj for obj in queryset.filter(q)} instance = [rrsets.get((data.get('subname', ''), data['type']), None) for data in validated_data] return self.child._save(instance, validated_data) @transaction.atomic def create(self, validated_data): return self.child._save([None] * len(validated_data), validated_data) class RRsetTypeField(serializers.CharField): def validate_empty_values(self, data): # The type field is always required, regardless of PATCH or not if data is empty: self.fail('required') return super().validate_empty_values(data) class SlugRRField(serializers.SlugRelatedField): def __init__(self, *args, **kwargs): kwargs['slug_field'] = 'content' kwargs['queryset'] = RR.objects.all() super().__init__(*args, **kwargs) def to_internal_value(self, data): return RR(**{self.slug_field: data}) class RRsetSerializer(BulkSerializerMixin, serializers.ModelSerializer): domain = serializers.StringRelatedField() subname = serializers.CharField(allow_blank=True, required=False) type = RRsetTypeField() records = SlugRRField(many=True) class Meta: model = RRset fields = ('id', 'domain', 'subname', 'name', 'records', 'ttl', 'type',) list_serializer_class = RRsetBulkListSerializer def _save(self, instance, validated_data): bulk = isinstance(instance, list) if not bulk: instance = [instance] validated_data = [validated_data] name = self.context['view'].kwargs['name'] domain = self.context['request'].user.domains.get(name=name) method = self.context['request'].method errors = [] rrsets = {} rrsets_seen = set() for rrset, data in zip(instance, validated_data): # Construct RRset records = data.pop('records', None) if rrset: # We have a known instance (update). Update fields if given. rrset.subname = data.get('subname', rrset.subname) rrset.type = data.get('type', rrset.type) rrset.ttl = data.get('ttl', rrset.ttl) else: # No known instance (creation or meaningless request) if not 'ttl' in data: if records: # If we have records, this is a creation request, so we # need a TTL. errors.append({'ttl': ['This field is required for new RRsets.']}) continue else: # If this request is meaningless, we still want it to # be processed by pdns for type validation. In this # case, we need some dummy TTL. data['ttl'] = data.get('ttl', 1) data.pop('id', None) data['domain'] = domain rrset = RRset(**data) # Verify that we have not seen this RRset before if (rrset.subname, rrset.type) in rrsets_seen: errors.append({'__all__': ['RRset repeated with same subname and type.']}) continue rrsets_seen.add((rrset.subname, rrset.type)) # Validate RRset. Raises error if type or subname have been changed # or if new RRset is not unique. validate_unique = (method == 'POST') try: rrset.full_clean(exclude=['updated'], validate_unique=validate_unique) except django.core.exceptions.ValidationError as e: errors.append(e.message_dict) continue # Construct dictionary of RR lists to write, indexed by their RRset if records is None: rrsets[rrset] = None else: rr_data = [{'content': x.content} for x in records] # Use RRSerializer to validate records inputs allow_empty = (method in ('PATCH', 'PUT')) rr_serializer = RRSerializer(data=rr_data, many=True, allow_empty=allow_empty) if not rr_serializer.is_valid(): error = rr_serializer.errors if 'non_field_errors' in error: error['records'] = error.pop('non_field_errors') errors.append(error) continue # Blessings have been given, so add RRset to the to-write dict rrsets[rrset] = [RR(rrset=rrset, **rr_validated_data) for rr_validated_data in rr_serializer.validated_data] errors.append({}) if any(errors): raise ValidationError(errors if bulk else errors[0]) # Now try to save RRsets try: rrsets = domain.write_rrsets(rrsets) except django.core.exceptions.ValidationError as e: for attr in ['errors', 'error_dict', 'message']: detail = getattr(e, attr, None) if detail: raise ValidationError(detail) raise ValidationError(str(e)) except ValueError as e: raise ValidationError({'__all__': str(e)}) return rrsets if bulk else rrsets[0] @transaction.atomic def update(self, instance, validated_data): return self._save(instance, validated_data) @transaction.atomic def create(self, validated_data): return self._save(None, validated_data) def validate_type(self, value): if value in RRset.DEAD_TYPES: raise serializers.ValidationError( "The %s RRset type is currently unsupported." % value) if value in RRset.RESTRICTED_TYPES: raise serializers.ValidationError( "You cannot tinker with the %s RRset." % value) if value.startswith('TYPE'): raise serializers.ValidationError( "Generic type format is not supported.") return value def to_representation(self, instance): data = super().to_representation(instance) data.pop('id') return data class DomainSerializer(serializers.ModelSerializer): name = serializers.RegexField(regex=r'^[A-Za-z0-9_.-]+$', trim_whitespace=False) class Meta: model = Domain fields = ('created', 'published', 'name', 'keys') class DonationSerializer(serializers.ModelSerializer): class Meta: model = Donation fields = ('name', 'iban', 'bic', 'amount', 'message', 'email') def validate_bic(self, value): return re.sub(r'[\s]', '', value) def validate_iban(self, value): return re.sub(r'[\s]', '', value) class UserSerializer(djoserSerializers.UserSerializer): locked = serializers.SerializerMethodField() class Meta(djoserSerializers.UserSerializer.Meta): fields = tuple(User.REQUIRED_FIELDS) + ( User.USERNAME_FIELD, 'dyn', 'limit_domains', 'locked', ) read_only_fields = ('dyn', 'limit_domains', 'locked',) def get_locked(self, obj): return bool(obj.locked) class UserCreateSerializer(djoserSerializers.UserCreateSerializer): class Meta(djoserSerializers.UserCreateSerializer.Meta): fields = tuple(User.REQUIRED_FIELDS) + ( User.USERNAME_FIELD, 'password', 'dyn', ) fix(api): check for maximum domain name length from rest_framework import serializers from rest_framework.exceptions import ValidationError from desecapi.models import Domain, Donation, User, RR, RRset, Token from djoser import serializers as djoserSerializers from django.db import models, transaction import django.core.exceptions from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin import re from rest_framework.fields import empty class TokenSerializer(serializers.ModelSerializer): value = serializers.ReadOnlyField(source='key') # note this overrides the original "id" field, which is the db primary key id = serializers.ReadOnlyField(source='user_specific_id') class Meta: model = Token fields = ('id', 'created', 'name', 'value',) read_only_fields = ('created', 'value', 'id') class RRSerializer(serializers.ModelSerializer): class Meta: model = RR fields = ('content',) def to_internal_value(self, data): if not isinstance(data, dict): data = {'content': data} return super().to_internal_value(data) class RRsetBulkListSerializer(BulkListSerializer): @transaction.atomic def update(self, queryset, validated_data): q = models.Q(pk__isnull=True) for data in validated_data: q |= models.Q(subname=data.get('subname', ''), type=data['type']) rrsets = {(obj.subname, obj.type): obj for obj in queryset.filter(q)} instance = [rrsets.get((data.get('subname', ''), data['type']), None) for data in validated_data] return self.child._save(instance, validated_data) @transaction.atomic def create(self, validated_data): return self.child._save([None] * len(validated_data), validated_data) class RRsetTypeField(serializers.CharField): def validate_empty_values(self, data): # The type field is always required, regardless of PATCH or not if data is empty: self.fail('required') return super().validate_empty_values(data) class SlugRRField(serializers.SlugRelatedField): def __init__(self, *args, **kwargs): kwargs['slug_field'] = 'content' kwargs['queryset'] = RR.objects.all() super().__init__(*args, **kwargs) def to_internal_value(self, data): return RR(**{self.slug_field: data}) class RRsetSerializer(BulkSerializerMixin, serializers.ModelSerializer): domain = serializers.StringRelatedField() subname = serializers.CharField(allow_blank=True, required=False) type = RRsetTypeField() records = SlugRRField(many=True) class Meta: model = RRset fields = ('id', 'domain', 'subname', 'name', 'records', 'ttl', 'type',) list_serializer_class = RRsetBulkListSerializer def _save(self, instance, validated_data): bulk = isinstance(instance, list) if not bulk: instance = [instance] validated_data = [validated_data] name = self.context['view'].kwargs['name'] domain = self.context['request'].user.domains.get(name=name) method = self.context['request'].method errors = [] rrsets = {} rrsets_seen = set() for rrset, data in zip(instance, validated_data): # Construct RRset records = data.pop('records', None) if rrset: # We have a known instance (update). Update fields if given. rrset.subname = data.get('subname', rrset.subname) rrset.type = data.get('type', rrset.type) rrset.ttl = data.get('ttl', rrset.ttl) else: # No known instance (creation or meaningless request) if not 'ttl' in data: if records: # If we have records, this is a creation request, so we # need a TTL. errors.append({'ttl': ['This field is required for new RRsets.']}) continue else: # If this request is meaningless, we still want it to # be processed by pdns for type validation. In this # case, we need some dummy TTL. data['ttl'] = data.get('ttl', 1) data.pop('id', None) data['domain'] = domain rrset = RRset(**data) # Verify that we have not seen this RRset before if (rrset.subname, rrset.type) in rrsets_seen: errors.append({'__all__': ['RRset repeated with same subname and type.']}) continue rrsets_seen.add((rrset.subname, rrset.type)) # Validate RRset. Raises error if type or subname have been changed # or if new RRset is not unique. validate_unique = (method == 'POST') try: rrset.full_clean(exclude=['updated'], validate_unique=validate_unique) except django.core.exceptions.ValidationError as e: errors.append(e.message_dict) continue # Construct dictionary of RR lists to write, indexed by their RRset if records is None: rrsets[rrset] = None else: rr_data = [{'content': x.content} for x in records] # Use RRSerializer to validate records inputs allow_empty = (method in ('PATCH', 'PUT')) rr_serializer = RRSerializer(data=rr_data, many=True, allow_empty=allow_empty) if not rr_serializer.is_valid(): error = rr_serializer.errors if 'non_field_errors' in error: error['records'] = error.pop('non_field_errors') errors.append(error) continue # Blessings have been given, so add RRset to the to-write dict rrsets[rrset] = [RR(rrset=rrset, **rr_validated_data) for rr_validated_data in rr_serializer.validated_data] errors.append({}) if any(errors): raise ValidationError(errors if bulk else errors[0]) # Now try to save RRsets try: rrsets = domain.write_rrsets(rrsets) except django.core.exceptions.ValidationError as e: for attr in ['errors', 'error_dict', 'message']: detail = getattr(e, attr, None) if detail: raise ValidationError(detail) raise ValidationError(str(e)) except ValueError as e: raise ValidationError({'__all__': str(e)}) return rrsets if bulk else rrsets[0] @transaction.atomic def update(self, instance, validated_data): return self._save(instance, validated_data) @transaction.atomic def create(self, validated_data): return self._save(None, validated_data) def validate_type(self, value): if value in RRset.DEAD_TYPES: raise serializers.ValidationError( "The %s RRset type is currently unsupported." % value) if value in RRset.RESTRICTED_TYPES: raise serializers.ValidationError( "You cannot tinker with the %s RRset." % value) if value.startswith('TYPE'): raise serializers.ValidationError( "Generic type format is not supported.") return value def to_representation(self, instance): data = super().to_representation(instance) data.pop('id') return data class DomainSerializer(serializers.ModelSerializer): name = serializers.RegexField(regex=r'^[A-Za-z0-9_.-]+$', max_length=191, trim_whitespace=False) class Meta: model = Domain fields = ('created', 'published', 'name', 'keys') class DonationSerializer(serializers.ModelSerializer): class Meta: model = Donation fields = ('name', 'iban', 'bic', 'amount', 'message', 'email') def validate_bic(self, value): return re.sub(r'[\s]', '', value) def validate_iban(self, value): return re.sub(r'[\s]', '', value) class UserSerializer(djoserSerializers.UserSerializer): locked = serializers.SerializerMethodField() class Meta(djoserSerializers.UserSerializer.Meta): fields = tuple(User.REQUIRED_FIELDS) + ( User.USERNAME_FIELD, 'dyn', 'limit_domains', 'locked', ) read_only_fields = ('dyn', 'limit_domains', 'locked',) def get_locked(self, obj): return bool(obj.locked) class UserCreateSerializer(djoserSerializers.UserCreateSerializer): class Meta(djoserSerializers.UserCreateSerializer.Meta): fields = tuple(User.REQUIRED_FIELDS) + ( User.USERNAME_FIELD, 'password', 'dyn', )
# Copyright 2017 the authors. # This file is part of Hy, which is free software licensed under the Expat # license. See the LICENSE. from functools import wraps from ast import literal_eval from rply import ParserGenerator from hy._compat import PY3, str_type from hy.models import (HyBytes, HyComplex, HyCons, HyDict, HyExpression, HyFloat, HyInteger, HyKeyword, HyList, HySet, HyString, HySymbol) from .lexer import lexer from .exceptions import LexException, PrematureEndOfInput pg = ParserGenerator( [rule.name for rule in lexer.rules] + ['$end'], cache_id="hy_parser" ) def hy_symbol_mangle(p): if p.startswith("*") and p.endswith("*") and p not in ("*", "**"): p = p[1:-1].upper() if "-" in p and p != "-": p = p.replace("-", "_") if p.endswith("?") and p != "?": p = "is_%s" % (p[:-1]) if p.endswith("!") and p != "!": p = "%s_bang" % (p[:-1]) return p def hy_symbol_unmangle(p): # hy_symbol_mangle is one-way, so this can't be perfect. # But it can be useful till we have a way to get the original # symbol (https://github.com/hylang/hy/issues/360). p = str_type(p) if p.endswith("_bang") and p != "_bang": p = p[:-len("_bang")] + "!" if p.startswith("is_") and p != "is_": p = p[len("is_"):] + "?" if "_" in p and p != "_": p = p.replace("_", "-") if (all([c.isalpha() and c.isupper() or c == '_' for c in p]) and any([c.isalpha() for c in p])): p = '*' + p.lower() + '*' return p def set_boundaries(fun): @wraps(fun) def wrapped(p): start = p[0].source_pos end = p[-1].source_pos ret = fun(p) ret.start_line = start.lineno ret.start_column = start.colno if start is not end: ret.end_line = end.lineno ret.end_column = end.colno else: ret.end_line = start.lineno ret.end_column = start.colno + len(p[0].value) return ret return wrapped def set_quote_boundaries(fun): @wraps(fun) def wrapped(p): start = p[0].source_pos ret = fun(p) ret.start_line = start.lineno ret.start_column = start.colno ret.end_line = p[-1].end_line ret.end_column = p[-1].end_column return ret return wrapped @pg.production("main : list_contents") def main(p): return p[0] @pg.production("main : $end") def main_empty(p): return [] def reject_spurious_dots(*items): "Reject the spurious dots from items" for list in items: for tok in list: if tok == "." and type(tok) == HySymbol: raise LexException("Malformed dotted list", tok.start_line, tok.start_column) @pg.production("paren : LPAREN list_contents RPAREN") @set_boundaries def paren(p): cont = p[1] # Dotted lists are expressions of the form # (a b c . d) # that evaluate to nested cons cells of the form # (a . (b . (c . d))) if len(cont) >= 3 and isinstance(cont[-2], HySymbol) and cont[-2] == ".": reject_spurious_dots(cont[:-2], cont[-1:]) if len(cont) == 3: # Two-item dotted list: return the cons cell directly return HyCons(cont[0], cont[2]) else: # Return a nested cons cell return HyCons(cont[0], paren([p[0], cont[1:], p[2]])) # Warn preemptively on a malformed dotted list. # Only check for dots after the first item to allow for a potential # attribute accessor shorthand reject_spurious_dots(cont[1:]) return HyExpression(p[1]) @pg.production("paren : LPAREN RPAREN") @set_boundaries def empty_paren(p): return HyExpression([]) @pg.production("list_contents : term list_contents") def list_contents(p): return [p[0]] + p[1] @pg.production("list_contents : term") def list_contents_single(p): return [p[0]] @pg.production("list_contents : DISCARD term discarded_list_contents") def list_contents_empty(p): return [] @pg.production("discarded_list_contents : DISCARD term discarded_list_contents") @pg.production("discarded_list_contents :") def discarded_list_contents(p): pass @pg.production("term : identifier") @pg.production("term : paren") @pg.production("term : dict") @pg.production("term : list") @pg.production("term : set") @pg.production("term : string") def term(p): return p[0] @pg.production("term : DISCARD term term") def term_discard(p): return p[2] @pg.production("term : QUOTE term") @set_quote_boundaries def term_quote(p): return HyExpression([HySymbol("quote"), p[1]]) @pg.production("term : QUASIQUOTE term") @set_quote_boundaries def term_quasiquote(p): return HyExpression([HySymbol("quasiquote"), p[1]]) @pg.production("term : UNQUOTE term") @set_quote_boundaries def term_unquote(p): return HyExpression([HySymbol("unquote"), p[1]]) @pg.production("term : UNQUOTESPLICE term") @set_quote_boundaries def term_unquote_splice(p): return HyExpression([HySymbol("unquote_splice"), p[1]]) @pg.production("term : HASHSTARS term") @set_quote_boundaries def term_hashstars(p): n_stars = len(p[0].getstr()[1:]) if n_stars == 1: sym = "unpack_iterable" elif n_stars == 2: sym = "unpack_mapping" else: raise LexException( "Too many stars in `#*` construct (if you want to unpack a symbol " "beginning with a star, separate it with whitespace)", p[0].source_pos.lineno, p[0].source_pos.colno) return HyExpression([HySymbol(sym), p[1]]) @pg.production("term : HASHOTHER term") @set_quote_boundaries def hash_other(p): # p == [(Token('HASHOTHER', '#foo'), bar)] st = p[0].getstr()[1:] str_object = HyString(st) expr = p[1] return HyExpression([HySymbol("dispatch_tag_macro"), str_object, expr]) @pg.production("set : HLCURLY list_contents RCURLY") @set_boundaries def t_set(p): return HySet(p[1]) @pg.production("set : HLCURLY RCURLY") @set_boundaries def empty_set(p): return HySet([]) @pg.production("dict : LCURLY list_contents RCURLY") @set_boundaries def t_dict(p): return HyDict(p[1]) @pg.production("dict : LCURLY RCURLY") @set_boundaries def empty_dict(p): return HyDict([]) @pg.production("list : LBRACKET list_contents RBRACKET") @set_boundaries def t_list(p): return HyList(p[1]) @pg.production("list : LBRACKET RBRACKET") @set_boundaries def t_empty_list(p): return HyList([]) if PY3: def uni_hystring(s): return HyString(literal_eval(s)) def hybytes(s): return HyBytes(literal_eval('b'+s)) else: def uni_hystring(s): return HyString(literal_eval('u'+s)) def hybytes(s): return HyBytes(literal_eval(s)) @pg.production("string : STRING") @set_boundaries def t_string(p): # remove trailing quote s = p[0].value[:-1] # get the header header, s = s.split('"', 1) # remove unicode marker (this is redundant because Hy string # literals already, by default, generate Unicode literals # under Python 2) header = header.replace("u", "") # remove bytes marker, since we'll need to exclude it for Python 2 is_bytestring = "b" in header header = header.replace("b", "") # build python string s = header + '"""' + s + '"""' return (hybytes if is_bytestring else uni_hystring)(s) @pg.production("string : PARTIAL_STRING") def t_partial_string(p): # Any unterminated string requires more input raise PrematureEndOfInput("Premature end of input") @pg.production("identifier : IDENTIFIER") @set_boundaries def t_identifier(p): obj = p[0].value val = symbol_like(obj) if val is not None: return val if "." in obj and symbol_like(obj.split(".", 1)[0]) is not None: # E.g., `5.attr` or `:foo.attr` raise LexException( 'Cannot access attribute on anything other than a name (in ' 'order to get attributes of expressions, use ' '`(. <expression> <attr>)` or `(.<attr> <expression>)`)', p[0].source_pos.lineno, p[0].source_pos.colno) return HySymbol(".".join(hy_symbol_mangle(x) for x in obj.split("."))) def symbol_like(obj): "Try to interpret `obj` as a number or keyword." try: return HyInteger(obj) except ValueError: pass if '/' in obj: try: lhs, rhs = obj.split('/') return HyExpression([HySymbol('fraction'), HyInteger(lhs), HyInteger(rhs)]) except ValueError: pass try: return HyFloat(obj) except ValueError: pass if obj != 'j': try: return HyComplex(obj) except ValueError: pass if obj.startswith(":") and "." not in obj: return HyKeyword(obj) @pg.error def error_handler(token): tokentype = token.gettokentype() if tokentype == '$end': raise PrematureEndOfInput("Premature end of input") else: raise LexException( "Ran into a %s where it wasn't expected." % tokentype, token.source_pos.lineno, token.source_pos.colno) parser = pg.build() Simplify string parsing with `unicode_literals` I switched from `ast.literal_eval` back to `eval` because the former doesn't respect `unicode_literals`. # Copyright 2017 the authors. # This file is part of Hy, which is free software licensed under the Expat # license. See the LICENSE. from __future__ import unicode_literals from functools import wraps from rply import ParserGenerator from hy._compat import str_type from hy.models import (HyBytes, HyComplex, HyCons, HyDict, HyExpression, HyFloat, HyInteger, HyKeyword, HyList, HySet, HyString, HySymbol) from .lexer import lexer from .exceptions import LexException, PrematureEndOfInput pg = ParserGenerator( [rule.name for rule in lexer.rules] + ['$end'], cache_id="hy_parser" ) def hy_symbol_mangle(p): if p.startswith("*") and p.endswith("*") and p not in ("*", "**"): p = p[1:-1].upper() if "-" in p and p != "-": p = p.replace("-", "_") if p.endswith("?") and p != "?": p = "is_%s" % (p[:-1]) if p.endswith("!") and p != "!": p = "%s_bang" % (p[:-1]) return p def hy_symbol_unmangle(p): # hy_symbol_mangle is one-way, so this can't be perfect. # But it can be useful till we have a way to get the original # symbol (https://github.com/hylang/hy/issues/360). p = str_type(p) if p.endswith("_bang") and p != "_bang": p = p[:-len("_bang")] + "!" if p.startswith("is_") and p != "is_": p = p[len("is_"):] + "?" if "_" in p and p != "_": p = p.replace("_", "-") if (all([c.isalpha() and c.isupper() or c == '_' for c in p]) and any([c.isalpha() for c in p])): p = '*' + p.lower() + '*' return p def set_boundaries(fun): @wraps(fun) def wrapped(p): start = p[0].source_pos end = p[-1].source_pos ret = fun(p) ret.start_line = start.lineno ret.start_column = start.colno if start is not end: ret.end_line = end.lineno ret.end_column = end.colno else: ret.end_line = start.lineno ret.end_column = start.colno + len(p[0].value) return ret return wrapped def set_quote_boundaries(fun): @wraps(fun) def wrapped(p): start = p[0].source_pos ret = fun(p) ret.start_line = start.lineno ret.start_column = start.colno ret.end_line = p[-1].end_line ret.end_column = p[-1].end_column return ret return wrapped @pg.production("main : list_contents") def main(p): return p[0] @pg.production("main : $end") def main_empty(p): return [] def reject_spurious_dots(*items): "Reject the spurious dots from items" for list in items: for tok in list: if tok == "." and type(tok) == HySymbol: raise LexException("Malformed dotted list", tok.start_line, tok.start_column) @pg.production("paren : LPAREN list_contents RPAREN") @set_boundaries def paren(p): cont = p[1] # Dotted lists are expressions of the form # (a b c . d) # that evaluate to nested cons cells of the form # (a . (b . (c . d))) if len(cont) >= 3 and isinstance(cont[-2], HySymbol) and cont[-2] == ".": reject_spurious_dots(cont[:-2], cont[-1:]) if len(cont) == 3: # Two-item dotted list: return the cons cell directly return HyCons(cont[0], cont[2]) else: # Return a nested cons cell return HyCons(cont[0], paren([p[0], cont[1:], p[2]])) # Warn preemptively on a malformed dotted list. # Only check for dots after the first item to allow for a potential # attribute accessor shorthand reject_spurious_dots(cont[1:]) return HyExpression(p[1]) @pg.production("paren : LPAREN RPAREN") @set_boundaries def empty_paren(p): return HyExpression([]) @pg.production("list_contents : term list_contents") def list_contents(p): return [p[0]] + p[1] @pg.production("list_contents : term") def list_contents_single(p): return [p[0]] @pg.production("list_contents : DISCARD term discarded_list_contents") def list_contents_empty(p): return [] @pg.production("discarded_list_contents : DISCARD term discarded_list_contents") @pg.production("discarded_list_contents :") def discarded_list_contents(p): pass @pg.production("term : identifier") @pg.production("term : paren") @pg.production("term : dict") @pg.production("term : list") @pg.production("term : set") @pg.production("term : string") def term(p): return p[0] @pg.production("term : DISCARD term term") def term_discard(p): return p[2] @pg.production("term : QUOTE term") @set_quote_boundaries def term_quote(p): return HyExpression([HySymbol("quote"), p[1]]) @pg.production("term : QUASIQUOTE term") @set_quote_boundaries def term_quasiquote(p): return HyExpression([HySymbol("quasiquote"), p[1]]) @pg.production("term : UNQUOTE term") @set_quote_boundaries def term_unquote(p): return HyExpression([HySymbol("unquote"), p[1]]) @pg.production("term : UNQUOTESPLICE term") @set_quote_boundaries def term_unquote_splice(p): return HyExpression([HySymbol("unquote_splice"), p[1]]) @pg.production("term : HASHSTARS term") @set_quote_boundaries def term_hashstars(p): n_stars = len(p[0].getstr()[1:]) if n_stars == 1: sym = "unpack_iterable" elif n_stars == 2: sym = "unpack_mapping" else: raise LexException( "Too many stars in `#*` construct (if you want to unpack a symbol " "beginning with a star, separate it with whitespace)", p[0].source_pos.lineno, p[0].source_pos.colno) return HyExpression([HySymbol(sym), p[1]]) @pg.production("term : HASHOTHER term") @set_quote_boundaries def hash_other(p): # p == [(Token('HASHOTHER', '#foo'), bar)] st = p[0].getstr()[1:] str_object = HyString(st) expr = p[1] return HyExpression([HySymbol("dispatch_tag_macro"), str_object, expr]) @pg.production("set : HLCURLY list_contents RCURLY") @set_boundaries def t_set(p): return HySet(p[1]) @pg.production("set : HLCURLY RCURLY") @set_boundaries def empty_set(p): return HySet([]) @pg.production("dict : LCURLY list_contents RCURLY") @set_boundaries def t_dict(p): return HyDict(p[1]) @pg.production("dict : LCURLY RCURLY") @set_boundaries def empty_dict(p): return HyDict([]) @pg.production("list : LBRACKET list_contents RBRACKET") @set_boundaries def t_list(p): return HyList(p[1]) @pg.production("list : LBRACKET RBRACKET") @set_boundaries def t_empty_list(p): return HyList([]) @pg.production("string : STRING") @set_boundaries def t_string(p): # Replace the single double quotes with triple double quotes to allow # embedded newlines. s = eval(p[0].value.replace('"', '"""', 1)[:-1] + '"""') return (HyString if isinstance(s, str_type) else HyBytes)(s) @pg.production("string : PARTIAL_STRING") def t_partial_string(p): # Any unterminated string requires more input raise PrematureEndOfInput("Premature end of input") @pg.production("identifier : IDENTIFIER") @set_boundaries def t_identifier(p): obj = p[0].value val = symbol_like(obj) if val is not None: return val if "." in obj and symbol_like(obj.split(".", 1)[0]) is not None: # E.g., `5.attr` or `:foo.attr` raise LexException( 'Cannot access attribute on anything other than a name (in ' 'order to get attributes of expressions, use ' '`(. <expression> <attr>)` or `(.<attr> <expression>)`)', p[0].source_pos.lineno, p[0].source_pos.colno) return HySymbol(".".join(hy_symbol_mangle(x) for x in obj.split("."))) def symbol_like(obj): "Try to interpret `obj` as a number or keyword." try: return HyInteger(obj) except ValueError: pass if '/' in obj: try: lhs, rhs = obj.split('/') return HyExpression([HySymbol('fraction'), HyInteger(lhs), HyInteger(rhs)]) except ValueError: pass try: return HyFloat(obj) except ValueError: pass if obj != 'j': try: return HyComplex(obj) except ValueError: pass if obj.startswith(":") and "." not in obj: return HyKeyword(obj) @pg.error def error_handler(token): tokentype = token.gettokentype() if tokentype == '$end': raise PrematureEndOfInput("Premature end of input") else: raise LexException( "Ran into a %s where it wasn't expected." % tokentype, token.source_pos.lineno, token.source_pos.colno) parser = pg.build()
Make all columns string
"""Updates the cache for the `covidcast_meta` endpiont.""" # standard library import argparse import covidcast import sys import time import datetime from enum import Enum # first party from logger import get_structured_logger class DashboardSignal(Enum): # TODO: store this in config file or DB table instead of enum CHANGE = ("change", "chng") QUIDEL = ("quidel", "quidel") def __init__(self, signal_name, source): self.signal_name = signal_name self.source = source def get_argument_parser(): """Define command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument("--log_file", help="filename for log output") return parser def get_latest_issue_date_from_metadata(dashboard_signal, metadata): df_for_source = metadata[metadata.data_source == dashboard_signal.source] return df_for_source["max_issue"].max() def get_latest_data_date_from_metadata(dashboard_signal, metadata): df_for_source = metadata[metadata.data_source == dashboard_signal.source] return df_for_source["max_time"].max() def get_most_recent_issue_row_count(dashboard_signal, metadata): # TODO: Read database directly to calculate return None def get_coverage(dashboard_signal, metadata): latest_data_date = get_latest_data_date_from_metadata(dashboard_signal, metadata) df_for_source = metadata[metadata.data_source == dashboard_signal.source] # we need to do something smarter here -- both make this part of config (and allow multiple signals) and/or # aggregate across all sources for a signal signal = df_for_source["signal"].iloc[0] latest_data = covidcast.signal(dashboard_signal.source, signal, end_day=latest_data_date, start_day=latest_data_date) coverage = latest_data[["time_value", "geo_type", "geo_value"]].copy() coverage.insert(0, 'signal_name', dashboard_signal.signal_name) coverage_list = list(coverage.itertuples(index=False, name=None)) return coverage_list def get_dashboard_signals_to_generate(): # TODO: read this from a config file or DB table return [DashboardSignal.CHANGE, DashboardSignal.QUIDEL] def main(args): """Generate data for the signal dashboard. `args`: parsed command-line arguments """ log_file = None if (args): log_file = args.log_file logger = get_structured_logger( "metadata_cache_updater", filename=log_file,log_exceptions=False) start_time = time.time() signals_to_generate = get_dashboard_signals_to_generate() print(signals_to_generate) metadata = covidcast.metadata() signal_status_list = [] coverage_list = [] for dashboard_signal in signals_to_generate: latest_issue_date = get_latest_issue_date_from_metadata(dashboard_signal, metadata) latest_data_date = get_latest_data_date_from_metadata(dashboard_signal, metadata) latest_row_count = get_most_recent_issue_row_count(dashboard_signal, metadata) latest_coverage = get_coverage(dashboard_signal, metadata) signal_status_list.append((dashboard_signal.signal_name, datetime.date.today(), latest_issue_date, latest_data_date, latest_row_count)) coverage_list.append(latest_coverage) print(signal_status_list) print(coverage_list) # TODO: Insert signal_status_list and coverage_list into DB logger.info( "Generated signal dashboard data", total_runtime_in_seconds=round(time.time() - start_time, 2)) return True if __name__ == '__main__': if not main(get_argument_parser().parse_args()): sys.exit(1) reflow """Updates the cache for the `covidcast_meta` endpiont.""" # standard library import argparse import covidcast import sys import time import datetime from enum import Enum # first party from logger import get_structured_logger class DashboardSignal(Enum): # TODO: store this in config file or DB table instead of enum CHANGE = ("change", "chng") QUIDEL = ("quidel", "quidel") def __init__(self, signal_name, source): self.signal_name = signal_name self.source = source def get_argument_parser(): """Define command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument("--log_file", help="filename for log output") return parser def get_latest_issue_date_from_metadata(dashboard_signal, metadata): df_for_source = metadata[metadata.data_source == dashboard_signal.source] return df_for_source["max_issue"].max() def get_latest_data_date_from_metadata(dashboard_signal, metadata): df_for_source = metadata[metadata.data_source == dashboard_signal.source] return df_for_source["max_time"].max() def get_most_recent_issue_row_count(dashboard_signal, metadata): # TODO: Read database directly to calculate return None def get_coverage(dashboard_signal, metadata): latest_data_date = get_latest_data_date_from_metadata( dashboard_signal, metadata) df_for_source = metadata[metadata.data_source == dashboard_signal.source] # we need to do something smarter here -- both make this part of config (and allow multiple signals) and/or # aggregate across all sources for a signal signal = df_for_source["signal"].iloc[0] latest_data = covidcast.signal( dashboard_signal.source, signal, end_day=latest_data_date, start_day=latest_data_date) coverage = latest_data[["time_value", "geo_type", "geo_value"]].copy() coverage.insert(0, 'signal_name', dashboard_signal.signal_name) coverage_list = list(coverage.itertuples(index=False, name=None)) return coverage_list def get_dashboard_signals_to_generate(): # TODO: read this from a config file or DB table return [DashboardSignal.CHANGE, DashboardSignal.QUIDEL] def main(args): """Generate data for the signal dashboard. `args`: parsed command-line arguments """ log_file = None if (args): log_file = args.log_file logger = get_structured_logger( "metadata_cache_updater", filename=log_file, log_exceptions=False) start_time = time.time() signals_to_generate = get_dashboard_signals_to_generate() print(signals_to_generate) metadata = covidcast.metadata() signal_status_list = [] coverage_list = [] for dashboard_signal in signals_to_generate: latest_issue_date = get_latest_issue_date_from_metadata( dashboard_signal, metadata) latest_data_date = get_latest_data_date_from_metadata( dashboard_signal, metadata) latest_row_count = get_most_recent_issue_row_count( dashboard_signal, metadata) latest_coverage = get_coverage(dashboard_signal, metadata) signal_status_list.append( (dashboard_signal.signal_name, datetime.date.today(), latest_issue_date, latest_data_date, latest_row_count)) coverage_list.append(latest_coverage) print(signal_status_list) print(coverage_list) # TODO: Insert signal_status_list and coverage_list into DB logger.info( "Generated signal dashboard data", total_runtime_in_seconds=round(time.time() - start_time, 2)) return True if __name__ == '__main__': if not main(get_argument_parser().parse_args()): sys.exit(1)
""" Version module. This module defines the package version for use in __init__.py and setup.py. """ __version__ = '0.1.3' trunk version bump """ Version module. This module defines the package version for use in __init__.py and setup.py. """ __version__ = '0.1.4a'
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ A "DAV object" is anything we get from the caldav server or push into the caldav server, notably principal, calendars and calendar events. """ import vobject import io import uuid import re import datetime from lxml import etree from caldav.lib import error, vcal, url from caldav.lib.url import URL from caldav.elements import dav, cdav from caldav.lib.python_utilities import to_unicode class DAVObject(object): """ Base class for all DAV objects. Can be instantiated by a client and an absolute or relative URL, or from the parent object. """ id = None url = None client = None parent = None name = None def __init__(self, client=None, url=None, parent=None, name=None, id=None, **extra): """ Default constructor. Parameters: * client: A DAVClient instance * url: The url for this object. May be a full URL or a relative URL. * parent: The parent object - used when creating objects * name: A displayname * id: The resource id (UID for an Event) """ if client is None and parent is not None: client = parent.client self.client = client self.parent = parent self.name = name self.id = id self.extra_init_options = extra ## url may be a path relative to the caldav root if client and url: self.url = client.url.join(url) else: self.url = URL.objectify(url) @property def canonical_url(self): return str(self.url.unauth()) def children(self, type=None): """ List children, using a propfind (resourcetype) on the parent object, at depth = 1. """ c = [] depth = 1 properties = {} props = [dav.ResourceType(), ] response = self._query_properties(props, depth) properties = self._handle_prop_response(response=response, props=props, type=type, what='tag') for path in list(properties.keys()): resource_type = properties[path][dav.ResourceType.tag] if resource_type == type or type is None: ## TODO: investigate the RFCs thoroughly - why does a "get ## members of this collection"-request also return the collection URL itself? ## And why is the strip_trailing_slash-method needed? The collection URL ## should always end with a slash according to RFC 2518, section 5.2. if self.url.strip_trailing_slash() != self.url.join(path).strip_trailing_slash(): c.append((self.url.join(path), resource_type)) return c def _query_properties(self, props=[], depth=0): """ This is an internal method for doing a propfind query. It's a result of code-refactoring work, attempting to consolidate similar-looking code into a common method. """ root = None # build the propfind request if len(props) > 0: prop = dav.Prop() + props root = dav.Propfind() + prop return self._query(root, depth) def _query(self, root=None, depth=0, query_method='propfind', url=None, expected_return_value=None): """ This is an internal method for doing a query. It's a result of code-refactoring work, attempting to consolidate similar-looking code into a common method. """ if url is None: url = self.url body = "" if root: body = etree.tostring(root.xmlelement(), encoding="utf-8", xml_declaration=True) ret = getattr(self.client, query_method)( url, body, depth) if ret.status == 404: raise error.NotFoundError(ret.raw) if ( (expected_return_value is not None and ret.status != expected_return_value) or ret.status >= 400): raise error.exception_by_method[query_method](ret.raw) return ret def _handle_prop_response(self, response, props=[], type=None, what='text'): """ Internal method to massage an XML response into a dict. (This method is a result of some code refactoring work, attempting to consolidate similar-looking code) """ properties = {} # All items should be in a <D:response> element for r in response.tree.findall('.//' + dav.Response.tag): status = r.find('.//' + dav.Status.tag) if not '200 ' in status.text and not '404 ' in status.text: raise error.ReportError(response.raw) ## TODO: may be wrong error class href = r.find('.//' + dav.Href.tag).text properties[href] = {} for p in props: t = r.find(".//" + p.tag) if len(list(t)) > 0: if type is not None: val = t.find(".//" + type) else: val = t.find(".//*") if val is not None: val = getattr(val, what) else: val = None else: val = t.text properties[href][p.tag] = val return properties def get_properties(self, props=[], depth=0): """ Get properties (PROPFIND) for this object. Works only for properties, that don't have complex types. Parameters: * props = [dav.ResourceType(), dav.DisplayName(), ...] Returns: * {proptag: value, ...} """ rc = None response = self._query_properties(props, depth) properties = self._handle_prop_response(response, props) path = self.url.path exchange_path = self.url.path + '/' if path in list(properties.keys()): rc = properties[path] elif exchange_path in list(properties.keys()): rc = properties[exchange_path] else: raise Exception("The CalDAV server you are using has " "a problem with path handling.") return rc def set_properties(self, props=[]): """ Set properties (PROPPATCH) for this object. Parameters: * props = [dav.DisplayName('name'), ...] Returns: * self """ prop = dav.Prop() + props set = dav.Set() + prop root = dav.PropertyUpdate() + set r = self._query(root, query_method='proppatch') statuses = r.tree.findall(".//" + dav.Status.tag) for s in statuses: if not '200 ' in s.text: raise error.PropsetError(r.raw) return self def save(self): """ Save the object. This is an abstract method, that all classes derived .from DAVObject implement. Returns: * self """ raise NotImplementedError() def delete(self): """ Delete the object. """ if self.url is not None: r = self.client.delete(self.url) #TODO: find out why we get 404 if r.status not in (200, 204, 404): raise error.DeleteError(r.raw) def __str__(self): return str(self.url) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.url) class CalendarSet(DAVObject): def calendars(self): """ List all calendar collections in this set. Returns: * [Calendar(), ...] """ cals = [] data = self.children(cdav.Calendar.tag) for c_url, c_type in data: cals.append(Calendar(self.client, c_url, parent=self)) return cals def make_calendar(self, name=None, cal_id=None, supported_calendar_component_set=None): """ Utility method for creating a new calendar. Parameters: * name: the name of the new calendar * cal_id: the uuid of the new calendar * supported_calendar_component_set: what kind of objects (EVENT, VTODO, VFREEBUSY, VJOURNAL) the calendar should handle. Should be set to ['VTODO'] when creating a task list in Zimbra - in most other cases the default will be OK. Returns: * Calendar(...)-object """ return Calendar(self.client, name=name, parent=self, id=cal_id, supported_calendar_component_set=supported_calendar_component_set).save() def calendar(self, name=None, cal_id=None): """ The calendar method will return a calendar object. It will not initiate any communication with the server. Parameters: * name: return the calendar with this name * cal_id: return the calendar with this calendar id Returns: * Calendar(...)-object """ return Calendar(self.client, name=name, parent = self, url = self.url.join(cal_id), id=cal_id) class Principal(DAVObject): """ This class represents a DAV Principal. It doesn't do much, except keep track of the URLs for the calendar-home-set, etc. """ def __init__(self, client=None, url=None): """ Returns a Principal. Parameters: * client: a DAVClient() oject * url: Deprecated - for backwards compatibility purposes only. If url is not given, deduct principal path as well as calendar home set path from doing propfinds. """ self.client = client self._calendar_home_set = None ## backwards compatibility. if url is not None: self.url = client.url.join(URL.objectify(url)) else: self.url = self.client.url cup = self.get_properties([dav.CurrentUserPrincipal()]) self.url = self.client.url.join(URL.objectify(cup['{DAV:}current-user-principal'])) def make_calendar(self, name=None, cal_id=None, supported_calendar_component_set=None): """ Convenience method, bypasses the self.calendar_home_set object. See CalendarSet.make_calendar for details. """ return self.calendar_home_set.make_calendar(name, cal_id, supported_calendar_component_set=supported_calendar_component_set) def calendar(self, name=None, cal_id=None): """ The calendar method will return a calendar object. It will not initiate any communication with the server. """ return self.calendar_home_set.calendar(name, cal_id) @property def calendar_home_set(self): if not self._calendar_home_set: chs = self.get_properties([cdav.CalendarHomeSet()]) self.calendar_home_set = chs['{urn:ietf:params:xml:ns:caldav}calendar-home-set'] return self._calendar_home_set @calendar_home_set.setter def calendar_home_set(self, url): if isinstance(url, CalendarSet): self._calendar_home_set = url return sanitized_url = URL.objectify(url) if sanitized_url.hostname and sanitized_url.hostname != self.client.url.hostname: ## icloud (and others?) having a load balanced system, where each principal resides on one named host self.client.url = sanitized_url self._calendar_home_set = CalendarSet(self.client, self.client.url.join(sanitized_url)) def calendars(self): """ Return the principials calendars """ return self.calendar_home_set.calendars() class Calendar(DAVObject): """ The `Calendar` object is used to represent a calendar collection. Refer to the RFC for details: http://www.ietf.org/rfc/rfc4791.txt """ def _create(self, name, id=None, supported_calendar_component_set=None): """ Create a new calendar with display name `name` in `parent`. """ if id is None: id = str(uuid.uuid1()) self.id = id path = self.parent.url.join(id) self.url = path ## TODO: mkcalendar seems to ignore the body on most servers? ## at least the name doesn't get set this way. ## zimbra gives 500 (!) if body is omitted ... cal = cdav.CalendarCollection() coll = dav.Collection() + cal type = dav.ResourceType() + coll prop = dav.Prop() + [type,] if name: display_name = dav.DisplayName(name) prop += [display_name,] if supported_calendar_component_set: sccs = cdav.SupportedCalendarComponentSet() for scc in supported_calendar_component_set: sccs += cdav.Comp(scc) prop += sccs set = dav.Set() + prop mkcol = cdav.Mkcalendar() + set r = self._query(root=mkcol, query_method='mkcalendar', url=path, expected_return_value=201) if name: try: self.set_properties([display_name]) except: self.delete() raise ## Special hack for Zimbra! The calendar we've made exists at ## the specified URL, and we can do operations like ls, even ## PUT an event to the calendar. Zimbra will enforce that the ## event uuid matches the event url, and return either 201 or ## 302 - but alas, try to do a GET towards the event and we ## get 404! But turn around and replace the calendar ID with ## the calendar name in the URL and hey ... it works! ## TODO: write test cases for calendars with non-trivial ## names and calendars with names already matching existing ## calendar urls and ensure they pass. zimbra_url = self.parent.url.join(name) try: ret = self.client.request(zimbra_url) if ret.status == 404: raise error.NotFoundError ## insane server self.url = zimbra_url except error.NotFoundError: ## sane server pass def add_event(self, ical): """ Add a new event to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Event(self.client, data = ical, parent = self).save() def add_todo(self, ical): """ Add a new task to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Todo(self.client, data=ical, parent=self).save() def add_journal(self, ical): """ Add a new journal entry to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Journal(self.client, data=ical, parent=self).save() def save(self): """ The save method for a calendar is only used to create it, for now. We know we have to create it when we don't have a url. Returns: * self """ if self.url is None: self._create(name=self.name, id=self.id, **self.extra_init_options) if not self.url.endswith('/'): self.url = URL.objectify(str(self.url) + '/') return self def date_search(self, start, end=None): """ Search events by date in the calendar. Recurring events are expanded if they are occuring during the specified time frame and if an end timestamp is given. Parameters: * start = datetime.today(). * end = same as above. Returns: * [Event(), ...] """ matches = [] # build the request ## Some servers will raise an error if we send the expand flag ## but don't set any end-date - expand doesn't make much sense ## if we have one recurring event describing an indefinite ## series of events. Hence, if the end date is not set, we ## skip asking for expanded events. if end: data = cdav.CalendarData() + cdav.Expand(start, end) else: data = cdav.CalendarData() prop = dav.Prop() + data range = cdav.TimeRange(start, end) vevent = cdav.CompFilter("VEVENT") + range vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') results = self._handle_prop_response(response=response, props=[cdav.CalendarData()]) for r in results: matches.append( Event(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return matches def freebusy_request(self, start, end): """ Search the calendar, but return only the free/busy information. Parameters: * start = datetime.today(). * end = same as above. Returns: * [FreeBusy(), ...] """ root = cdav.FreeBusyQuery() + [ cdav.TimeRange(start, end) ] response = self._query(root, 1, 'report') return FreeBusy(self, response.raw) def journals(self): """ fetches a list of journal entries. """ def todos(self, sort_key='due', include_completed=False): """ fetches a list of todo events. Parameters: * sort_key: use this field in the VTODO for sorting (lower case string, i.e. 'priority'). * include_completed: boolean - by default, only pending tasks are listed """ ## ref https://www.ietf.org/rfc/rfc4791.txt, section 7.8.9 matches = [] # build the request data = cdav.CalendarData() prop = dav.Prop() + data if not include_completed: vnotcompleted = cdav.TextMatch('COMPLETED', negate=True) vnotcancelled = cdav.TextMatch('CANCELLED', negate=True) vstatus = cdav.PropFilter('STATUS') + vnotcancelled + vnotcompleted vnocompletedate = cdav.PropFilter('COMPLETED') + cdav.NotDefined() vtodo = cdav.CompFilter("VTODO") + vnocompletedate + vstatus else: vtodo = cdav.CompFilter("VTODO") vcalendar = cdav.CompFilter("VCALENDAR") + vtodo filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') results = self._handle_prop_response(response=response, props=[cdav.CalendarData()]) for r in results: matches.append( Todo(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) def sort_key_func(x): val = getattr(x.instance.vtodo, sort_key, None) if not val: return None val = val.value if hasattr(val, 'strftime'): return val.strftime('%F%H%M%S') return val if sort_key: matches.sort(key=sort_key_func) return matches def _calendar_comp_class_by_data(self, data): for line in data.split('\n'): if line == 'BEGIN:VEVENT': return Event if line == 'BEGIN:VTODO': return Todo if line == 'BEGIN:VJOURNAL': return Journal if line == 'BEGIN:VFREEBUSY': return FreeBusy def event_by_url(self, href, data=None): """ Returns the event with the given URL """ return Event(url=href, data=data, parent=self).load() def object_by_uid(self, uid, comp_filter=None): """ Get one event from the calendar. Parameters: * uid: the event uid Returns: * Event() or None """ data = cdav.CalendarData() prop = dav.Prop() + data query = cdav.TextMatch(uid) query = cdav.PropFilter("UID") + query if comp_filter: query = comp_filter + query vcalendar = cdav.CompFilter("VCALENDAR") + query filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') if response.status == 404: raise error.NotFoundError(response.raw) elif response.status == 400: raise error.ReportError(response.raw) r = response.tree.find(".//" + dav.Response.tag) if r is not None: href = r.find(".//" + dav.Href.tag).text data = r.find(".//" + cdav.CalendarData.tag).text return self._calendar_comp_class_by_data(data)(self.client, url=URL.objectify(href), data=data, parent=self) else: raise error.NotFoundError(response.raw) def event_by_uid(self, uid): return self.object_by_uid(uid, comp_filter=cdav.CompFilter("VEVENT")) ## alias for backward compatibility event = event_by_uid def events(self): """ List all events from the calendar. Returns: * [Event(), ...] """ all = [] data = cdav.CalendarData() prop = dav.Prop() + data vevent = cdav.CompFilter("VEVENT") vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, query_method='report') results = self._handle_prop_response(response, props=[cdav.CalendarData()]) for r in results: all.append(Event(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return all def journals(self): """ List all journals from the calendar. Returns: * [Journal(), ...] """ ## TODO: this is basically a copy of events() - can we do more ## refactoring and consolidation here? Maybe it's wrong to do ## separate methods for journals, todos and events? all = [] data = cdav.CalendarData() prop = dav.Prop() + data vevent = cdav.CompFilter("VJOURNAL") vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, query_method='report') results = self._handle_prop_response(response, props=[cdav.CalendarData()]) for r in results: all.append(Journal(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return all class CalendarObjectResource(DAVObject): """ Ref RFC 4791, section 4.1, a "Calendar Object Resource" can be an event, a todo-item, a journal entry, a free/busy entry, etc. """ _instance = None _data = None def __init__(self, client=None, url=None, data=None, parent=None, id=None): """ CalendarObjectResource has an additional parameter for its constructor: * data = "...", vCal data for the event """ DAVObject.__init__(self, client=client, url=url, parent=parent, id=id) if data is not None: self.data = data def load(self): """ Load the object from the caldav server. """ r = self.client.request(self.url) if r.status == 404: raise error.NotFoundError(r.raw) self.data = vcal.fix(r.raw) return self def _create(self, data, id=None, path=None): if id is None and path is not None and str(path).endswith('.ics'): id = re.search('(/|^)([^/]*).ics',str(path)).group(2) elif id is None: for obj in ('vevent', 'vtodo', 'vjournal', 'vfreebusy'): if hasattr(self.instance, obj): id = getattr(self.instance, obj).uid.value break if path is None: path = id + ".ics" path = self.parent.url.join(path) r = self.client.put(path, data, {"Content-Type": 'text/calendar; charset="utf-8"'}) if r.status == 302: path = [x[1] for x in r.headers if x[0]=='location'][0] elif not (r.status in (204, 201)): raise error.PutError(r.raw) self.url = URL.objectify(path) self.id = id def save(self): """ Save the object, can be used for creation and update. Returns: * self """ if self._instance is not None: path = self.url.path if self.url else None self._create(self._instance.serialize(), self.id, path) return self def __str__(self): return "%s: %s" % (self.__class__.__name__, self.url) def _set_data(self, data): self._data = vcal.fix(data) self._instance = vobject.readOne(io.StringIO(to_unicode(self._data))) return self def _get_data(self): return self._data data = property(_get_data, _set_data, doc="vCal representation of the object") def _set_instance(self, inst): self._instance = inst self._data = inst.serialize() return self def _get_instance(self): return self._instance instance = property(_get_instance, _set_instance, doc="vobject instance of the object") class Event(CalendarObjectResource): """ The `Event` object is used to represent an event (VEVENT). """ pass class Journal(CalendarObjectResource): """ The `Journal` object is used to represent a journal entry (VJOURNAL). """ pass class FreeBusy(CalendarObjectResource): """ The `FreeBusy` object is used to represent a freebusy response from the server. """ def __init__(self, parent, data): """ A freebusy response object has no URL or ID (TODO: reconsider the class hierarchy? most of the inheritated methods are moot and will fail?). Raw response can be accessed through self.data, instantiated vobject as self.instance. """ CalendarObjectResource.__init__(self, client=parent.client, url=None, data=data, parent=parent, id=None) class Todo(CalendarObjectResource): """ The `Todo` object is used to represent a todo item (VTODO). """ def complete(self, completion_timestamp=None): """ Marks the task as completed. Parameters: * completion_timestamp - datetime object. Defaults to datetime.datetime.now(). """ if not completion_timestamp: completion_timestamp = datetime.datetime.now() if not hasattr(self.instance.vtodo, 'status'): self.instance.vtodo.add('status') self.instance.vtodo.status.value = 'COMPLETED' self.instance.vtodo.add('completed').value = completion_timestamp self.save() Fail fast without comp_filter #!/usr/bin/env python # -*- encoding: utf-8 -*- """ A "DAV object" is anything we get from the caldav server or push into the caldav server, notably principal, calendars and calendar events. """ import vobject import io import uuid import re import datetime from lxml import etree from caldav.lib import error, vcal, url from caldav.lib.url import URL from caldav.elements import dav, cdav from caldav.lib.python_utilities import to_unicode class DAVObject(object): """ Base class for all DAV objects. Can be instantiated by a client and an absolute or relative URL, or from the parent object. """ id = None url = None client = None parent = None name = None def __init__(self, client=None, url=None, parent=None, name=None, id=None, **extra): """ Default constructor. Parameters: * client: A DAVClient instance * url: The url for this object. May be a full URL or a relative URL. * parent: The parent object - used when creating objects * name: A displayname * id: The resource id (UID for an Event) """ if client is None and parent is not None: client = parent.client self.client = client self.parent = parent self.name = name self.id = id self.extra_init_options = extra ## url may be a path relative to the caldav root if client and url: self.url = client.url.join(url) else: self.url = URL.objectify(url) @property def canonical_url(self): return str(self.url.unauth()) def children(self, type=None): """ List children, using a propfind (resourcetype) on the parent object, at depth = 1. """ c = [] depth = 1 properties = {} props = [dav.ResourceType(), ] response = self._query_properties(props, depth) properties = self._handle_prop_response(response=response, props=props, type=type, what='tag') for path in list(properties.keys()): resource_type = properties[path][dav.ResourceType.tag] if resource_type == type or type is None: ## TODO: investigate the RFCs thoroughly - why does a "get ## members of this collection"-request also return the collection URL itself? ## And why is the strip_trailing_slash-method needed? The collection URL ## should always end with a slash according to RFC 2518, section 5.2. if self.url.strip_trailing_slash() != self.url.join(path).strip_trailing_slash(): c.append((self.url.join(path), resource_type)) return c def _query_properties(self, props=[], depth=0): """ This is an internal method for doing a propfind query. It's a result of code-refactoring work, attempting to consolidate similar-looking code into a common method. """ root = None # build the propfind request if len(props) > 0: prop = dav.Prop() + props root = dav.Propfind() + prop return self._query(root, depth) def _query(self, root=None, depth=0, query_method='propfind', url=None, expected_return_value=None): """ This is an internal method for doing a query. It's a result of code-refactoring work, attempting to consolidate similar-looking code into a common method. """ if url is None: url = self.url body = "" if root: body = etree.tostring(root.xmlelement(), encoding="utf-8", xml_declaration=True) ret = getattr(self.client, query_method)( url, body, depth) if ret.status == 404: raise error.NotFoundError(ret.raw) if ( (expected_return_value is not None and ret.status != expected_return_value) or ret.status >= 400): raise error.exception_by_method[query_method](ret.raw) return ret def _handle_prop_response(self, response, props=[], type=None, what='text'): """ Internal method to massage an XML response into a dict. (This method is a result of some code refactoring work, attempting to consolidate similar-looking code) """ properties = {} # All items should be in a <D:response> element for r in response.tree.findall('.//' + dav.Response.tag): status = r.find('.//' + dav.Status.tag) if not '200 ' in status.text and not '404 ' in status.text: raise error.ReportError(response.raw) ## TODO: may be wrong error class href = r.find('.//' + dav.Href.tag).text properties[href] = {} for p in props: t = r.find(".//" + p.tag) if len(list(t)) > 0: if type is not None: val = t.find(".//" + type) else: val = t.find(".//*") if val is not None: val = getattr(val, what) else: val = None else: val = t.text properties[href][p.tag] = val return properties def get_properties(self, props=[], depth=0): """ Get properties (PROPFIND) for this object. Works only for properties, that don't have complex types. Parameters: * props = [dav.ResourceType(), dav.DisplayName(), ...] Returns: * {proptag: value, ...} """ rc = None response = self._query_properties(props, depth) properties = self._handle_prop_response(response, props) path = self.url.path exchange_path = self.url.path + '/' if path in list(properties.keys()): rc = properties[path] elif exchange_path in list(properties.keys()): rc = properties[exchange_path] else: raise Exception("The CalDAV server you are using has " "a problem with path handling.") return rc def set_properties(self, props=[]): """ Set properties (PROPPATCH) for this object. Parameters: * props = [dav.DisplayName('name'), ...] Returns: * self """ prop = dav.Prop() + props set = dav.Set() + prop root = dav.PropertyUpdate() + set r = self._query(root, query_method='proppatch') statuses = r.tree.findall(".//" + dav.Status.tag) for s in statuses: if not '200 ' in s.text: raise error.PropsetError(r.raw) return self def save(self): """ Save the object. This is an abstract method, that all classes derived .from DAVObject implement. Returns: * self """ raise NotImplementedError() def delete(self): """ Delete the object. """ if self.url is not None: r = self.client.delete(self.url) #TODO: find out why we get 404 if r.status not in (200, 204, 404): raise error.DeleteError(r.raw) def __str__(self): return str(self.url) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.url) class CalendarSet(DAVObject): def calendars(self): """ List all calendar collections in this set. Returns: * [Calendar(), ...] """ cals = [] data = self.children(cdav.Calendar.tag) for c_url, c_type in data: cals.append(Calendar(self.client, c_url, parent=self)) return cals def make_calendar(self, name=None, cal_id=None, supported_calendar_component_set=None): """ Utility method for creating a new calendar. Parameters: * name: the name of the new calendar * cal_id: the uuid of the new calendar * supported_calendar_component_set: what kind of objects (EVENT, VTODO, VFREEBUSY, VJOURNAL) the calendar should handle. Should be set to ['VTODO'] when creating a task list in Zimbra - in most other cases the default will be OK. Returns: * Calendar(...)-object """ return Calendar(self.client, name=name, parent=self, id=cal_id, supported_calendar_component_set=supported_calendar_component_set).save() def calendar(self, name=None, cal_id=None): """ The calendar method will return a calendar object. It will not initiate any communication with the server. Parameters: * name: return the calendar with this name * cal_id: return the calendar with this calendar id Returns: * Calendar(...)-object """ return Calendar(self.client, name=name, parent = self, url = self.url.join(cal_id), id=cal_id) class Principal(DAVObject): """ This class represents a DAV Principal. It doesn't do much, except keep track of the URLs for the calendar-home-set, etc. """ def __init__(self, client=None, url=None): """ Returns a Principal. Parameters: * client: a DAVClient() oject * url: Deprecated - for backwards compatibility purposes only. If url is not given, deduct principal path as well as calendar home set path from doing propfinds. """ self.client = client self._calendar_home_set = None ## backwards compatibility. if url is not None: self.url = client.url.join(URL.objectify(url)) else: self.url = self.client.url cup = self.get_properties([dav.CurrentUserPrincipal()]) self.url = self.client.url.join(URL.objectify(cup['{DAV:}current-user-principal'])) def make_calendar(self, name=None, cal_id=None, supported_calendar_component_set=None): """ Convenience method, bypasses the self.calendar_home_set object. See CalendarSet.make_calendar for details. """ return self.calendar_home_set.make_calendar(name, cal_id, supported_calendar_component_set=supported_calendar_component_set) def calendar(self, name=None, cal_id=None): """ The calendar method will return a calendar object. It will not initiate any communication with the server. """ return self.calendar_home_set.calendar(name, cal_id) @property def calendar_home_set(self): if not self._calendar_home_set: chs = self.get_properties([cdav.CalendarHomeSet()]) self.calendar_home_set = chs['{urn:ietf:params:xml:ns:caldav}calendar-home-set'] return self._calendar_home_set @calendar_home_set.setter def calendar_home_set(self, url): if isinstance(url, CalendarSet): self._calendar_home_set = url return sanitized_url = URL.objectify(url) if sanitized_url.hostname and sanitized_url.hostname != self.client.url.hostname: ## icloud (and others?) having a load balanced system, where each principal resides on one named host self.client.url = sanitized_url self._calendar_home_set = CalendarSet(self.client, self.client.url.join(sanitized_url)) def calendars(self): """ Return the principials calendars """ return self.calendar_home_set.calendars() class Calendar(DAVObject): """ The `Calendar` object is used to represent a calendar collection. Refer to the RFC for details: http://www.ietf.org/rfc/rfc4791.txt """ def _create(self, name, id=None, supported_calendar_component_set=None): """ Create a new calendar with display name `name` in `parent`. """ if id is None: id = str(uuid.uuid1()) self.id = id path = self.parent.url.join(id) self.url = path ## TODO: mkcalendar seems to ignore the body on most servers? ## at least the name doesn't get set this way. ## zimbra gives 500 (!) if body is omitted ... cal = cdav.CalendarCollection() coll = dav.Collection() + cal type = dav.ResourceType() + coll prop = dav.Prop() + [type,] if name: display_name = dav.DisplayName(name) prop += [display_name,] if supported_calendar_component_set: sccs = cdav.SupportedCalendarComponentSet() for scc in supported_calendar_component_set: sccs += cdav.Comp(scc) prop += sccs set = dav.Set() + prop mkcol = cdav.Mkcalendar() + set r = self._query(root=mkcol, query_method='mkcalendar', url=path, expected_return_value=201) if name: try: self.set_properties([display_name]) except: self.delete() raise ## Special hack for Zimbra! The calendar we've made exists at ## the specified URL, and we can do operations like ls, even ## PUT an event to the calendar. Zimbra will enforce that the ## event uuid matches the event url, and return either 201 or ## 302 - but alas, try to do a GET towards the event and we ## get 404! But turn around and replace the calendar ID with ## the calendar name in the URL and hey ... it works! ## TODO: write test cases for calendars with non-trivial ## names and calendars with names already matching existing ## calendar urls and ensure they pass. zimbra_url = self.parent.url.join(name) try: ret = self.client.request(zimbra_url) if ret.status == 404: raise error.NotFoundError ## insane server self.url = zimbra_url except error.NotFoundError: ## sane server pass def add_event(self, ical): """ Add a new event to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Event(self.client, data = ical, parent = self).save() def add_todo(self, ical): """ Add a new task to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Todo(self.client, data=ical, parent=self).save() def add_journal(self, ical): """ Add a new journal entry to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Journal(self.client, data=ical, parent=self).save() def save(self): """ The save method for a calendar is only used to create it, for now. We know we have to create it when we don't have a url. Returns: * self """ if self.url is None: self._create(name=self.name, id=self.id, **self.extra_init_options) if not self.url.endswith('/'): self.url = URL.objectify(str(self.url) + '/') return self def date_search(self, start, end=None): """ Search events by date in the calendar. Recurring events are expanded if they are occuring during the specified time frame and if an end timestamp is given. Parameters: * start = datetime.today(). * end = same as above. Returns: * [Event(), ...] """ matches = [] # build the request ## Some servers will raise an error if we send the expand flag ## but don't set any end-date - expand doesn't make much sense ## if we have one recurring event describing an indefinite ## series of events. Hence, if the end date is not set, we ## skip asking for expanded events. if end: data = cdav.CalendarData() + cdav.Expand(start, end) else: data = cdav.CalendarData() prop = dav.Prop() + data range = cdav.TimeRange(start, end) vevent = cdav.CompFilter("VEVENT") + range vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') results = self._handle_prop_response(response=response, props=[cdav.CalendarData()]) for r in results: matches.append( Event(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return matches def freebusy_request(self, start, end): """ Search the calendar, but return only the free/busy information. Parameters: * start = datetime.today(). * end = same as above. Returns: * [FreeBusy(), ...] """ root = cdav.FreeBusyQuery() + [ cdav.TimeRange(start, end) ] response = self._query(root, 1, 'report') return FreeBusy(self, response.raw) def journals(self): """ fetches a list of journal entries. """ def todos(self, sort_key='due', include_completed=False): """ fetches a list of todo events. Parameters: * sort_key: use this field in the VTODO for sorting (lower case string, i.e. 'priority'). * include_completed: boolean - by default, only pending tasks are listed """ ## ref https://www.ietf.org/rfc/rfc4791.txt, section 7.8.9 matches = [] # build the request data = cdav.CalendarData() prop = dav.Prop() + data if not include_completed: vnotcompleted = cdav.TextMatch('COMPLETED', negate=True) vnotcancelled = cdav.TextMatch('CANCELLED', negate=True) vstatus = cdav.PropFilter('STATUS') + vnotcancelled + vnotcompleted vnocompletedate = cdav.PropFilter('COMPLETED') + cdav.NotDefined() vtodo = cdav.CompFilter("VTODO") + vnocompletedate + vstatus else: vtodo = cdav.CompFilter("VTODO") vcalendar = cdav.CompFilter("VCALENDAR") + vtodo filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') results = self._handle_prop_response(response=response, props=[cdav.CalendarData()]) for r in results: matches.append( Todo(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) def sort_key_func(x): val = getattr(x.instance.vtodo, sort_key, None) if not val: return None val = val.value if hasattr(val, 'strftime'): return val.strftime('%F%H%M%S') return val if sort_key: matches.sort(key=sort_key_func) return matches def _calendar_comp_class_by_data(self, data): for line in data.split('\n'): if line == 'BEGIN:VEVENT': return Event if line == 'BEGIN:VTODO': return Todo if line == 'BEGIN:VJOURNAL': return Journal if line == 'BEGIN:VFREEBUSY': return FreeBusy def event_by_url(self, href, data=None): """ Returns the event with the given URL """ return Event(url=href, data=data, parent=self).load() def object_by_uid(self, uid, comp_filter=None): """ Get one event from the calendar. Parameters: * uid: the event uid Returns: * Event() or None """ data = cdav.CalendarData() prop = dav.Prop() + data query = cdav.TextMatch(uid) query = cdav.PropFilter("UID") + query if comp_filter: query = comp_filter + query else: raise Exception("Need a comp_filter") vcalendar = cdav.CompFilter("VCALENDAR") + query filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') if response.status == 404: raise error.NotFoundError(response.raw) elif response.status == 400: raise error.ReportError(response.raw) r = response.tree.find(".//" + dav.Response.tag) if r is not None: href = r.find(".//" + dav.Href.tag).text data = r.find(".//" + cdav.CalendarData.tag).text return self._calendar_comp_class_by_data(data)(self.client, url=URL.objectify(href), data=data, parent=self) else: raise error.NotFoundError(response.raw) def event_by_uid(self, uid): return self.object_by_uid(uid, comp_filter=cdav.CompFilter("VEVENT")) ## alias for backward compatibility event = event_by_uid def events(self): """ List all events from the calendar. Returns: * [Event(), ...] """ all = [] data = cdav.CalendarData() prop = dav.Prop() + data vevent = cdav.CompFilter("VEVENT") vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, query_method='report') results = self._handle_prop_response(response, props=[cdav.CalendarData()]) for r in results: all.append(Event(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return all def journals(self): """ List all journals from the calendar. Returns: * [Journal(), ...] """ ## TODO: this is basically a copy of events() - can we do more ## refactoring and consolidation here? Maybe it's wrong to do ## separate methods for journals, todos and events? all = [] data = cdav.CalendarData() prop = dav.Prop() + data vevent = cdav.CompFilter("VJOURNAL") vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, query_method='report') results = self._handle_prop_response(response, props=[cdav.CalendarData()]) for r in results: all.append(Journal(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return all class CalendarObjectResource(DAVObject): """ Ref RFC 4791, section 4.1, a "Calendar Object Resource" can be an event, a todo-item, a journal entry, a free/busy entry, etc. """ _instance = None _data = None def __init__(self, client=None, url=None, data=None, parent=None, id=None): """ CalendarObjectResource has an additional parameter for its constructor: * data = "...", vCal data for the event """ DAVObject.__init__(self, client=client, url=url, parent=parent, id=id) if data is not None: self.data = data def load(self): """ Load the object from the caldav server. """ r = self.client.request(self.url) if r.status == 404: raise error.NotFoundError(r.raw) self.data = vcal.fix(r.raw) return self def _create(self, data, id=None, path=None): if id is None and path is not None and str(path).endswith('.ics'): id = re.search('(/|^)([^/]*).ics',str(path)).group(2) elif id is None: for obj in ('vevent', 'vtodo', 'vjournal', 'vfreebusy'): if hasattr(self.instance, obj): id = getattr(self.instance, obj).uid.value break if path is None: path = id + ".ics" path = self.parent.url.join(path) r = self.client.put(path, data, {"Content-Type": 'text/calendar; charset="utf-8"'}) if r.status == 302: path = [x[1] for x in r.headers if x[0]=='location'][0] elif not (r.status in (204, 201)): raise error.PutError(r.raw) self.url = URL.objectify(path) self.id = id def save(self): """ Save the object, can be used for creation and update. Returns: * self """ if self._instance is not None: path = self.url.path if self.url else None self._create(self._instance.serialize(), self.id, path) return self def __str__(self): return "%s: %s" % (self.__class__.__name__, self.url) def _set_data(self, data): self._data = vcal.fix(data) self._instance = vobject.readOne(io.StringIO(to_unicode(self._data))) return self def _get_data(self): return self._data data = property(_get_data, _set_data, doc="vCal representation of the object") def _set_instance(self, inst): self._instance = inst self._data = inst.serialize() return self def _get_instance(self): return self._instance instance = property(_get_instance, _set_instance, doc="vobject instance of the object") class Event(CalendarObjectResource): """ The `Event` object is used to represent an event (VEVENT). """ pass class Journal(CalendarObjectResource): """ The `Journal` object is used to represent a journal entry (VJOURNAL). """ pass class FreeBusy(CalendarObjectResource): """ The `FreeBusy` object is used to represent a freebusy response from the server. """ def __init__(self, parent, data): """ A freebusy response object has no URL or ID (TODO: reconsider the class hierarchy? most of the inheritated methods are moot and will fail?). Raw response can be accessed through self.data, instantiated vobject as self.instance. """ CalendarObjectResource.__init__(self, client=parent.client, url=None, data=data, parent=parent, id=None) class Todo(CalendarObjectResource): """ The `Todo` object is used to represent a todo item (VTODO). """ def complete(self, completion_timestamp=None): """ Marks the task as completed. Parameters: * completion_timestamp - datetime object. Defaults to datetime.datetime.now(). """ if not completion_timestamp: completion_timestamp = datetime.datetime.now() if not hasattr(self.instance.vtodo, 'status'): self.instance.vtodo.add('status') self.instance.vtodo.status.value = 'COMPLETED' self.instance.vtodo.add('completed').value = completion_timestamp self.save()
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', type=str, help='path to .csv file', default='orbit.csv') return parser.parse_args() def plane_err(data,coeffs): a,b = coeffs return np.sum((data[:,2] - a*data[:,0]-b*data[:,1])**2) def project_to_plane(coeffs,points): a,b,c = coeffs proj_mat = [[b**2+c**2, -a*b , -a*c ], [ -a*b ,a**2+c**2, -b*c ], [ -a*c , -b*c ,a**2+b**2]] return np.matmul(points,proj_mat)/(a**2+b**2+c**2) def conv_to_2D(points,x,y): mat = [x[0:2],y[0:2]] mat_inv = np.linalg.inv(mat) coords = np.matmul(points[:,0:2],mat_inv) return coords def cart_to_pol(points): pol = np.empty(points.shape) pol[:,0] = np.sqrt(points[:,0]**2+points[:,1]**2) pol[:,1] = np.arctan2(points[:,1],points[:,0])#*57.296 return pol def ellipse_err(polar_coords,params): a,e,t0 = params dem = 1+e*np.cos(polar_coords[:,1]-t0) num = a*(1-e**2) r = np.divide(num,dem) err = np.sum((r - polar_coords[:,0])**2) return err data = np.loadtxt(read_args().file,skiprows=1,usecols=(1,2,3)); plane_err_data = partial(plane_err,data) # z = ax+by p0 = [0,0] p = minimize(plane_err_data,p0,method='nelder-mead').x p = np.append(-p,1) # ax+by+cz = 0 form lan_vec = np.cross([0,0,1],p) inc = math.acos(np.dot(p,[0,0,1])/np.linalg.norm(p)) lan = math.acos(np.dot(lan_vec,[1,0,0])/np.linalg.norm(lan_vec)) proj_data = project_to_plane(p,data) p_x,p_y = lan_vec, project_to_plane(p,np.cross([0,0,1],lan_vec)) p_x,p_y = p_x/np.linalg.norm(p_x), p_y/np.linalg.norm(p_y) coords_2D = conv_to_2D(proj_data,p_x,p_y) polar_coords = cart_to_pol(coords_2D) r_m = np.min(polar_coords[:,0]) r_M = np.max(polar_coords[:,0]) a0 = (r_m+r_M)/2 e0 = (r_M-r_m)/(r_M+r_m) t0 = polar_coords[np.argmin(polar_coords[:,0]),1] params0 = [a0,e0,t0] ellipse_err_data = partial(ellipse_err,polar_coords) params = minimize(ellipse_err_data,params0,method='nelder-mead').x # output print("Semi-major axis: ",params[0]) print("Eccentricity: ",params[1]) print("Argument of periapsis: ",params[2]) print("Inclination: ",inc) print("Longitude of Ascending Node: ",lan) # plotting a,e,t0 = params theta = np.linspace(0,2*math.pi,1000) radii = a*(1-e**2)/(1+e*np.cos(theta-t0)) # convert to cartesian x_s = np.multiply(radii,np.cos(theta)) y_s = np.multiply(radii,np.sin(theta)) # convert to 3D mat = np.column_stack((p_x,p_y)) coords_3D = np.matmul(mat,[x_s,y_s]) fig = plt.figure() ax = fig.add_subplot(111,projection='3d') ax.axis('equal') ax.plot3D(coords_3D[0],coords_3D[1],coords_3D[2],'red') ax.scatter3D(data[::8,0],data[::8,1],data[::8,2],c='blue',depthshade=False) ax.scatter3D(0,0,0,c='green',depthshade=False) plt.show() Minor bug fixes and improvements. import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', type=str, help='path to .csv file', default='orbit.csv') parser.add_argument('-u', '--units', type=str, help='units of distance (m or km)', default='km') return parser.parse_args() def plane_err(data,coeffs): a,b,c = coeffs return np.sum((a*data[:,0]+b*data[:,1]+c*data[:,2])**2)/(a**2+b**2+c**2) def project_to_plane(coeffs,points): a,b,c = coeffs proj_mat = [[b**2+c**2, -a*b , -a*c ], [ -a*b ,a**2+c**2, -b*c ], [ -a*c , -b*c ,a**2+b**2]] return np.matmul(points,proj_mat)/(a**2+b**2+c**2) def conv_to_2D(points,x,y): mat = [x[0:2],y[0:2]] mat_inv = np.linalg.inv(mat) coords = np.matmul(points[:,0:2],mat_inv) return coords def cart_to_pol(points): pol = np.empty(points.shape) pol[:,0] = np.sqrt(points[:,0]**2+points[:,1]**2) pol[:,1] = np.arctan2(points[:,1],points[:,0])#*57.296 return pol def ellipse_err(polar_coords,params): a,e,t0 = params dem = 1+e*np.cos(polar_coords[:,1]-t0) num = a*(1-e**2) r = np.divide(num,dem) err = np.sum((r - polar_coords[:,0])**2) return err args = read_args() data = np.loadtxt(args.file,skiprows=1,usecols=(1,2,3)); plane_err_data = partial(plane_err,data) # ax+by+cz=0 p0 = [0,0,1] p = minimize(plane_err_data,p0,method='nelder-mead').x p = p/np.linalg.norm(p) # normalize p lan_vec = np.cross([0,0,1],p) inc = math.acos(np.dot(p,[0,0,1])/np.linalg.norm(p)) lan = math.acos(np.dot(lan_vec,[1,0,0])/np.linalg.norm(lan_vec)) proj_data = project_to_plane(p,data) p_x,p_y = lan_vec, project_to_plane(p,np.cross([0,0,1],lan_vec)) p_x,p_y = p_x/np.linalg.norm(p_x), p_y/np.linalg.norm(p_y) coords_2D = conv_to_2D(proj_data,p_x,p_y) polar_coords = cart_to_pol(coords_2D) r_m = np.min(polar_coords[:,0]) r_M = np.max(polar_coords[:,0]) a0 = (r_m+r_M)/2 e0 = (r_M-r_m)/(r_M+r_m) t0 = polar_coords[np.argmin(polar_coords[:,0]),1] params0 = [a0,e0,t0] ellipse_err_data = partial(ellipse_err,polar_coords) params = minimize(ellipse_err_data,params0,method='nelder-mead').x # output print("Semi-major axis: ",params[0],args.units) print("Eccentricity: ",params[1]) print("Argument of periapsis: ",params[2],"rad") print("Inclination: ",inc,"rad") print("Longitude of Ascending Node:",lan,"rad") # plotting a,e,t0 = params theta = np.linspace(0,2*math.pi,1000) radii = a*(1-e**2)/(1+e*np.cos(theta-t0)) # convert to cartesian x_s = np.multiply(radii,np.cos(theta)) y_s = np.multiply(radii,np.sin(theta)) # convert to 3D mat = np.column_stack((p_x,p_y)) coords_3D = np.matmul(mat,[x_s,y_s]) fig = plt.figure() ax = Axes3D(fig) ax.axis('equal') ax.plot3D(coords_3D[0],coords_3D[1],coords_3D[2],'red',label='Fitted Ellipse') ax.scatter3D(data[::8,0],data[::8,1],data[::8,2],c='black',depthshade=False,label='Initial Data') # Earth ax.scatter3D(0,0,0,c='blue',s=500,depthshade=False) ax.can_zoom() ax.legend() plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Time and frequency utilities''' import numpy as np import re __all__ = ['frames_to_samples', 'frames_to_time', 'samples_to_frames', 'samples_to_time', 'time_to_samples', 'time_to_frames', 'note_to_hz', 'note_to_midi', 'midi_to_hz', 'midi_to_note', 'hz_to_note', 'hz_to_midi', 'hz_to_mel', 'hz_to_octs', 'mel_to_hz', 'octs_to_hz', 'fft_frequencies', 'cqt_frequencies', 'mel_frequencies', 'A_weighting'] def frames_to_samples(frames, hop_length=512, n_fft=None): """Converts frame indices to audio sample indices Parameters ---------- frames : np.ndarray [shape=(n,)] vector of frame indices hop_length : int > 0 [scalar] number of samples between successive frames n_fft : None or int > 0 [scalar] Optional: length of the FFT window. If given, time conversion will include an offset of `n_fft / 2` to counteract windowing effects when using a non-centered STFT. Returns ------- times : np.ndarray [shape=(n,)] time (in seconds) of each given frame number: `times[i] = frames[i] * hop_length` See Also -------- frames_to_time : convert frame indices to time values samples_to_frames : convert sample indices to frame indices Examples -------- >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> tempo, beats = librosa.beat.beat_track(y, sr=sr) >>> beat_samples = librosa.frames_to_samples(beats) """ offset = 0 if n_fft is not None: offset = int(n_fft // 2) return (np.atleast_1d(frames) * hop_length + offset).astype(int) def samples_to_frames(samples, hop_length=512, n_fft=None): """Converts sample indices into STFT frames. Examples -------- >>> # Get the frame numbers for every 256 samples >>> librosa.samples_to_frames(np.arange(0, 22050, 256)) array([ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43]) Parameters ---------- samples : np.ndarray [shape=(n,)] vector of sample indices hop_length : int > 0 [scalar] number of samples between successive frames n_fft : None or int > 0 [scalar] Optional: length of the FFT window. If given, time conversion will include an offset of `- n_fft / 2` to counteract windowing effects in STFT. .. note:: This may result in negative frame indices. Returns ------- frames : np.ndarray [shape=(n,), dtype=int] Frame numbers corresponding to the given times: `frames[i] = floor( samples[i] / hop_length )` See Also -------- samples_to_time : convert sample indices to time values frames_to_samples : convert frame indices to sample indices """ offset = 0 if n_fft is not None: offset = int(n_fft // 2) return np.floor((np.atleast_1d(samples) - offset) // hop_length).astype(int) def frames_to_time(frames, sr=22050, hop_length=512, n_fft=None): """Converts frame counts to time (seconds) Parameters ---------- frames : np.ndarray [shape=(n,)] vector of frame numbers sr : int > 0 [scalar] audio sampling rate hop_length : int > 0 [scalar] number of samples between successive frames n_fft : None or int > 0 [scalar] Optional: length of the FFT window. If given, time conversion will include an offset of `n_fft / 2` to counteract windowing effects when using a non-centered STFT. Returns ------- times : np.ndarray [shape=(n,)] time (in seconds) of each given frame number: `times[i] = frames[i] * hop_length / sr` See Also -------- time_to_frames : convert time values to frame indices frames_to_samples : convert frame indices to sample indices Examples -------- >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> tempo, beats = librosa.beat.beat_track(y, sr=sr) >>> beat_times = librosa.frames_to_time(beats, sr=sr) """ samples = frames_to_samples(frames, hop_length=hop_length, n_fft=n_fft) return samples_to_time(samples, sr=sr) def time_to_frames(times, sr=22050, hop_length=512, n_fft=None): """Converts time stamps into STFT frames. Examples -------- >>> # Get the frame numbers for every 100ms >>> librosa.time_to_frames(np.arange(0, 1, 0.1), sr=22050, hop_length=512) array([ 0, 4, 8, 12, 17, 21, 25, 30, 34, 38]) Parameters ---------- times : np.ndarray [shape=(n,)] vector of time stamps sr : int > 0 [scalar] audio sampling rate hop_length : int > 0 [scalar] number of samples between successive frames n_fft : None or int > 0 [scalar] Optional: length of the FFT window. If given, time conversion will include an offset of `- n_fft / 2` to counteract windowing effects in STFT. .. note:: This may result in negative frame indices. Returns ------- frames : np.ndarray [shape=(n,), dtype=int] Frame numbers corresponding to the given times: `frames[i] = floor( times[i] * sr / hop_length )` See Also -------- frames_to_time : convert frame indices to time values time_to_samples : convert time values to sample indices """ samples = time_to_samples(times, sr=sr) return samples_to_frames(samples, hop_length=hop_length, n_fft=n_fft) def time_to_samples(times, sr=22050): '''Convert timestamps (in seconds) to sample indices. Examples -------- >>> librosa.time_to_samples(np.arange(0, 1, 0.1), sr=22050) array([ 0, 2205, 4410, 6615, 8820, 11025, 13230, 15435, 17640, 19845]) Parameters ---------- times : np.ndarray Array of time values (in seconds) sr : int > 0 Sampling rate Returns ------- samples : np.ndarray [shape=times.shape, dtype=int] Sample indices corresponding to values in `times` See Also -------- time_to_frames : convert time values to frame indices samples_to_time : convert sample indices to time values ''' return (np.atleast_1d(times) * sr).astype(int) def samples_to_time(samples, sr=22050): '''Convert sample indices to time (in seconds). Examples -------- >>> # Get timestamps corresponding to every 512 samples >>> librosa.samples_to_time(np.arange(0, 22050, 512)) array([ 0. , 0.023, 0.046, 0.07 , 0.093, 0.116, 0.139, 0.163, 0.186, 0.209, 0.232, 0.255, 0.279, 0.302, 0.325, 0.348, 0.372, 0.395, 0.418, 0.441, 0.464, 0.488, 0.511, 0.534, 0.557, 0.58 , 0.604, 0.627, 0.65 , 0.673, 0.697, 0.72 , 0.743, 0.766, 0.789, 0.813, 0.836, 0.859, 0.882, 0.906, 0.929, 0.952, 0.975, 0.998]) Parameters ---------- samples : np.ndarray Array of sample indices sr : int > 0 Sampling rate Returns ------- times : np.ndarray [shape=samples.shape, dtype=int] Time values corresponding to `samples` (in seconds) See Also -------- samples_to_frames : convert sample indices to frame indices time_to_samples : convert time values to sample indices ''' return np.atleast_1d(samples) / float(sr) def note_to_hz(note, **kwargs): '''Convert one or more note names to frequency (Hz) Examples -------- >>> # Get the frequency of a note >>> librosa.note_to_hz('C') array([ 8.176]) >>> # Or multiple notes >>> librosa.note_to_hz(['A3', 'A4', 'A5']) array([ 110., 220., 440.]) >>> # Or notes with tuning deviations >>> librosa.note_to_hz('C2-32', round_midi=False) array([ 32.104]) Parameters ---------- note : str or iterable of str One or more note names to convert kwargs : additional keyword arguments Additional parameters to `note_to_midi` Returns ------- frequencies : np.ndarray [shape=(len(note),)] Array of frequencies (in Hz) corresponding to `note` See Also -------- midi_to_hz note_to_midi hz_to_note ''' return midi_to_hz(note_to_midi(note, **kwargs)) def note_to_midi(note, round_midi=True): '''Convert one or more spelled notes to MIDI number(s). Notes may be spelled out with optional accidentals or octave numbers. The leading note name is case-insensitive. Sharps are indicated with `#`, flats may be indicated with `!` or `b`. Parameters ---------- note : str or iterable of str One or more note names. round_midi : bool - If `True`, allow for fractional midi notes - Otherwise, round cent deviations to the nearest note Returns ------- midi : float or np.array Midi note numbers corresponding to inputs. Raises ------ ValueError If the input is not in valid note format See Also -------- midi_to_note note_to_hz Examples -------- >>> librosa.note_to_midi('C') 0 >>> librosa.note_to_midi('C#3') 37 >>> librosa.note_to_midi('f4') 53 >>> librosa.note_to_midi('Bb-1') -2 >>> librosa.note_to_midi('A!8') 104 >>> # Lists of notes also work >>> librosa.note_to_midi(['C', 'E', 'G']) array([0, 4, 7]) ''' if not isinstance(note, str): return np.array([note_to_midi(n) for n in note]) pitch_map = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} acc_map = {'#': 1, '': 0, 'b': -1, '!': -1} try: match = re.match(r'^(?P<n>[A-Ga-g])' r'(?P<offset>[#b!]*)' r'(?P<oct>[+-]?\d*)' r'(?P<cents>[+-]?\d*)$', note) pitch = match.group('n').upper() offset = np.sum([acc_map[o] for o in match.group('offset')]) octave = match.group('oct') cents = match.group('cents') if not octave: octave = 0 else: octave = int(octave) if round_midi or not cents: cents = 0 else: cents = int(cents) * 1e-2 except: raise ValueError('Improper note format: {:s}'.format(note)) return 12 * octave + pitch_map[pitch] + offset + cents def midi_to_note(midi, octave=True, cents=False): '''Convert one or more MIDI numbers to note strings. MIDI numbers will be rounded to the nearest integer. Notes will be of the format 'C0', 'C#0', 'D0', ... Examples -------- >>> librosa.midi_to_note(0) 'C0' >>> librosa.midi_to_note(37) 'C#3' >>> librosa.midi_to_note(-2) 'A#-1' >>> librosa.midi_to_note(104.7) 'A8' >>> librosa.midi_to_note(104.7, cents=True) 'A8-30' >>> librosa.midi_to_note(range(12)) ['C0', 'C#0', 'D0', 'D#0', 'E0', 'F0', 'F#0', 'G0', 'G#0', 'A0', 'A#0', 'B0'] Parameters ---------- midi : int or iterable of int Midi numbers to convert. octave: bool If True, include the octave number cents: bool If true, cent markers will be appended for fractional notes. Eg, `midi_to_note(69.3, cents=True)` == `A5+03` Returns ------- notes : str or iterable of str Strings describing each midi note. See Also -------- midi_to_hz note_to_midi hz_to_note ''' if not np.isscalar(midi): return [midi_to_note(x, octave=octave, cents=cents) for x in midi] note_map = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] note_num = int(np.round(midi)) note_cents = int(100 * np.around(midi - note_num, 2)) note = note_map[note_num % 12] if octave: note = '{:s}{:0d}'.format(note, int(note_num / 12)) if cents: note = '{:s}{:+02d}'.format(note, note_cents) return note def midi_to_hz(notes): """Get the frequency (Hz) of MIDI note(s) Examples -------- >>> librosa.midi_to_hz(36) array([ 65.406]) >>> librosa.midi_to_hz(np.arange(36, 48)) array([ 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, 92.499, 97.999, 103.826, 110. , 116.541, 123.471]) Parameters ---------- notes : int or np.ndarray [shape=(n,), dtype=int] midi number(s) of the note(s) Returns ------- frequency : np.ndarray [shape=(n,), dtype=float] frequency (frequencies) of `notes` in Hz See Also -------- hz_to_midi note_to_hz """ return 440.0 * (2.0 ** ((np.atleast_1d(notes) - 69.0)/12.0)) def hz_to_midi(frequencies): """Get the closest MIDI note number(s) for given frequencies Examples -------- >>> librosa.hz_to_midi(60) array([ 34.506]) >>> librosa.hz_to_midi([110, 220, 440]) array([ 45., 57., 69.]) Parameters ---------- frequencies : float or np.ndarray [shape=(n,), dtype=float] frequencies to convert Returns ------- note_nums : np.ndarray [shape=(n,), dtype=int] closest MIDI notes to `frequencies` See Also -------- midi_to_hz note_to_midi hz_to_note """ return 12 * (np.log2(np.atleast_1d(frequencies)) - np.log2(440.0)) + 69 def hz_to_note(frequencies, **kwargs): '''Convert one or more frequencies (in Hz) to the nearest note names. Examples -------- >>> # Get a single note name for a frequency >>> librosa.hz_to_note(440.0) ['A5'] >>> # Get multiple notes with cent deviation >>> librosa.hz_to_note([32, 64], cents=True) ['C2-38', 'C3-38'] >>> # Get multiple notes, but suppress octave labels >>> librosa.hz_to_note(440.0 * (2.0 ** np.linspace(0, 1, 12)), octave=False) ['A', 'A#', 'B', 'C', 'C#', 'D', 'E', 'F', 'F#', 'G', 'G#', 'A'] Parameters ---------- frequencies : float or iterable of float Input frequencies, specified in Hz kwargs : additional keyword arguments Arguments passed through to `midi_to_note` Returns ------- notes : list of str `notes[i]` is the closest note name to `frequency[i]` (or `frequency` if the input is scalar) See Also -------- hz_to_midi midi_to_note note_to_hz ''' return midi_to_note(hz_to_midi(frequencies), **kwargs) def hz_to_mel(frequencies, htk=False): """Convert Hz to Mels Examples -------- >>> librosa.hz_to_mel(60) array([0.9]) >>> librosa.hz_to_mel([110, 220, 440]) array([ 1.65, 3.3 , 6.6 ]) Parameters ---------- frequencies : np.ndarray [shape=(n,)] , float scalar or array of frequencies htk : bool use HTK formula instead of Slaney Returns ------- mels : np.ndarray [shape=(n,)] input frequencies in Mels See Also -------- mel_to_hz """ frequencies = np.atleast_1d(frequencies) if htk: return 2595.0 * np.log10(1.0 + frequencies / 700.0) # Fill in the linear part f_min = 0.0 f_sp = 200.0 / 3 mels = (frequencies - f_min) / f_sp # Fill in the log-scale part min_log_hz = 1000.0 # beginning of log region (Hz) min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels) logstep = np.log(6.4) / 27.0 # step size for log region log_t = (frequencies >= min_log_hz) mels[log_t] = min_log_mel + np.log(frequencies[log_t]/min_log_hz) / logstep return mels def mel_to_hz(mels, htk=False): """Convert mel bin numbers to frequencies Examples -------- >>> librosa.mel_to_hz(3) array([ 200.]) >>> librosa.mel_to_hz([1,2,3,4,5]) array([ 66.667, 133.333, 200. , 266.667, 333.333]) Parameters ---------- mels : np.ndarray [shape=(n,)], float mel bins to convert htk : bool use HTK formula instead of Slaney Returns ------- frequencies : np.ndarray [shape=(n,)] input mels in Hz See Also -------- hz_to_mel """ mels = np.atleast_1d(mels) if htk: return 700.0 * (10.0**(mels / 2595.0) - 1.0) # Fill in the linear scale f_min = 0.0 f_sp = 200.0 / 3 freqs = f_min + f_sp * mels # And now the nonlinear scale min_log_hz = 1000.0 # beginning of log region (Hz) min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels) logstep = np.log(6.4) / 27.0 # step size for log region log_t = (mels >= min_log_mel) freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel)) return freqs def hz_to_octs(frequencies, A440=440.0): """Convert frequencies (Hz) to (fractional) octave numbers. Examples -------- >>> librosa.hz_to_octs(440.0) array([ 4.]) >>> librosa.hz_to_octs([32, 64, 128, 256]) array([ 0.219, 1.219, 2.219, 3.219]) Parameters ---------- frequencies : np.ndarray [shape=(n,)] or float scalar or vector of frequencies A440 : float frequency of A440 (in Hz) Returns ------- octaves : np.ndarray [shape=(n,)] octave number for each frequency See Also -------- octs_to_hz """ return np.log2(np.atleast_1d(frequencies) / (float(A440) / 16)) def octs_to_hz(octs, A440=440.0): """Convert octaves numbers to frequencies. Octaves are counted relative to A. Examples -------- >>> librosa.octs_to_hz(1) array([ 55.]) >>> librosa.octs_to_hz([-2, -1, 0, 1, 2]) array([ 6.875, 13.75 , 27.5 , 55. , 110. ]) Parameters ---------- octaves : np.ndarray [shape=(n,)] or float octave number for each frequency A440 : float frequency of A440 Returns ------- frequencies : np.ndarray [shape=(n,)] scalar or vector of frequencies See Also -------- hz_to_octs """ return (float(A440) / 16)*(2.0**np.atleast_1d(octs)) def fft_frequencies(sr=22050, n_fft=2048): '''Alternative implementation of `np.fft.fftfreqs` Examples -------- >>> librosa.fft_frequencies(sr=22050, n_fft=16) array([ 0. , 1378.125, 2756.25 , 4134.375, 5512.5 , 6890.625, 8268.75 , 9646.875, 11025. ]) Parameters ---------- sr : int > 0 [scalar] Audio sampling rate n_fft : int > 0 [scalar] FFT window size Returns ------- freqs : np.ndarray [shape=(1 + n_fft/2,)] Frequencies `(0, sr/n_fft, 2*sr/n_fft, ..., sr/2)` ''' return np.linspace(0, float(sr) / 2, int(1 + n_fft//2), endpoint=True) def cqt_frequencies(n_bins, fmin, bins_per_octave=12, tuning=0.0): """Compute the center frequencies of Constant-Q bins. Examples -------- >>> # Get the CQT frequencies for 24 notes, starting at C2 >>> librosa.cqt_frequencies(24, fmin=librosa.note_to_hz('C2')) array([ 32.703, 34.648, 36.708, 38.891, 41.203, 43.654, 46.249, 48.999, 51.913, 55. , 58.27 , 61.735, 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, 92.499, 97.999, 103.826, 110. , 116.541, 123.471]) Parameters ---------- n_bins : int > 0 [scalar] Number of constant-Q bins fmin : float > 0 [scalar] Minimum frequency bins_per_octave : int > 0 [scalar] Number of bins per octave tuning : float in `[-0.5, +0.5)` Deviation from A440 tuning in fractional bins (cents) Returns ------- frequencies : np.ndarray [shape=(n_bins,)] Center frequency for each CQT bin """ correction = 2.0**(float(tuning) / bins_per_octave) frequencies = 2.0**(np.arange(0, n_bins, dtype=float) / bins_per_octave) return correction * fmin * frequencies def mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0, htk=False, extra=False): """Compute the center frequencies of mel bands Examples -------- >>> librosa.mel_frequencies(n_mels=40) array([ 0. , 81.155, 162.311, 243.466, 324.622, 405.777, 486.933, 568.088, 649.244, 730.399, 811.554, 892.71 , 973.865, 1058.382, 1150.775, 1251.232, 1360.46 , 1479.222, 1608.352, 1748.754, 1901.413, 2067.399, 2247.874, 2444.104, 2657.464, 2889.45 , 3141.687, 3415.943, 3714.14 , 4038.369, 4390.902, 4774.209, 5190.978, 5644.128, 6136.837, 6672.557, 7255.043, 7888.378, 8577.001, 9325.737]) Parameters ---------- n_mels : int > 0 [scalar] number of Mel bins fmin : float >= 0 [scalar] minimum frequency (Hz) fmax : float >= 0 [scalar] maximum frequency (Hz) htk : bool use HTK formula instead of Slaney extra : bool include extra frequencies necessary for building Mel filters Returns ------- bin_frequencies : ndarray [shape=(n_mels,)] vector of Mel frequencies """ # 'Center freqs' of mel bands - uniformly spaced between limits minmel = hz_to_mel(fmin, htk=htk) maxmel = hz_to_mel(fmax, htk=htk) mels = np.arange(minmel, maxmel + 1, (maxmel - minmel) / (n_mels + 1.0)) if not extra: mels = mels[:n_mels] return mel_to_hz(mels, htk=htk) # A-weighting should be capitalized: suppress the naming warning def A_weighting(frequencies, min_db=-80.0): # pylint: disable=invalid-name '''Compute the A-weighting of a set of frequencies. Parameters ---------- frequencies : scalar or np.ndarray [shape=(n,)] One or more frequencies (in Hz) min_db : float [scalar] or None Clip weights below this threshold. If `None`, no clipping is performed. Returns ------- A_weighting : scalar or np.ndarray [shape=(n,)] `A_weighting[i]` is the A-weighting of `frequencies[i]` See Also -------- perceptual_weighting Examples -------- Get the A-weighting for CQT frequencies >>> import matplotlib.pyplot as plt >>> freqs = librosa.cqt_frequencies(108, librosa.note_to_hz('C2')) >>> aw = librosa.A_weighting(freqs) >>> plt.plot(freqs, aw) >>> plt.xlabel('Frequency (Hz)') >>> plt.ylabel('Weighting (log10)') >>> plt.title('A-Weighting of CQT frequencies') ''' # Vectorize to make our lives easier frequencies = np.atleast_1d(frequencies) # Pre-compute squared frequeny f_sq = frequencies**2.0 const = np.array([12200, 20.6, 107.7, 737.9])**2.0 r_a = const[0] * f_sq**2 r_a /= (f_sq + const[0]) * (f_sq + const[1]) r_a /= np.sqrt((f_sq + const[2]) * (f_sq + const[3])) weights = 2.0 + 20 * np.log10(r_a) if min_db is not None: weights = np.maximum(min_db, weights) return weights simpified mel_frequencies code #!/usr/bin/env python # -*- coding: utf-8 -*- '''Time and frequency utilities''' import numpy as np import re __all__ = ['frames_to_samples', 'frames_to_time', 'samples_to_frames', 'samples_to_time', 'time_to_samples', 'time_to_frames', 'note_to_hz', 'note_to_midi', 'midi_to_hz', 'midi_to_note', 'hz_to_note', 'hz_to_midi', 'hz_to_mel', 'hz_to_octs', 'mel_to_hz', 'octs_to_hz', 'fft_frequencies', 'cqt_frequencies', 'mel_frequencies', 'A_weighting'] def frames_to_samples(frames, hop_length=512, n_fft=None): """Converts frame indices to audio sample indices Parameters ---------- frames : np.ndarray [shape=(n,)] vector of frame indices hop_length : int > 0 [scalar] number of samples between successive frames n_fft : None or int > 0 [scalar] Optional: length of the FFT window. If given, time conversion will include an offset of `n_fft / 2` to counteract windowing effects when using a non-centered STFT. Returns ------- times : np.ndarray [shape=(n,)] time (in seconds) of each given frame number: `times[i] = frames[i] * hop_length` See Also -------- frames_to_time : convert frame indices to time values samples_to_frames : convert sample indices to frame indices Examples -------- >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> tempo, beats = librosa.beat.beat_track(y, sr=sr) >>> beat_samples = librosa.frames_to_samples(beats) """ offset = 0 if n_fft is not None: offset = int(n_fft // 2) return (np.atleast_1d(frames) * hop_length + offset).astype(int) def samples_to_frames(samples, hop_length=512, n_fft=None): """Converts sample indices into STFT frames. Examples -------- >>> # Get the frame numbers for every 256 samples >>> librosa.samples_to_frames(np.arange(0, 22050, 256)) array([ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43]) Parameters ---------- samples : np.ndarray [shape=(n,)] vector of sample indices hop_length : int > 0 [scalar] number of samples between successive frames n_fft : None or int > 0 [scalar] Optional: length of the FFT window. If given, time conversion will include an offset of `- n_fft / 2` to counteract windowing effects in STFT. .. note:: This may result in negative frame indices. Returns ------- frames : np.ndarray [shape=(n,), dtype=int] Frame numbers corresponding to the given times: `frames[i] = floor( samples[i] / hop_length )` See Also -------- samples_to_time : convert sample indices to time values frames_to_samples : convert frame indices to sample indices """ offset = 0 if n_fft is not None: offset = int(n_fft // 2) return np.floor((np.atleast_1d(samples) - offset) // hop_length).astype(int) def frames_to_time(frames, sr=22050, hop_length=512, n_fft=None): """Converts frame counts to time (seconds) Parameters ---------- frames : np.ndarray [shape=(n,)] vector of frame numbers sr : int > 0 [scalar] audio sampling rate hop_length : int > 0 [scalar] number of samples between successive frames n_fft : None or int > 0 [scalar] Optional: length of the FFT window. If given, time conversion will include an offset of `n_fft / 2` to counteract windowing effects when using a non-centered STFT. Returns ------- times : np.ndarray [shape=(n,)] time (in seconds) of each given frame number: `times[i] = frames[i] * hop_length / sr` See Also -------- time_to_frames : convert time values to frame indices frames_to_samples : convert frame indices to sample indices Examples -------- >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> tempo, beats = librosa.beat.beat_track(y, sr=sr) >>> beat_times = librosa.frames_to_time(beats, sr=sr) """ samples = frames_to_samples(frames, hop_length=hop_length, n_fft=n_fft) return samples_to_time(samples, sr=sr) def time_to_frames(times, sr=22050, hop_length=512, n_fft=None): """Converts time stamps into STFT frames. Examples -------- >>> # Get the frame numbers for every 100ms >>> librosa.time_to_frames(np.arange(0, 1, 0.1), sr=22050, hop_length=512) array([ 0, 4, 8, 12, 17, 21, 25, 30, 34, 38]) Parameters ---------- times : np.ndarray [shape=(n,)] vector of time stamps sr : int > 0 [scalar] audio sampling rate hop_length : int > 0 [scalar] number of samples between successive frames n_fft : None or int > 0 [scalar] Optional: length of the FFT window. If given, time conversion will include an offset of `- n_fft / 2` to counteract windowing effects in STFT. .. note:: This may result in negative frame indices. Returns ------- frames : np.ndarray [shape=(n,), dtype=int] Frame numbers corresponding to the given times: `frames[i] = floor( times[i] * sr / hop_length )` See Also -------- frames_to_time : convert frame indices to time values time_to_samples : convert time values to sample indices """ samples = time_to_samples(times, sr=sr) return samples_to_frames(samples, hop_length=hop_length, n_fft=n_fft) def time_to_samples(times, sr=22050): '''Convert timestamps (in seconds) to sample indices. Examples -------- >>> librosa.time_to_samples(np.arange(0, 1, 0.1), sr=22050) array([ 0, 2205, 4410, 6615, 8820, 11025, 13230, 15435, 17640, 19845]) Parameters ---------- times : np.ndarray Array of time values (in seconds) sr : int > 0 Sampling rate Returns ------- samples : np.ndarray [shape=times.shape, dtype=int] Sample indices corresponding to values in `times` See Also -------- time_to_frames : convert time values to frame indices samples_to_time : convert sample indices to time values ''' return (np.atleast_1d(times) * sr).astype(int) def samples_to_time(samples, sr=22050): '''Convert sample indices to time (in seconds). Examples -------- >>> # Get timestamps corresponding to every 512 samples >>> librosa.samples_to_time(np.arange(0, 22050, 512)) array([ 0. , 0.023, 0.046, 0.07 , 0.093, 0.116, 0.139, 0.163, 0.186, 0.209, 0.232, 0.255, 0.279, 0.302, 0.325, 0.348, 0.372, 0.395, 0.418, 0.441, 0.464, 0.488, 0.511, 0.534, 0.557, 0.58 , 0.604, 0.627, 0.65 , 0.673, 0.697, 0.72 , 0.743, 0.766, 0.789, 0.813, 0.836, 0.859, 0.882, 0.906, 0.929, 0.952, 0.975, 0.998]) Parameters ---------- samples : np.ndarray Array of sample indices sr : int > 0 Sampling rate Returns ------- times : np.ndarray [shape=samples.shape, dtype=int] Time values corresponding to `samples` (in seconds) See Also -------- samples_to_frames : convert sample indices to frame indices time_to_samples : convert time values to sample indices ''' return np.atleast_1d(samples) / float(sr) def note_to_hz(note, **kwargs): '''Convert one or more note names to frequency (Hz) Examples -------- >>> # Get the frequency of a note >>> librosa.note_to_hz('C') array([ 8.176]) >>> # Or multiple notes >>> librosa.note_to_hz(['A3', 'A4', 'A5']) array([ 110., 220., 440.]) >>> # Or notes with tuning deviations >>> librosa.note_to_hz('C2-32', round_midi=False) array([ 32.104]) Parameters ---------- note : str or iterable of str One or more note names to convert kwargs : additional keyword arguments Additional parameters to `note_to_midi` Returns ------- frequencies : np.ndarray [shape=(len(note),)] Array of frequencies (in Hz) corresponding to `note` See Also -------- midi_to_hz note_to_midi hz_to_note ''' return midi_to_hz(note_to_midi(note, **kwargs)) def note_to_midi(note, round_midi=True): '''Convert one or more spelled notes to MIDI number(s). Notes may be spelled out with optional accidentals or octave numbers. The leading note name is case-insensitive. Sharps are indicated with `#`, flats may be indicated with `!` or `b`. Parameters ---------- note : str or iterable of str One or more note names. round_midi : bool - If `True`, allow for fractional midi notes - Otherwise, round cent deviations to the nearest note Returns ------- midi : float or np.array Midi note numbers corresponding to inputs. Raises ------ ValueError If the input is not in valid note format See Also -------- midi_to_note note_to_hz Examples -------- >>> librosa.note_to_midi('C') 0 >>> librosa.note_to_midi('C#3') 37 >>> librosa.note_to_midi('f4') 53 >>> librosa.note_to_midi('Bb-1') -2 >>> librosa.note_to_midi('A!8') 104 >>> # Lists of notes also work >>> librosa.note_to_midi(['C', 'E', 'G']) array([0, 4, 7]) ''' if not isinstance(note, str): return np.array([note_to_midi(n) for n in note]) pitch_map = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} acc_map = {'#': 1, '': 0, 'b': -1, '!': -1} try: match = re.match(r'^(?P<n>[A-Ga-g])' r'(?P<offset>[#b!]*)' r'(?P<oct>[+-]?\d*)' r'(?P<cents>[+-]?\d*)$', note) pitch = match.group('n').upper() offset = np.sum([acc_map[o] for o in match.group('offset')]) octave = match.group('oct') cents = match.group('cents') if not octave: octave = 0 else: octave = int(octave) if round_midi or not cents: cents = 0 else: cents = int(cents) * 1e-2 except: raise ValueError('Improper note format: {:s}'.format(note)) return 12 * octave + pitch_map[pitch] + offset + cents def midi_to_note(midi, octave=True, cents=False): '''Convert one or more MIDI numbers to note strings. MIDI numbers will be rounded to the nearest integer. Notes will be of the format 'C0', 'C#0', 'D0', ... Examples -------- >>> librosa.midi_to_note(0) 'C0' >>> librosa.midi_to_note(37) 'C#3' >>> librosa.midi_to_note(-2) 'A#-1' >>> librosa.midi_to_note(104.7) 'A8' >>> librosa.midi_to_note(104.7, cents=True) 'A8-30' >>> librosa.midi_to_note(range(12)) ['C0', 'C#0', 'D0', 'D#0', 'E0', 'F0', 'F#0', 'G0', 'G#0', 'A0', 'A#0', 'B0'] Parameters ---------- midi : int or iterable of int Midi numbers to convert. octave: bool If True, include the octave number cents: bool If true, cent markers will be appended for fractional notes. Eg, `midi_to_note(69.3, cents=True)` == `A5+03` Returns ------- notes : str or iterable of str Strings describing each midi note. See Also -------- midi_to_hz note_to_midi hz_to_note ''' if not np.isscalar(midi): return [midi_to_note(x, octave=octave, cents=cents) for x in midi] note_map = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] note_num = int(np.round(midi)) note_cents = int(100 * np.around(midi - note_num, 2)) note = note_map[note_num % 12] if octave: note = '{:s}{:0d}'.format(note, int(note_num / 12)) if cents: note = '{:s}{:+02d}'.format(note, note_cents) return note def midi_to_hz(notes): """Get the frequency (Hz) of MIDI note(s) Examples -------- >>> librosa.midi_to_hz(36) array([ 65.406]) >>> librosa.midi_to_hz(np.arange(36, 48)) array([ 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, 92.499, 97.999, 103.826, 110. , 116.541, 123.471]) Parameters ---------- notes : int or np.ndarray [shape=(n,), dtype=int] midi number(s) of the note(s) Returns ------- frequency : np.ndarray [shape=(n,), dtype=float] frequency (frequencies) of `notes` in Hz See Also -------- hz_to_midi note_to_hz """ return 440.0 * (2.0 ** ((np.atleast_1d(notes) - 69.0)/12.0)) def hz_to_midi(frequencies): """Get the closest MIDI note number(s) for given frequencies Examples -------- >>> librosa.hz_to_midi(60) array([ 34.506]) >>> librosa.hz_to_midi([110, 220, 440]) array([ 45., 57., 69.]) Parameters ---------- frequencies : float or np.ndarray [shape=(n,), dtype=float] frequencies to convert Returns ------- note_nums : np.ndarray [shape=(n,), dtype=int] closest MIDI notes to `frequencies` See Also -------- midi_to_hz note_to_midi hz_to_note """ return 12 * (np.log2(np.atleast_1d(frequencies)) - np.log2(440.0)) + 69 def hz_to_note(frequencies, **kwargs): '''Convert one or more frequencies (in Hz) to the nearest note names. Examples -------- >>> # Get a single note name for a frequency >>> librosa.hz_to_note(440.0) ['A5'] >>> # Get multiple notes with cent deviation >>> librosa.hz_to_note([32, 64], cents=True) ['C2-38', 'C3-38'] >>> # Get multiple notes, but suppress octave labels >>> librosa.hz_to_note(440.0 * (2.0 ** np.linspace(0, 1, 12)), octave=False) ['A', 'A#', 'B', 'C', 'C#', 'D', 'E', 'F', 'F#', 'G', 'G#', 'A'] Parameters ---------- frequencies : float or iterable of float Input frequencies, specified in Hz kwargs : additional keyword arguments Arguments passed through to `midi_to_note` Returns ------- notes : list of str `notes[i]` is the closest note name to `frequency[i]` (or `frequency` if the input is scalar) See Also -------- hz_to_midi midi_to_note note_to_hz ''' return midi_to_note(hz_to_midi(frequencies), **kwargs) def hz_to_mel(frequencies, htk=False): """Convert Hz to Mels Examples -------- >>> librosa.hz_to_mel(60) array([0.9]) >>> librosa.hz_to_mel([110, 220, 440]) array([ 1.65, 3.3 , 6.6 ]) Parameters ---------- frequencies : np.ndarray [shape=(n,)] , float scalar or array of frequencies htk : bool use HTK formula instead of Slaney Returns ------- mels : np.ndarray [shape=(n,)] input frequencies in Mels See Also -------- mel_to_hz """ frequencies = np.atleast_1d(frequencies) if htk: return 2595.0 * np.log10(1.0 + frequencies / 700.0) # Fill in the linear part f_min = 0.0 f_sp = 200.0 / 3 mels = (frequencies - f_min) / f_sp # Fill in the log-scale part min_log_hz = 1000.0 # beginning of log region (Hz) min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels) logstep = np.log(6.4) / 27.0 # step size for log region log_t = (frequencies >= min_log_hz) mels[log_t] = min_log_mel + np.log(frequencies[log_t]/min_log_hz) / logstep return mels def mel_to_hz(mels, htk=False): """Convert mel bin numbers to frequencies Examples -------- >>> librosa.mel_to_hz(3) array([ 200.]) >>> librosa.mel_to_hz([1,2,3,4,5]) array([ 66.667, 133.333, 200. , 266.667, 333.333]) Parameters ---------- mels : np.ndarray [shape=(n,)], float mel bins to convert htk : bool use HTK formula instead of Slaney Returns ------- frequencies : np.ndarray [shape=(n,)] input mels in Hz See Also -------- hz_to_mel """ mels = np.atleast_1d(mels) if htk: return 700.0 * (10.0**(mels / 2595.0) - 1.0) # Fill in the linear scale f_min = 0.0 f_sp = 200.0 / 3 freqs = f_min + f_sp * mels # And now the nonlinear scale min_log_hz = 1000.0 # beginning of log region (Hz) min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels) logstep = np.log(6.4) / 27.0 # step size for log region log_t = (mels >= min_log_mel) freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel)) return freqs def hz_to_octs(frequencies, A440=440.0): """Convert frequencies (Hz) to (fractional) octave numbers. Examples -------- >>> librosa.hz_to_octs(440.0) array([ 4.]) >>> librosa.hz_to_octs([32, 64, 128, 256]) array([ 0.219, 1.219, 2.219, 3.219]) Parameters ---------- frequencies : np.ndarray [shape=(n,)] or float scalar or vector of frequencies A440 : float frequency of A440 (in Hz) Returns ------- octaves : np.ndarray [shape=(n,)] octave number for each frequency See Also -------- octs_to_hz """ return np.log2(np.atleast_1d(frequencies) / (float(A440) / 16)) def octs_to_hz(octs, A440=440.0): """Convert octaves numbers to frequencies. Octaves are counted relative to A. Examples -------- >>> librosa.octs_to_hz(1) array([ 55.]) >>> librosa.octs_to_hz([-2, -1, 0, 1, 2]) array([ 6.875, 13.75 , 27.5 , 55. , 110. ]) Parameters ---------- octaves : np.ndarray [shape=(n,)] or float octave number for each frequency A440 : float frequency of A440 Returns ------- frequencies : np.ndarray [shape=(n,)] scalar or vector of frequencies See Also -------- hz_to_octs """ return (float(A440) / 16)*(2.0**np.atleast_1d(octs)) def fft_frequencies(sr=22050, n_fft=2048): '''Alternative implementation of `np.fft.fftfreqs` Examples -------- >>> librosa.fft_frequencies(sr=22050, n_fft=16) array([ 0. , 1378.125, 2756.25 , 4134.375, 5512.5 , 6890.625, 8268.75 , 9646.875, 11025. ]) Parameters ---------- sr : int > 0 [scalar] Audio sampling rate n_fft : int > 0 [scalar] FFT window size Returns ------- freqs : np.ndarray [shape=(1 + n_fft/2,)] Frequencies `(0, sr/n_fft, 2*sr/n_fft, ..., sr/2)` ''' return np.linspace(0, float(sr) / 2, int(1 + n_fft//2), endpoint=True) def cqt_frequencies(n_bins, fmin, bins_per_octave=12, tuning=0.0): """Compute the center frequencies of Constant-Q bins. Examples -------- >>> # Get the CQT frequencies for 24 notes, starting at C2 >>> librosa.cqt_frequencies(24, fmin=librosa.note_to_hz('C2')) array([ 32.703, 34.648, 36.708, 38.891, 41.203, 43.654, 46.249, 48.999, 51.913, 55. , 58.27 , 61.735, 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, 92.499, 97.999, 103.826, 110. , 116.541, 123.471]) Parameters ---------- n_bins : int > 0 [scalar] Number of constant-Q bins fmin : float > 0 [scalar] Minimum frequency bins_per_octave : int > 0 [scalar] Number of bins per octave tuning : float in `[-0.5, +0.5)` Deviation from A440 tuning in fractional bins (cents) Returns ------- frequencies : np.ndarray [shape=(n_bins,)] Center frequency for each CQT bin """ correction = 2.0**(float(tuning) / bins_per_octave) frequencies = 2.0**(np.arange(0, n_bins, dtype=float) / bins_per_octave) return correction * fmin * frequencies def mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0, htk=False, extra=False): """Compute the center frequencies of mel bands Examples -------- >>> librosa.mel_frequencies(n_mels=40) array([ 0. , 81.155, 162.311, 243.466, 324.622, 405.777, 486.933, 568.088, 649.244, 730.399, 811.554, 892.71 , 973.865, 1058.382, 1150.775, 1251.232, 1360.46 , 1479.222, 1608.352, 1748.754, 1901.413, 2067.399, 2247.874, 2444.104, 2657.464, 2889.45 , 3141.687, 3415.943, 3714.14 , 4038.369, 4390.902, 4774.209, 5190.978, 5644.128, 6136.837, 6672.557, 7255.043, 7888.378, 8577.001, 9325.737]) Parameters ---------- n_mels : int > 0 [scalar] number of Mel bins fmin : float >= 0 [scalar] minimum frequency (Hz) fmax : float >= 0 [scalar] maximum frequency (Hz) htk : bool use HTK formula instead of Slaney extra : bool include extra frequencies necessary for building Mel filters Returns ------- bin_frequencies : ndarray [shape=(n_mels,)] vector of Mel frequencies """ # 'Center freqs' of mel bands - uniformly spaced between limits min_mel = hz_to_mel(fmin, htk=htk) max_mel = hz_to_mel(fmax, htk=htk) mels = np.linspace(min_mel, max_mel, n_mels + 2) if not extra: mels = mels[:n_mels] return mel_to_hz(mels, htk=htk) # A-weighting should be capitalized: suppress the naming warning def A_weighting(frequencies, min_db=-80.0): # pylint: disable=invalid-name '''Compute the A-weighting of a set of frequencies. Parameters ---------- frequencies : scalar or np.ndarray [shape=(n,)] One or more frequencies (in Hz) min_db : float [scalar] or None Clip weights below this threshold. If `None`, no clipping is performed. Returns ------- A_weighting : scalar or np.ndarray [shape=(n,)] `A_weighting[i]` is the A-weighting of `frequencies[i]` See Also -------- perceptual_weighting Examples -------- Get the A-weighting for CQT frequencies >>> import matplotlib.pyplot as plt >>> freqs = librosa.cqt_frequencies(108, librosa.note_to_hz('C2')) >>> aw = librosa.A_weighting(freqs) >>> plt.plot(freqs, aw) >>> plt.xlabel('Frequency (Hz)') >>> plt.ylabel('Weighting (log10)') >>> plt.title('A-Weighting of CQT frequencies') ''' # Vectorize to make our lives easier frequencies = np.atleast_1d(frequencies) # Pre-compute squared frequeny f_sq = frequencies**2.0 const = np.array([12200, 20.6, 107.7, 737.9])**2.0 r_a = const[0] * f_sq**2 r_a /= (f_sq + const[0]) * (f_sq + const[1]) r_a /= np.sqrt((f_sq + const[2]) * (f_sq + const[3])) weights = 2.0 + 20 * np.log10(r_a) if min_db is not None: weights = np.maximum(min_db, weights) return weights
""" URLconf for registration and activation, using django-registration's default backend. If the default behavior of these views is acceptable to you, simply use a line like this in your root URLconf to set up the default URLs for registration:: (r'^accounts/', include('registration.backends.default.urls')), This will also automatically set up the views in ``django.contrib.auth`` at sensible default locations. If you'd like to customize the behavior (e.g., by passing extra arguments to the various views) or split up the URLs, feel free to set up your own URL patterns for these views instead. """ from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from registration.views import activate from registration.views import register urlpatterns = patterns('', url(r'^register/$', register, {'backend': 'registration.backends.simple.SimpleBackend'}, name='registration_register'), url(r'^register/closed/$', direct_to_template, {'template': 'registration/registration_closed.html'}, name='registration_disallowed'), (r'', include('registration.auth_urls')), ) This will teach me to copy/paste as a starting point. """ URLconf for registration and activation, using django-registration's one-step backend. If the default behavior of these views is acceptable to you, simply use a line like this in your root URLconf to set up the default URLs for registration:: (r'^accounts/', include('registration.backends.simple.urls')), This will also automatically set up the views in ``django.contrib.auth`` at sensible default locations. If you'd like to customize the behavior (e.g., by passing extra arguments to the various views) or split up the URLs, feel free to set up your own URL patterns for these views instead. """ from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from registration.views import activate from registration.views import register urlpatterns = patterns('', url(r'^register/$', register, {'backend': 'registration.backends.simple.SimpleBackend'}, name='registration_register'), url(r'^register/closed/$', direct_to_template, {'template': 'registration/registration_closed.html'}, name='registration_disallowed'), (r'', include('registration.auth_urls')), )
import base64 import json import os def load_manifest(path): here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, "manifests", path), "rb") as fp: return base64.b64encode(fp.read()).decode("utf-8") def get_layers(): return { "os": { "type": "coreos", "channel": "stable", "version": "899.15.0", "manifests": { "etcd": load_manifest("os/etcd.sh"), "master": load_manifest("os/master.sh"), "node": load_manifest("os/node.sh"), }, }, "kubernetes": { "version": "v1.2.2_kel.0", "images": { "kube-dns": { "etcd": "gcr.io/google_containers/etcd:2.0.9", "kube2sky": "gcr.io/google_containers/kube2sky:1.11", "skydns": "gcr.io/google_containers/skydns:2015-10-13-8c72f8c", } }, "manifests": { "kube-dns": load_manifest("kubernetes/dns.yml"), }, }, "kel": { "bundles": { "api": "git-ce6fa670", "blobstore": "git-dec5e2b1", "router": "git-717bba4c", }, "images": { "bundle-builder": "quay.io/kelproject/bundle-builder", "bundle-runner": "quay.io/kelproject/bundle-runner", "api-cache": "quay.io/kelproject/services:redis-3.0", "api-database": "quay.io/kelproject/services:postgresql-9.4", "api-web": "quay.io/kelproject/bundle-runner", "api-worker": "quay.io/kelproject/bundle-runner", "blobstore-data": "quay.io/kelproject/services:data-1.0", "blobstore": "quay.io/kelproject/bundle-runner", "log-agent": "quay.io/kelproject/log-agent", "logstash": "quay.io/kelproject/logstash", "log-store": "quay.io/pires/docker-elasticsearch-kubernetes:2.2.0", "router": "quay.io/kelproject/bundle-runner", }, "manifests": { "kel-system": load_manifest("kel/kel-system.yml"), "kel-builds": load_manifest("kel/kel-builds.yml"), "router": load_manifest("kel/router.yml"), "blobstore-data": load_manifest("kel/blobstore-data.yml"), "blobstore": load_manifest("kel/blobstore.yml"), "api-cache": load_manifest("kel/api-cache.yml"), "api-database": load_manifest("kel/api-database.yml"), "api-web": load_manifest("kel/api-web.yml"), "api-worker": load_manifest("kel/api-worker.yml"), "log-agent": load_manifest("kel/log-agent.yml"), "logstash": load_manifest("kel/logstash.yml"), "log-store": load_manifest("kel/log-store.yml"), }, }, } def main(): print(json.dumps({"layers": get_layers()})) if __name__ == "__main__": main() kubernetes: point to correct release import base64 import json import os def load_manifest(path): here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, "manifests", path), "rb") as fp: return base64.b64encode(fp.read()).decode("utf-8") def get_layers(): return { "os": { "type": "coreos", "channel": "stable", "version": "899.15.0", "manifests": { "etcd": load_manifest("os/etcd.sh"), "master": load_manifest("os/master.sh"), "node": load_manifest("os/node.sh"), }, }, "kubernetes": { "version": "v1.2.2_kel.2", "images": { "kube-dns": { "etcd": "gcr.io/google_containers/etcd:2.0.9", "kube2sky": "gcr.io/google_containers/kube2sky:1.11", "skydns": "gcr.io/google_containers/skydns:2015-10-13-8c72f8c", } }, "manifests": { "kube-dns": load_manifest("kubernetes/dns.yml"), }, }, "kel": { "bundles": { "api": "git-ce6fa670", "blobstore": "git-dec5e2b1", "router": "git-717bba4c", }, "images": { "bundle-builder": "quay.io/kelproject/bundle-builder", "bundle-runner": "quay.io/kelproject/bundle-runner", "api-cache": "quay.io/kelproject/services:redis-3.0", "api-database": "quay.io/kelproject/services:postgresql-9.4", "api-web": "quay.io/kelproject/bundle-runner", "api-worker": "quay.io/kelproject/bundle-runner", "blobstore-data": "quay.io/kelproject/services:data-1.0", "blobstore": "quay.io/kelproject/bundle-runner", "log-agent": "quay.io/kelproject/log-agent", "logstash": "quay.io/kelproject/logstash", "log-store": "quay.io/pires/docker-elasticsearch-kubernetes:2.2.0", "router": "quay.io/kelproject/bundle-runner", }, "manifests": { "kel-system": load_manifest("kel/kel-system.yml"), "kel-builds": load_manifest("kel/kel-builds.yml"), "router": load_manifest("kel/router.yml"), "blobstore-data": load_manifest("kel/blobstore-data.yml"), "blobstore": load_manifest("kel/blobstore.yml"), "api-cache": load_manifest("kel/api-cache.yml"), "api-database": load_manifest("kel/api-database.yml"), "api-web": load_manifest("kel/api-web.yml"), "api-worker": load_manifest("kel/api-worker.yml"), "log-agent": load_manifest("kel/log-agent.yml"), "logstash": load_manifest("kel/logstash.yml"), "log-store": load_manifest("kel/log-store.yml"), }, }, } def main(): print(json.dumps({"layers": get_layers()})) if __name__ == "__main__": main()
from __future__ import division from urllib2 import urlopen import re import operator import copy import json from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render_to_response, redirect from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import DetailView, TemplateView, ListView from django.views.decorators.vary import vary_on_cookie from django.db.models import Q from django.core.cache import cache import xlwt from django.utils.safestring import mark_safe from education.curriculum_progress_helper import get_target_value, get_location_for_curriculum_view, get_curriculum_data, target from rapidsms_httprouter.models import Message from .forms import * from .models import * from uganda_common.utils import * from rapidsms.contrib.locations.models import Location from generic.views import generic from generic.sorters import SimpleSorter from poll.models import Poll, ResponseCategory from script.models import ScriptStep, Script from .reports import * from .utils import * from .utils import _schedule_monthly_script, _schedule_termly_script, _schedule_weekly_scripts, _schedule_teacher_weekly_scripts import reversion from reversion.models import Revision from unregister.models import Blacklist from .utils import themes from education.absenteeism_view_helper import * import datetime from datetime import date from education.view_helper import * from education.view_helper_utils import * Num_REG = re.compile('\d+') super_user_required = \ user_passes_test(lambda u: u.groups.filter( name__in=['Admins', 'DFO', 'UNICEF Officials']).exists() or u.is_superuser) @login_required def index(request, **kwargs): """ kwargs is where we list the variables that can be passed as our context use as follows: index(request, context_vars={'some_model_queryset'=Model.objects.all}) """ if not kwargs: return render_to_response("education/index.html", {}, RequestContext(request)) else: #When choosing to use kwargs, don't forget to include template and context_var variables # if you don't need a template or just need the original template, use template_name=None context_vars = kwargs.get('context_vars') template_name = kwargs['template_name'] if not template_name: #if no template name is given t = "education/index.html" else: t = "education/%s" % template_name return render_to_response(t, context_vars, RequestContext(request)) #MAPS @login_required def dash_map(request): return render_to_response('education/dashboard/map.html', {}, RequestContext(request)) def dash_ministry_map(request): return render_to_response('education/dashboard/map.html', {}, RequestContext(request)) def dash_attdance(request): boysp3_attendance = get_responses_to_polls(poll_name='edtrac_boysp3_attendance') boysp3_enrolled = get_responses_to_polls(poll_name="edtrac_boysp3_enrollment") boysp3_absent = boysp3_enrolled - boysp3_attendance girlsp3_attendance = get_responses_to_polls(poll_name="edtrac_girlsp3_attendance") girlsp3_enrolled = get_responses_to_polls(poll_name="edtrac_girlsp3_enrollment") girlsp3_absent = girlsp3_enrolled - girlsp3_attendance boysp6_attendance = get_responses_to_polls(poll_name="edtrac_boysp6_attendance") boysp6_enrolled = get_responses_to_polls(poll_name="edtrac_boysp6_enrollment") boysp6_absent = boysp6_enrolled - boysp6_attendance girlsp6_attendance = get_responses_to_polls(poll_name="edtrac_girlsp6_attendance") girlsp6_enrolled = get_responses_to_polls(poll_name="edtrac_girlsp6_enrollment") girlsp6_absent = girlsp6_enrolled - girlsp6_attendance total_male_teachers = get_responses_to_polls(poll_name="edtrac_m_teachers_deployment") total_female_teachers = get_responses_to_polls(poll_name="edtrac_f_teachers_deployment") male_teachers_present = get_responses_to_polls(poll_name="edtrac_m_teachers_attendance") male_teachers_absent = total_male_teachers - male_teachers_present female_teachers_present = get_responses_to_polls(poll_name="edtrac_f_teachers_attendance") female_teachers_absent = total_female_teachers - female_teachers_present return render_to_response('education/dashboard/attdance.html', { 'girlsp3_present' : girlsp3_attendance, 'girlsp3_absent' : girlsp3_absent, 'boysp3_present' : boysp3_attendance, 'boysp3_absent' : boysp3_absent, 'girlsp6_present' : girlsp6_attendance, 'girlsp6_absent' : girlsp6_absent, 'boysp6_present' : boysp6_attendance, 'boysp6_absent' : boysp6_absent, 'female_teachers_present' : female_teachers_present, 'female_teachers_absent' : female_teachers_absent, 'male_teachers_present' : male_teachers_present, 'male_teachers_absent' : male_teachers_absent } , RequestContext(request)) def get_mode_progress(mode): try: mode_progress = (100 * sorted(target.values()).index(mode) + 1) / float(len(target.keys())) # offset zero-based index by 1 except ValueError: mode_progress = 0 # when no values are recorded return mode_progress def get_progress_color(current_mode, target_value): on_schedule = 'green' behind_schedule = 'red' if current_mode < target_value: return behind_schedule return on_schedule def get_weeks_in_term(): term_start= getattr(settings,'SCHOOL_TERM_START') first_term_start= getattr(settings,'FIRST_TERM_BEGINS') second_term_start= getattr(settings,'SECOND_TERM_BEGINS') third_term_start= getattr(settings,'THIRD_TERM_BEGINS') weeks = [] for term_starts in [first_term_start, second_term_start, third_term_start]: if term_start == term_starts: weeks.extend(get_weeks(get_week_date()[1],depth=get_week_count(get_week_date()[0],term_starts))) break weeks.extend(get_weeks(dateutils.increment(term_starts, weeks=12),depth=12)) return weeks def format_week(week,sep): day1 = week[0].strftime("%d"+sep+"%b"+sep+"%Y") day2 = week[1].strftime("%d"+sep+"%b"+sep+"%Y") formated_week = "%s to %s" % (day1 , day2) return formated_week def _get_formated_date_choice(week): if week[0] < datetime.datetime.today() < week[1]: return format_week(week, ","), "current week( %s )" % format_week(week, "-") return format_week(week, ","), format_week(week, "-") class CurriculumForm(forms.Form): error_css_class = 'error' SELECT_CHOICES = [_get_formated_date_choice(week) for week in get_weeks_in_term()] choose_week_to_view = forms.ChoiceField(choices=SELECT_CHOICES, required=False) class ReporterDetailView(DetailView): model = EmisReporter def format_to_datetime_object(week_as_string): day1 = week_as_string.split()[0] day2 = week_as_string.split()[2] day_one = datetime.datetime.strptime(day1,"%d,%b,%Y") day_two = datetime.datetime.strptime(day2,"%d,%b,%Y") return [day_one,day_two] def get_modes_and_target(current_mode, target_value): target_progress = get_mode_progress(target_value) if len(current_mode) > 0 and isinstance(current_mode,list): max_mode = max([i[0] for i in current_mode]) mode_progress = get_mode_progress(max_mode) color = get_progress_color(max_mode, target_value) return color, mode_progress, target_progress mode_progress = 0 color = 'red' return color, mode_progress, target_progress def get_mode_if_exception_thrown(loc_data): if "Progress undetermined this week" in loc_data.values(): return "Progress undetermined this week" return "No Reports made this week" @login_required def curriculum_progress(request,district_pk=None): locations, user_location, sub_location_type,template_name = get_location_for_curriculum_view(district_pk, request) if request.method == 'POST': curriculum_form = CurriculumForm(data=request.POST) if curriculum_form.is_valid(): target_week = format_to_datetime_object(curriculum_form.cleaned_data['choose_week_to_view']) target_date = target_week[0] else: return render_to_response('education/progress/admin_progress_details.html', {'form': curriculum_form}, RequestContext(request)) else: target_week = get_week_date() curriculum_form = CurriculumForm(initial={'choose_week_to_view': format_week(target_week, ",")}) target_date = target_week[0] loc_data , valid_responses = get_curriculum_data(locations,target_week) try: current_mode = Statistics(valid_responses).mode except StatisticsException: current_mode = get_mode_if_exception_thrown(loc_data) target_value , term = get_target_value(target_date) if isinstance(current_mode,list) and len(current_mode) == 0: current_mode = "Progress undetermined this week" color, mode_progress, target_progress = get_modes_and_target(current_mode, target_value) return render_to_response(template_name, {'form': curriculum_form, 'location_data': loc_data, 'target': target_value, 'current_mode': current_mode, 'mode_progress': mode_progress, 'target_progress': target_progress, 'class_sent_from_behind': color, 'sub_location_type': sub_location_type, 'term': term}, RequestContext(request)) def dash_admin_meetings(req): profile = req.user.get_profile() location = profile.location p = Poll.objects.get(name = 'edtrac_smc_meetings') if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Ministry Officials'): meeting_stats = get_count_response_to_polls(p, #404 is shortcode for unknown choices = [0, 1, 2, 3, 404], # number of meetings with_percent = True, #percentage counted based on number of schools termly = True, admin=True) return render_to_response("education/admin/admin_meetings.html",{ 'meeting_basis': meeting_stats.get('correctly_answered'), 'titles':",".join(str(k) for k in meeting_stats.get('to_ret').keys()), 'meetings':",".join(str(v) for v in meeting_stats.get('to_ret').values()) }, RequestContext(req)) else: meeting_stats = get_count_response_to_polls(p, location_name = location.name, #404 is shortcode for unknown choices = [0, 1, 2, 3, 404], # number of meetings with_percent = True, #percentage counted based on number of schools termly = True, admin = False ) return render_to_response('education/admin/other_meetings.html', {'location_name':location.name, 'meeting_basis': meeting_stats.get('correctly_answered'), 'meetings':",".join(str(v) for v in meeting_stats.get('to_ret').values()), 'titles':",".join(str(k) for k in meeting_stats.get('to_ret').keys()), 'meeting_basis':meeting_stats.get('correctly_answered')}, RequestContext(req)) def preprocess_response(resp): """ reprocess the response values and return just one value """ if not resp: return '--' elif None in resp: return 'wrong response' else: return resp[0] # assumption only one SMC is attached to that school def dash_district_meetings(req, district_name): district = Location.objects.filter(type="district").get(name = district_name) p = Poll.objects.get(name = 'edtrac_smc_meetings') schools_data = EmisReporter.objects.exclude(connection__in = Blacklist.objects.values_list('connection')).\ filter(groups__name = 'SMC', reporting_location = district).exclude(schools = None).order_by('schools__name').\ values_list('schools__name','schools__id','connection__pk') school_container = {} for school_name, school_id, smc_connection in schools_data: school_container[(school_name, school_id)] = preprocess_response([r.eav.poll_number_value for r in p.responses.filter(contact__connection__pk = smc_connection, date__range =[getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END')] )]) #TODO -> sort the school container items return render_to_response( 'education/admin/district_meetings.html', {'location_name':district_name, 'meeting_count':school_container.items()}, RequestContext(req)) # Dashboard specific view functions @login_required @vary_on_cookie def dashboard(request): return admin_dashboard(request) def capitation_grants(locations): # capitation grants cg = Poll.objects.get(name="edtrac_upe_grant") yes_category = cg.categories.get(name='yes') yeses_cg = cg.responses.filter(contact__reporting_location__in=locations, categories__category=yes_category).values_list('contact').distinct().count() # percent of those that received grants head_teacher_count = EmisReporter.objects.exclude(schools=None, connection__in= \ Blacklist.objects.values_list('connection', flat=True)).filter(groups__name='Head Teachers', \ reporting_location__in=locations).count() try: grant_percent = (100 * yeses_cg) / head_teacher_count except ZeroDivisionError: grant_percent = 0 return {'grant_percent': grant_percent} def month_total(poll_name, locations): poll = Poll.objects.get(name=poll_name) return NumericResponsesFor(poll) \ .forLocations(locations) \ .forDateRange(get_month_day_range(datetime.datetime.now(), depth=1)[0]) \ .total() def violence_numbers_girls(locations): return {'violence_numbers_girls' : month_total('edtrac_violence_girls', locations)} def violence_numbers_boys(locations): return {'violence_numbers_boys' : month_total('edtrac_violence_boys', locations)} def violence_numbers_reported(locations): return {'violence_numbers_reported' : month_total('edtrac_violence_reported', locations)} def gendered_text_responses(date_weeks, locations, options, gender): poll = Poll.objects.get(name='edtrac_head_teachers_attendance') gendered_schools = EmisReporter.objects.filter(reporting_location__in = locations, gender = gender, groups__name = "Head Teachers") \ .exclude(schools = None) \ .values('reporting_location__id') result = Response.objects.filter(poll = poll, has_errors = False, message__direction = 'I', date__range = date_weeks, eav_values__value_text__in = options, contact__reporting_location__id__in = gendered_schools) \ .values('contact__reporting_location__id').count() return result or 0 def compute_percent(x,y): if y != 0: return (100 * x) / y else: return 0 def get_two_weeks_absenteeism(gender, locations, get_time): date_weeks = get_week_date(depth=2, get_time=get_time) if is_holiday(date_weeks[0][0], getattr(settings, 'SCHOOL_HOLIDAYS')) \ or is_holiday(date_weeks[1][0], getattr(settings, 'SCHOOL_HOLIDAYS')): return '--','--' else: poll = Poll.objects.get(name='edtrac_head_teachers_attendance') yesses_this_week = gendered_text_responses(date_weeks[0], locations, ['Yes', 'YES', 'yes'], gender) yesses_last_week = gendered_text_responses(date_weeks[1], locations, ['Yes', 'YES', 'yes'], gender) noes_this_week = gendered_text_responses(date_weeks[0], locations, ['No', 'NO', 'no'], gender) noes_last_week = gendered_text_responses(date_weeks[1], locations, ['No', 'NO', 'no'], gender) this_week_absent = compute_percent(noes_this_week, yesses_this_week + noes_this_week) past_week_absent = compute_percent(noes_last_week, yesses_last_week + noes_last_week) return this_week_absent, past_week_absent def p3_absent_boys(locations, get_time=datetime.datetime.now): """ Attendance of P3 Pupils; this gets the absenteeism """ boysp3, boysp3_past = compute_absenteeism_summary('P3Boys',locations,get_time=get_time) return {'boysp3' : boysp3, 'boysp3_past' : boysp3_past,} def p6_boys_absent(locations, get_time=datetime.datetime.now): boysp6, boysp6_past = compute_absenteeism_summary('P6Boys',locations,get_time=get_time) return {'boysp6' : boysp6, 'boysp6_past' : boysp6_past} def p3_absent_girls(locations, get_time=datetime.datetime.now): girlsp3 ,girlsp3_past = compute_absenteeism_summary('P3Girls',locations,get_time=get_time) return {'girlsp3' : girlsp3, 'girlsp3_past' : girlsp3_past} def p6_girls_absent(locations,get_time=datetime.datetime.now): girlsp6,girlsp6_past = compute_absenteeism_summary('P6Girls',locations,get_time=get_time) return {'girlsp6' : girlsp6, 'girlsp6_past' : girlsp6_past} def f_teachers_absent(locations, get_time=datetime.datetime.now): female_teachers ,female_teachers_past = compute_absenteeism_summary('FemaleTeachers',locations,get_time=get_time) return {'female_teachers' :female_teachers,'female_teachers_past' : female_teachers_past,} def m_teachers_absent(locations, get_time=datetime.datetime.now): male_teachers,male_teachers_past = compute_absenteeism_summary('MaleTeachers',locations, get_time=get_time) return {'male_teachers' : male_teachers, 'male_teachers_past' : male_teachers_past} def get_target_week(): for week in get_weeks_in_term(): if week[0] < datetime.datetime.today() < week[1]: return week def progress(stages, stage): numerator = stages.index(stage) + 1 denominator = len(stages) return 100 * numerator / denominator def p3_curriculum(locations): target_week = get_week_date() poll = Poll.objects.get(name='edtrac_p3curriculum_progress') mode = NumericResponsesFor(poll) \ .forDateRange(target_week) \ .forLocations(locations) \ .forValues(themes.keys()) \ .mode() if mode: return {'mode_progress' : progress(sorted(themes.keys()), mode), 'c_mode' : [[mode]]} else: return {'mode_progress' : 0, 'c_mode' : "Progress undetermined this week"} def meals_missed(locations, get_time): poll = Poll.objects.get(name = "edtrac_headteachers_meals") this_month = get_month_day_range(get_time()) schools_without_meals = NumericResponsesFor(poll) \ .forLocations(locations) \ .forDateRange(this_month) \ .excludeGreaterThan(0) \ .groupBySchools() return {'meals_missed' : len(schools_without_meals)} def head_teachers_female(locations, get_time=datetime.datetime.now): female_d1,female_d2 = get_two_weeks_absenteeism('F', locations, get_time) try: f_head_diff = female_d2 - female_d1 if f_head_diff < 0: f_head_t_class = "decrease" f_head_t_data = 'data-red' elif f_head_diff > 0: f_head_t_class = "increase" f_head_t_data = 'data-green' else: f_head_t_class = "zero" f_head_t_data = 'data-white' except: f_head_diff = '--' f_head_t_class = "zero" f_head_t_data = 'data-white' return {'f_head_t_week' : female_d1, 'f_head_t_week_before' : female_d2, 'f_head_diff' : f_head_diff, 'f_head_t_class' : f_head_t_class, 'f_head_t_data':f_head_t_data} def head_teachers_male(locations, get_time=datetime.datetime.now): male_d1, male_d2 = get_two_weeks_absenteeism('M', locations, get_time=get_time) try: m_head_diff = male_d2 - male_d1 if m_head_diff < 0: m_head_t_class = "decrease" m_head_t_data = 'data-red' elif m_head_diff > 0: m_head_t_class = "increase" m_head_t_data = 'data-green' else: m_head_t_class = "zero" m_head_t_data = 'data-white' except: m_head_diff = '--' m_head_t_class = "zero" m_head_t_data = 'data-white' return {'m_head_t_week' : male_d1, 'm_head_t_data':m_head_t_data, 'm_head_t_week_before' : male_d2, 'm_head_diff' : m_head_diff, 'm_head_t_class' : m_head_t_class} def schools_valid(locations, group_names, blacklisted): school_valid = EmisReporter.objects.filter( groups__name__in=group_names, reporting_location__in=locations ).exclude(connection__in=blacklisted).exclude(schools=None) \ .values('schools__id').distinct().count() return {'total_schools_valid': school_valid} def schools_active(locations): try: count_reps = EmisReporter.objects.filter(groups__name__in=['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'], reporting_location__in = locations).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None).count() count = 0 for p in Poll.objects.filter(name__icontains = 'attendance').select_related(): if len(locations) == 1: count += p.responses.filter( contact__reporting_location__in = locations, date__range = get_week_date(depth = 2)[0] ).distinct().select_related().count() else: count += p.responses.filter(date__range = get_week_date(depth=2)[0]).distinct().select_related().count() school_active = (100 * count) / count_reps except ZeroDivisionError: school_active = 0 return {'school_active': school_active} def smc_meetings(locations): # SMC meetings are count based school_to_date = School.objects.filter(pk__in=EmisReporter.objects.\ filter(reporting_location__name__in = [loc.name for loc in locations]).select_related().\ values_list('schools__pk', flat=True)).count() smc_meeting_poll = Poll.objects.get(name = 'edtrac_smc_meetings') meetings = NumericResponsesFor(smc_meeting_poll) \ .excludeZeros() \ .forDateRange([getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END')]) \ .forLocations(locations) \ .total() try: total_meetings = 100 * meetings / school_to_date except ZeroDivisionError: total_meetings = 0 return {'smc_meetings': total_meetings, 'schools_to_date': school_to_date} def total_reporters(locations, group_names, blacklisted): total_reporters = EmisReporter.objects.filter( groups__name__in=group_names, reporting_location__in=locations ).exclude( connection__in=blacklisted ).exclude( schools=None ).count() return {'total_reporters': total_reporters} # generate context vars def generate_dashboard_vars(location): """ An overly ambitious function that generates context variables for a location if provided This gets populated in the dashboard. """ context_vars = {} if location.name == "Uganda": # get locations from active districts only locations = Location.objects.filter(pk__in=EmisReporter.objects.\ values_list('reporting_location__pk', flat=True)).distinct() else: locations = [location] group_names = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] blacklisted = Blacklist.objects.all().values_list('connection', flat=True) # violence girls context_vars.update(violence_numbers_girls(locations)) #violence boys context_vars.update(violence_numbers_boys(locations)) #violence_reported context_vars.update(violence_numbers_reported(locations)) # capitations grants context_vars.update(capitation_grants(locations)) #active schools context_vars.update(schools_active(locations)) #valid schools context_vars.update(schools_valid(locations, group_names, blacklisted)) #SMC meetings context_vars.update(smc_meetings(locations)) #female head teachers that missed school context_vars.update(head_teachers_female(locations)) #male head teachers that missed school context_vars.update(head_teachers_male(locations)) # time stamps context_vars.update({'month':datetime.datetime.now()}) # progress context_vars.update(p3_curriculum(locations)) # Female teachers context_vars.update(f_teachers_absent(locations)) # P3 teachers male context_vars.update(m_teachers_absent(locations)) # P3 boys context_vars.update(p3_absent_boys(locations)) # P3 Girls context_vars.update(p3_absent_girls(locations)) # P6 Girls context_vars.update(p6_girls_absent(locations)) # P6 Boys context_vars.update(p6_boys_absent(locations)) #Meals context_vars.update(meals_missed(locations, get_time = datetime.datetime.now)) #Total Reporters context_vars.update(total_reporters(locations, group_names, blacklisted)) return context_vars # view generator def view_generator(req, enrol_deploy_poll=None, attendance_poll=None, title=None, url_name_district=None, url_name_school = 'school-detail', template_name='education/timeslider_base.html'): """ A generic function to create views based on time ranges. """ time_range_form = ResultForm() profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): # high level officials will access all districts locations = Location.objects.filter(type='district').filter(pk__in =\ EnrolledDeployedQuestionsAnswered.objects.values_list('school__location__pk',flat=True)) else: # other officials will access individual districts locations = [profile.location] if req.method == 'POST': time_range_form = ResultForm(data=req.POST) to_ret = [] if time_range_form.is_valid(): from_date = time_range_form.cleaned_data['from_date'] to_date = time_range_form.cleaned_data['to_date'] month_delta = abs(from_date.month - to_date.month) date_weeks = [] month_flag = None if month_delta <= 2: # same month get days in between month_flag = False # don't split data in months while from_date <= to_date: if from_date.weekday() == 3: #is to_day a Thursday? date_weeks.append(previous_calendar_week(t = from_date)) # get range from Wed to Thur. from_date += datetime.timedelta(days = 1) else: month_flag = True # split data in months while from_date <= to_date: date_weeks.append([dateutils.month_start(from_date),dateutils.month_end(dateutils.increment(from_date, months=1))]) next_date = dateutils.increment(from_date, months = 1) delta = next_date - from_date from_date += datetime.timedelta(days = abs(delta.days)) if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): schools_temp = School.objects.filter(pk__in = \ EnrolledDeployedQuestionsAnswered.objects.select_related().values_list('school__pk', flat=True)) for location in locations: temp = [] # get schools in this location location_schools = schools_temp.select_related().filter(location = location) # store in memory for d in date_weeks: total_attendance = 0 # per school total_enrollment = 0 # per school for school in location_schools: enrolled = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) if enrolled > 0: if month_flag: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'avg') # use averages else: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_enrollment += enrolled try: percentage = (total_enrollment - total_attendance) * 100 / total_enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) return render_to_response(template_name, {'form':time_range_form, 'dataset':to_ret, 'title': title,'month_flag': month_flag, 'url_name':url_name_district, 'date_batch':date_weeks}, RequestContext(req)) else: location_schools = School.objects.filter(pk__in = EnrolledDeployedQuestionsAnswered.objects.select_related().\ filter(school__location=locations[0]).values_list('school__pk', flat=True)).select_related() #Non admin types# for school in location_schools: for d in date_weeks: temp = [] enrollment = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) if month_flag: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'avg') else: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') try: percentage = (enrollment - attendance) * 100 / enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([school, temp]) return render_to_response(template_name, {'form':time_range_form, 'dataset_school':to_ret, 'title': title,'month_flag':month_flag, 'url_name': url_name_school, 'date_batch':date_weeks}, RequestContext(req)) else: return render_to_response(template_name, {'form':time_range_form, 'url_name':url_name_district, 'title':title}, RequestContext(req)) # NO POST data sent! else: date_weeks = [] date_weeks.append(previous_calendar_week(t = datetime.datetime.now())) sw = date_weeks[0][0] date_weeks.append(previous_calendar_week(t = dateutils.increment(datetime.datetime(sw.year, sw.month, sw.day, 10), weeks = -1))) location_data = [] schools_temp = School.objects.select_related().\ filter(pk__in =\ EnrolledDeployedQuestionsAnswered.objects.select_related().filter(school__location__in=locations).values_list('school__pk',flat=True)) context_vars = {} if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): for location in locations: temp = [] # get schools in this location location_schools = schools_temp.select_related().filter(location = location) for d in date_weeks: total_attendance = 0 # per school total_enrollment = 0 # per school for school in location_schools: enrolled = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_enrollment += enrolled try: percentage = (total_enrollment - total_attendance) * 100 / total_enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) try: diff = temp[0] - temp[1] except TypeError: diff = '--' location_data.append([location, temp[0], temp[1], diff]) context_vars.update({'location_data':location_data}) else: location_schools = School.objects.select_related().filter(pk__in = EnrolledDeployedQuestionsAnswered.objects.select_related().\ filter(school__location=locations[0]).values_list('school__pk', flat=True)) #Non admin types to_ret = [] for school in location_schools: enrollment = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) temp = [] for d in date_weeks: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') try: percentage = (enrollment - attendance) * 100 / enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([school, temp]) context_vars = {'form':time_range_form, 'dataset_school':to_ret, 'title': title, 'url_name': url_name_school, 'date_batch':date_weeks} if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): x = {'url_name':url_name_district, 'headings':['District', 'Current week', 'Previous week', 'Percentage difference']} else: x = {'url_name':url_name_school, 'headings':['School', 'Current week', 'Previous week', 'Percentage difference']} if context_vars.has_key('form') ==False and context_vars.has_key('title') == False: context_vars.update({'form':time_range_form,'title':title}) # add the keys to context_vars dict context_vars.update(x) return render_to_response(template_name, context_vars, RequestContext(req)) @login_required def admin_dashboard(request): if request.user.get_profile().is_member_of('Ministry Officials') or request.user.get_profile().is_member_of('Admins')\ or request.user.get_profile().is_member_of('UNICEF Officials'): location = Location.objects.get(name="Uganda") else: location = request.user.get_profile().location key = "context-vars-for-location-" + str(location.id) context_vars = cache.get(key) if not context_vars: context_vars = generate_dashboard_vars(location=location) cache.set(key, context_vars, 60 * 60) return render_to_response("education/admin/admin_dashboard.html", context_vars, RequestContext(request)) class NationalStatistics(TemplateView): template_name = "education/admin/national_statistics.html" groups = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] def compute_percent(self, reps, groups = groups): all_reporters = EmisReporter.objects.filter(groups__name__in=groups).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None) try: reps.count() / all_reporters.count() except ZeroDivisionError: return 0 def get_context_data(self, **kwargs): context = super(NationalStatistics, self).get_context_data(**kwargs) groups = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] all_reporters = EmisReporter.objects.filter(groups__name__in=groups).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None) profile = self.request.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): districts = Location.objects.filter(type="district").\ filter(name__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in=Blacklist.objects.values_list('connection',flat=True)).values_list('reporting_location__name', flat=True)) reps = EmisReporter.objects.select_related().filter(groups__name__in=['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters'], connection__in=Message.objects.\ filter(date__range = get_week_date(depth = 2)[1]).values_list('connection', flat = True)).exclude(schools = None).exclude(connection__in = Blacklist.objects.values_list('connection', flat=True)) district_schools = [ (district, School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).\ filter(reporting_location__name = district.name).distinct().values_list('schools__pk',flat=True)).count()) for district in districts ] context['total_districts'] = districts.count() context['district_schools'] = district_schools schools= School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).\ exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).distinct().values_list('schools__pk',flat=True)) context['school_count'] = schools.count() total_schools = 0 for district in districts: s_count = School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).\ filter(reporting_location__name = district.name).distinct().values_list('schools__pk',flat=True)).count() total_schools += s_count context['total_schools'] = total_schools district_active = [ ( district, self.compute_percent(reps.filter(reporting_location__pk=district.pk), groups=['Head Teachers']) ) for district in districts ] district_active.sort(key=operator.itemgetter(1), reverse=True) context['district_active'] = district_active[:3] context['district_less_active'] = district_active[-3:] head_teacher_count = all_reporters.filter(groups__name='Head Teachers').count() smc_count = all_reporters.filter(groups__name = "SMC").count() p6_teacher_count = all_reporters.filter(groups__name = "Teachers", grade = "P6").count() p3_teacher_count = all_reporters.filter(groups__name = "Teachers", grade = "P3").count() total_teacher_count = all_reporters.filter(groups__name="Teachers").count() deo_count = all_reporters.filter(groups__name="DEO").count() gem_count = all_reporters.filter(groups__name="GEM").count() teacher_data_unclean = total_teacher_count - p3_teacher_count - p6_teacher_count context['head_teacher_count'] = head_teacher_count context['smc_count'] = smc_count context['p6_teacher_count'] = p6_teacher_count context['p3_teacher_count'] = p3_teacher_count context['total_teacher_count'] = total_teacher_count context['teacher_data_unclean'] = teacher_data_unclean context['deo_count'] = deo_count context['gem_count'] = gem_count context['all_reporters'] = all_reporters.count() context['expected_reporters'] = schools.count() * 4 # reporters that used EduTrac the past week active_school_reporters = all_reporters.filter(connection__in=Message.objects.exclude(application='script').\ filter(date__range = get_week_date(depth = 2)[1]).values_list('connection', flat = True)) school_active = [ (school, self.compute_percent(active_school_reporters.filter(schools__pk=school.pk), groups=['Head Teachers', 'Teachers', 'GEM', 'SMC','Other Reporters'])) for school in schools ] school_active.sort(key=operator.itemgetter(1), reverse=True) context['school_active_count'] = School.objects.filter(pk__in = active_school_reporters.values_list('schools__pk', flat=True)).count() context['school_active'] = school_active[:3] context['school_less_active'] = school_active[-3:] return context else: return self.render_to_response(dashboard(self.request)) def get_term_range(term): if term == 'first': return [getattr(settings,'FIRST_TERM_BEGINS'),dateutils.increment(getattr(settings,'FIRST_TERM_BEGINS'),weeks=12)] if term == 'second': return [getattr(settings,'SECOND_TERM_BEGINS'),dateutils.increment(getattr(settings,'SECOND_TERM_BEGINS'),weeks=12)] if term == 'third': return [getattr(settings,'THIRD_TERM_BEGINS'),dateutils.increment(getattr(settings,'THIRD_TERM_BEGINS'),weeks=12)] if term == '' or term =='current' or term is None: return [getattr(settings,'SCHOOL_TERM_START'),getattr(settings,'SCHOOL_TERM_END')] class CapitationGrants(TemplateView): poll_name ='' restrict_group='' def compute_percent(self, x, y): try: return (100 * x) / y except ZeroDivisionError: return 0 def _extract_info(self, list): to_ret = [] for item in list: to_ret.append( [item.get('category__name'), item.get('value')] ) final_ret = {} for li in to_ret: final_ret[li[0]] = li[1] total = sum(filter(None, final_ret.values())) for key in final_ret.keys(): final_ret[key] = self.compute_percent(final_ret.get(key), total) return final_ret def _get_per_category_responses_for_school(self, responses_by_category, school): info = [stat for stat in responses_by_category if stat['response__contact__emisreporter__schools__name'] == school.name] return school, self._extract_info(info).items() def _get_schools_info(self, responses_at_location,location): responses_by_category = responses_at_location.values( 'response__contact__emisreporter__schools__name', 'category__name').annotate(value=Count('pk')) schools = location.schools.all() return [self._get_per_category_responses_for_school(responses_by_category, school) for school in schools] def get_context_data(self, **kwargs): term = self.kwargs.get('term') term_range = get_term_range(term) context = super(CapitationGrants, self).get_context_data(**kwargs) cg = Poll.objects.select_related().get(name=self.poll_name) authorized_users = ['Admins', 'Ministry Officials', 'UNICEF Officials'] authorized_user = False for auth_user in authorized_users: if self.request.user.get_profile().is_member_of(auth_user): authorized_user = True break context['authorized_user'] = authorized_user er = EmisReporter.objects.select_related() unknown_unknowns = cg.responses.filter(~Q(message__text__iregex="i don('?)t know"), categories__category__name="unknown") if authorized_user: reporter_count = er.filter(groups__name=self.restrict_group).exclude(schools=None).count() all_responses = cg.responses_by_category().exclude(response__in=unknown_unknowns).filter(response__date__range=term_range) locs = Location.objects.filter( type="district", pk__in= \ er.exclude(connection__in=Blacklist.objects. \ values_list('connection', flat=True), schools=None).filter(groups__name=self.restrict_group). \ values_list('reporting_location__pk', flat=True)) districts_to_ret = [] for location in locs: info = self._extract_info(all_responses.filter(response__contact__reporting_location=location)) districts_to_ret.append((location, info.items())) total_responses = all_responses.values_list('response__contact').distinct().count() context['responses'] = self._extract_info(all_responses).items() context['location'] = Location.tree.root_nodes()[0] context['sub_locations'] = districts_to_ret context['sub_location_type'] = "district" else: location = self.request.user.get_profile().location all_responses = cg.responses_by_category().exclude(response__in=unknown_unknowns).filter(response__date__range=term_range) responses_at_location = all_responses.filter(response__contact__reporting_location=location) total_responses = responses_at_location.values_list('response__contact').distinct().count() reporter_count = er.exclude(schools=None, connection__in= \ Blacklist.objects.values_list('connection', flat=True)).filter(groups__name=self.restrict_group, \ reporting_location=location).count() context['responses'] = self._extract_info(responses_at_location).items() context['location'] = location context['sub_locations'] = self._get_schools_info(responses_at_location, location) context['sub_location_type'] = "school" context['reporter_count'] = self.compute_percent(total_responses, reporter_count) context['group'] = self.restrict_group return context # Details views... specified by ROLES def set_logged_in_users_location(profile): if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of( 'Admins'): location = Location.objects.get(name='Uganda') else: location = profile.location return location def violence_details_dash(req): profile = req.user.get_profile() context_vars = {} location = set_logged_in_users_location(profile) violence_cases_girls = poll_response_sum("edtrac_violence_girls", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_boys = poll_response_sum("edtrac_violence_boys", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_reported = poll_response_sum("edtrac_violence_reported", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_gem = poll_response_sum('edtrac_gem_abuse', location=location, month_filter='monthly', months=2, ret_type=list) girls_total = [] for name, list_val in violence_cases_girls: girls_total.append((list_val[0], list_val[1])) context_vars['violence_cases_girls'] = violence_cases_girls girls_first_col, girls_second_col = [],[] for first, second in girls_total: girls_first_col.append(first), girls_second_col.append(second) girls_first_col = [i for i in girls_first_col if i != '--'] girls_second_col = [i for i in girls_second_col if i != '--'] context_vars['girls_totals'] = [sum(girls_first_col), sum(girls_second_col)] boys_total = [] for name, list_val in violence_cases_boys: boys_total.append((list_val[0], list_val[1])) context_vars['violence_cases_boys'] = violence_cases_boys boys_first_col, boys_second_col = [],[] for first, second in boys_total: boys_first_col.append(first), boys_second_col.append(second) boys_first_col = [i for i in boys_first_col if i != '--'] boys_second_col = [i for i in boys_second_col if i != '--'] context_vars['boys_totals'] = [sum(boys_first_col), sum(boys_second_col)] reported_total = [] for name, list_val in violence_cases_reported: reported_total.append((list_val[0], list_val[1])) context_vars['violence_cases_reported'] = violence_cases_reported reported_first_col, reported_second_col = [],[] for first, second in reported_total: reported_first_col.append(first), reported_second_col.append(second) reported_first_col = [i for i in reported_first_col if i != '--'] reported_second_col = [i for i in reported_second_col if i != '--'] context_vars['reported_totals'] = [sum(reported_first_col), sum(reported_second_col)] gem_total = [] # total violence cases reported by school for name, list_val in violence_cases_gem: gem_total.append((list_val[0], list_val[1])) context_vars['violence_cases_reported_by_gem'] = violence_cases_gem first_col, second_col = [],[] for first, second in gem_total: first_col.append(first), second_col.append(second) first_col = [i for i in first_col if i != '--'] second_col = [i for i in second_col if i != '--'] context_vars['gem_totals'] = [sum(first_col), sum(second_col)] context_vars['report_dates'] = [start for start, end in get_month_day_range(datetime.datetime.now(), depth=2)] school_report_count = 0 gem_report_count = 0 for dr in get_month_day_range(datetime.datetime.now(), depth=2): if profile.location.type.name == 'country': contacts = Contact.objects.select_related().filter(reporting_location__in=profile.\ location.get_descendants().filter(type="district")) else: contacts = Contact.objects.select_related().filter(reporting_location=profile.location) school_resp_count = Poll.objects.select_related().get(name="edtrac_violence_girls").responses.filter( contact__in = contacts, date__range = dr).count() gem_resp_count = Poll.objects.select_related().get(name="edtrac_gem_abuse").responses.filter( contact__in = contacts, date__range = dr).count() school_report_count += school_resp_count gem_report_count += gem_resp_count try: context_vars['sch_reporting_percentage'] = 100 * ( school_report_count / (float(len(get_month_day_range(datetime.datetime.now(), depth=2))) * school_report_count)) except ZeroDivisionError: context_vars['sch_reporting_percentage'] = 0 try: context_vars['gem_reporting_percentage'] = 100 * ( gem_report_count / (float(len(get_month_day_range(datetime.datetime.now(), depth=2))) * gem_report_count)) except ZeroDivisionError: context_vars['gem_reporting_percentage'] = 0 now = datetime.datetime.now() month_ranges = get_month_day_range(now, depth=now.month) month_ranges.sort() h_teach_month = [] girls_violence_month = [] boys_violence_month =[] reported_violence_month = [] h_teach_data = [] gem_data = [] girls_violence_data = [] boys_violence_data = [] reported_violence_data = [] if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Admins'): for month_range in month_ranges: h_teach_month.append(month_range[0].strftime('%B')) h_teach_data.append(get_numeric_report_data('edtrac_violence_girls',time_range=month_range, to_ret = 'sum')) gem_data.append(get_numeric_report_data('edtrac_gem_abuse',time_range=month_range, to_ret = 'sum')) girls_violence_month.append(month_range[0].strftime('%B')) girls_violence_data.append(get_numeric_report_data('edtrac_violence_girls', time_range=month_range, to_ret='sum')) boys_violence_month.append(month_range[0].strftime('%B')) boys_violence_data.append(get_numeric_report_data('edtrac_violence_boys', time_range=month_range, to_ret='sum')) reported_violence_month.append(month_range[0].strftime('%B')) reported_violence_data.append(get_numeric_report_data('edtrac_violence_reported', time_range=month_range, to_ret='sum')) else: for month_range in month_ranges: h_teach_month.append(month_range[0].strftime('%B')) h_teach_data.append(get_numeric_report_data('edtrac_girls_violence',time_range=month_range, to_ret = 'sum', location=profile.location)) gem_data.append(get_numeric_report_data('edtrac_gem_abuse',time_range=month_range, to_ret = 'sum', location=profile.location)) girls_violence_month.append(month_range[0].strftime('%B')) girls_violence_data.append(get_numeric_report_data('edtrac_violence_girls', time_range=month_range, to_ret='sum', location=profile.location)) boys_violence_month.append(month_range[0].strftime('%B')) boys_violence_data.append(get_numeric_report_data('edtrac_violence_boys', time_range=month_range, to_ret='sum', location=profile.location)) reported_violence_month.append(month_range[0].strftime('%B')) reported_violence_data.append(get_numeric_report_data('edtrac_violence_reported', time_range=month_range, to_ret='sum', location=profile.location)) monthly_data_h_teachers = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(h_teach_month, h_teach_data)]) monthly_violence_data_girls = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(girls_violence_month, girls_violence_data)]) monthly_violence_data_boys = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(boys_violence_month, boys_violence_data)]) monthly_violence_data_reported = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(reported_violence_month, reported_violence_data)]) gem_month = copy.deepcopy(h_teach_month) monthly_data_gem = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(gem_month, gem_data)]) context_vars['monthly_data_gem'] = monthly_data_gem context_vars['monthly_violence_data_girls'] = monthly_violence_data_girls context_vars['monthly_violence_data_boys'] = monthly_violence_data_boys context_vars['monthly_violence_data_reported'] = monthly_violence_data_reported context_vars['monthly_data_h_teach'] = monthly_data_h_teachers context_vars['schools_responding_to_all_questions'] = total_number_of_schools_that_responded_to_all_violence_questions() if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Admins'): return render_to_response('education/admin/admin_violence_details.html', context_vars, RequestContext(req)) elif profile.is_member_of('DEO'): context_vars['location_name'] = profile.location return render_to_response('education/deo/deo2_violence_details.html', context_vars, RequestContext(req)) def total_number_of_schools_that_responded_to_all_violence_questions(): schools_responding_to_boys_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_boys")] schools_responding_to_girls_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_girls")] schools_that_referred_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_reported")] schools_that_answered_all_questions = list(set(schools_responding_to_boys_violence).intersection(schools_responding_to_girls_violence).intersection(schools_that_referred_violence)) valid_school_names = [school for school in schools_that_answered_all_questions if school is not None] return len(valid_school_names) def __get_school_name_from(response): try: school_name = response.contact.emisreporter.schools.all()[0].name except IndexError: school_name = None return school_name def __get_responses_for(poll_name): responses_for_all_questions = Response.objects.filter(poll__name__in =["edtrac_violence_girls","edtrac_violence_boys","edtrac_violence_reported"]) return responses_for_all_questions.filter(poll__name = poll_name) class DistrictViolenceDetails(TemplateView): template_name = "education/dashboard/district_violence_detail.html" def get_context_data(self, **kwargs): context = super(DistrictViolenceDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) or self.request.user.get_profile().location schools = School.objects.filter( pk__in = EmisReporter.objects.filter(reporting_location=location).values_list('schools__pk', flat=True)) school_case = [] month_now, month_before = get_month_day_range(datetime.datetime.now(), depth=2) totalViolence = 0 nowViolence = 0 beforeViolence = 0 for school in schools: # optimize with value queries now_data = get_numeric_report_data( 'edtrac_headteachers_abuse', time_range = month_now, school = school, to_ret = 'sum', belongs_to = 'schools') before_data = get_numeric_report_data('edtrac_headteachers_abuse', time_range = month_before, school = school,\ to_ret = 'sum', belongs_to = 'schools') data = int(now_data + before_data) totalViolence += data nowViolence += now_data beforeViolence += before_data if now_data > 0 or before_data > 0: school_case.append((school, now_data, before_data, data)) context['totalViolence'] = totalViolence context['nowViolence'] = nowViolence context['beforeViolence'] = beforeViolence context['location'] = location context['school_vals'] = school_case context['month_now'] = month_now[0] context['month_before'] = month_before[0] return context class AttendanceAdminDetails(TemplateView): template_name = "education/admin/attendance_details.html" def get_context_data(self, **kwargs): context = super(AttendanceAdminDetails, self).get_context_data(**kwargs) #TODO: proper drilldown of attendance by school # National level ideally "admin" and can be superclassed to suit other roles profile = self.request.user.get_profile() context['role_name'] = profile.role.name if profile.is_member_of("Admins") or profile.is_member_of("Ministry Officials") or profile.is_member_of('UNICEF Officials'): names = list(set(EmisReporter.objects.exclude(reporting_location=None).filter(reporting_location__type="district").\ values_list('reporting_location__name',flat=True))) locations = Location.objects.filter(name__in=names).order_by("name") context['total_disticts'] = locations.count() headings = [ 'Location', 'Boys P3', 'Boys P6', 'Girls P3', 'Girls P6', 'Female Teachers', "Male Teachers"] context['headings'] = headings context['week'] = datetime.datetime.now() context['location'] = profile.location return context # search functionality def search_form(req): searchform = SearchForm() if req.method == 'POST': searchform = SearchForm(req.POST) if searchform.is_valid(): searchform.save() return render_to_response( 'education/partials/search-form.html', {'form': searchform}, RequestContext(req) ) class ProgressAdminDetails(TemplateView): template_name = "education/progress/admin_progress_details.html" def get_context_data(self, **kwargs): context = super(ProgressAdminDetails, self).get_context_data(**kwargs) context['progress'] = list_poll_responses(Poll.objects.get(name="edtrac_p3curriculum_progress")) getcontext().prec = 1 context['progress_figures'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_p3curriculum_progress"),\ location=self.request.user.get_profile().location, choices = [Decimal(str(key)) for key in themes.keys()]) return context CHOICES = [0, 25, 50, 75, 100] class MealsAdminDetails(TemplateView): template_name = "education/admin/admin_meals_details.html" def get_context_data(self, **kwargs): choices = CHOICES context = super(MealsAdminDetails, self).get_context_data(**kwargs) context['school_meals_reports'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_headteachers_meals"),\ month_filter=True, choices=choices) context['community_meals_reports'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_smc_meals"), month_filter=True, choices=choices, with_percent=True) districts = Location.objects.filter(type="district", id__in =\ EmisReporter.objects.exclude(reporting_location = None).\ values_list('reporting_location__id', flat=True)).order_by('name').\ values_list('name', flat=True) # basic filtering for CSS districts = [[d, False] for d in districts] districts[0][1] = True context['districts'] = districts return context # Meals being had at a district class DistrictMealsDetails(DetailView): template_name = "education/admin/district_meal.html" context_object_name = "district_meals" model = Location def get_object(self): return self.model.objects.filter(type="district").get(name = self.kwargs.get('name')) def get_context_data(self, **kwargs): context = super(DistrictMealsDetails, self).get_context_data(**kwargs) location = self.get_object() choices = CHOICES school_meal_reports = get_count_response_to_polls( Poll.objects.get(name="edtrac_headteachers_meals"), location_name = location.name, month_filter=True, choices=choices, with_range = True, with_percent = True ) context['school_meals_reports'] = school_meal_reports context['location'] = location now = datetime.datetime.now() ranges = get_month_day_range(now, depth = now.month) ranges.reverse() context['date_ranges'] = ranges return context @login_required def deo_dashboard(req): location = req.user.get_profile().location return render_to_response("education/deo/deo_dashboard.html", generate_dashboard_vars(location=location), RequestContext(req)) @login_required def quitters(req): quitters = EmisReporter.objects.filter(connection__identity__in=Blacklist.objects.values_list('connection__identity',flat=True)) return render_to_response('education/partials/reporters/quitters.html',{'quitters':quitters}, RequestContext(req)) class ViolenceDeoDetails(TemplateView): template_name = "education/deo/deo_violence_details.html" def get_context_data(self, **kwargs): context = super(ViolenceDeoDetails, self).get_context_data(**kwargs) #context['violence_cases'] = list_poll_responses(Poll.objects.get(name="emis_headteachers_abuse")) context['violence_cases'] = poll_response_sum(Poll.objects.get(name="edtrac_headteachers_abuse"), location=self.request.user.get_profile().location, month_filter=True) return context @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ViolenceDeoDetails, self).dispatch(*args, **kwargs) class ProgressDeoDetails(TemplateView): template_name = "education/deo/deo_progress_details.html" def get_context_data(self, **kwargs): context = super(ProgressDeoDetails, self).get_context_data(**kwargs) #TODO mixins and filters context['progress'] = list_poll_responses(Poll.objects.get(name="edtrac_p3curriculum_progress")) return context ########################################################################################################## ########################################################################################################## ############################ More Generic Views ########################################################## ########################################################################################################## ########################################################################################################## ## management control panel @login_required def control_panel(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Ministry Officials'): return render_to_response('education/partials/control_panel.html', {}, RequestContext(req)) else: return render_to_response('education/partials/control_panel_dist.html',{}, RequestContext(req)) @login_required def audit_trail(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): # aparently the only places where comments are made is functions that involve editing users, reporters, etc. revisions = Revision.objects.exclude(comment='').order_by('-date_created').values_list('user__username','comment','date_created') else: revisions = Revision.objects.exclude(user__username = 'admin', comment='').\ order_by('-date_created').values_list('user__username','comment','date_created') return render_to_response('education/admin/audit_trail.html',{'revisions':revisions}, RequestContext(req)) class DistrictViolenceCommunityDetails(DetailView): context_object_name = "district_violence" model = Location def get_context_data(self, **kwargs): context = super(DistrictViolenceCommunityDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) or self.request.user.get_profile().location emis_reporters = EmisReporter.objects.filter(groups__name="GEM", connection__in =\ Poll.objects.get(name="edtrac_gem_abuse").responses.values_list('contact__connection',flat=True)) context['location'] = location context['reporters'] = emis_reporters context['month'] = datetime.datetime.now() return context # Progress happening in a district class DistrictProgressDetails(DetailView): context_object_name = "district_progress" model = Location #TODO provide filters def get_context_data(self, **kwargs): context = super(DistrictProgressDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) context['location'] = location return context ########################################################################################################## ########################################################################################################## ################################ Other handy views for EduTrac ############################################ ########################################################################################################## ########################################################################################################## HEADINGS = ['District', 'Absent (%) This week', 'Absent (%) Last week'] #define location and school for p3 and p6 students locale = Location.objects.exclude(type="country").filter(type="district") @login_required def boysp3_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_boysp3_enrollment','edtrac_boysp3_attendance') return render_to_response("education/boysp3_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data', 'Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def boysp6_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_boysp6_enrollment','edtrac_boysp6_attendance') return render_to_response("education/boysp6_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def girlsp3_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_girlsp3_enrollment','edtrac_girlsp3_attendance') return render_to_response("education/girlsp3_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def girlsp6_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_girlsp6_enrollment','edtrac_girlsp6_attendance') return render_to_response("education/girlsp6_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def female_t_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_f_teachers_deployment','edtrac_f_teachers_attendance') return render_to_response("education/female_t_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def male_t_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_m_teachers_deployment','edtrac_m_teachers_attendance') return render_to_response("education/male_t_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) def boys_p3_attendance(req, **kwargs): profile = req.user.get_profile() location = profile.location if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): """ This view shows data by district """ locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.select_related().distinct().values_list('reporting_location__name', flat=True)).order_by("name") # return view that will give school-based views # --> ref function just below this <--- return boys_p3_attd_admin(req, locations=locations) else: #DEO dates = kwargs.get('dates') schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] for d in dates: temp.extend(return_absent('edtrac_boysp3_attendance', 'edtrac_boysp3_enrollment', school = school, date_week=d)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location':location } def boys_p3_attd_admin(req, **kwargs): """ Helper function to get differences in absenteeism across districts. """ # P3 attendance /// what to show an admin or Ministry official locations = kwargs.get('locations') to_ret = return_absent('edtrac_boysp3_attendance', 'edtrac_boysp3_enrollment', locations) return {'location_data':to_ret, 'headings': HEADINGS, 'week':datetime.datetime.now()} def boys_p6_attendance(req): profile = req.user.get_profile() location = profile.location if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return boys_p6_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_boysp6_attendance', 'edtrac_boysp6_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def boys_p6_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P6 boys. """ # P6 attendance /// what to show an admin or Ministry official to_ret = return_absent('edtrac_boysp6_attendance', 'edtrac_boysp6_enrollment', locations=locations) return {'location_data':to_ret,'headings':HEADINGS,'week':datetime.datetime.now()} def girls_p3_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return girls_p3_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_girlsp3_attendance', 'edtrac_girlsp3_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def girls_p3_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P3 girls """ to_ret = return_absent('edtrac_girlsp3_attendance', 'edtrac_girlsp3_enrollment', locations=locations) return {'location_data':to_ret,'headings':HEADINGS,'week':datetime.datetime.now()} def girls_p6_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return girls_p6_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_girlsp6_attendance', 'edtrac_girlsp6_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def girls_p6_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P6 girls """ to_ret = return_absent('edtrac_girlsp6_attendance', 'edtrac_girlsp6_enrollment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def female_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.distinct().values_list('reporting_location__name',flat=True)).order_by("name") return female_teacher_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_f_teachers_attendance', 'edtrac_f_teachers_deployment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def female_teacher_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for all female teachers """ to_ret = return_absent('edtrac_f_teachers_attendance', 'edtrac_f_teachers_deployment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def male_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.distinct().values_list('reporting_location__name',flat=True)).order_by("name") return male_teacher_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_m_teachers_attendance', 'edtrac_m_teachers_deployment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def male_teacher_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for all female teachers """ to_ret = return_absent('edtrac_m_teachers_attendance', 'edtrac_m_teachers_deployment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def male_head_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): schools = School.objects.filter(location__name__in=EmisReporter.objects.distinct().\ filter(reporting_location__type = 'district').values_list('reporting_location__name', flat=True)) else: #DEO schools = School.objects.filter(location=location) data_to_render = [] for school in schools: #TODO separate male and female head teachers data = poll_response_sum(Poll.objects.get(name="edtrac_head_teachers_attendance"),month_filter='weekly',location=school.location) data_to_render.append( [ school, school.location, data ] ) return render_to_response( 'education/partials/male_head_teacher_attendance.html', { 'week':datetime.datetime.now(), 'headings':['School', 'District', 'Number'], 'location_data': data_to_render }, RequestContext(req) ) def female_head_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): schools = School.objects.filter(location__name__in= EmisReporter.objects.distinct().\ select_related().filter(reporting_location__type = 'district').values_list('reporting_location__name', flat=True)) else: #DEO schools = School.objects.select_related().filter(location=location).order_by("name", "location__name") data_to_render = [] for school in schools: #TODO separate male and female head teachers data = poll_response_sum(Poll.objects.get(name="edtrac_head_teachers_attendance"),month_filter='weekly',location=school.location) data_to_render.append( [ school, school.location, data ] ) return render_to_response( 'education/partials/female_head_teacher_attendance.html', { 'week':datetime.datetime.now(), 'headings':['School', 'District', 'Number'], 'location_data': data_to_render }, RequestContext(req) ) @login_required def time_range_boysp3(req): return view_stats(req, enrol_deploy_poll='edtrac_boysp3_enrollment', attendance_poll='edtrac_boysp3_attendance', title='P3 Boys Absenteeism', url_name_district = "boysp3-district-attd-detail" ) @login_required def time_range_boysp6(req): return view_stats(req, enrol_deploy_poll='edtrac_boysp6_enrollment', attendance_poll='edtrac_boysp6_attendance', title='P6 Boys Absenteeism', url_name_district = "boysp6-district-attd-detail" ) @login_required def time_range_girlsp3(req): return view_stats(req, enrol_deploy_poll='edtrac_girlsp3_enrollment', attendance_poll='edtrac_girlsp3_attendance', title='P3 Girls Absenteeism', url_name_district = "girlsp3-district-attd-detail" ) @login_required def time_range_girlsp6(req): return view_stats(req, enrol_deploy_poll='edtrac_girlsp6_enrollment', attendance_poll='edtrac_girlsp6_attendance', title='P6 Girls Absenteeism', url_name_district = "girlsp6-district-attd-detail" ) @login_required def time_range_teachers_m(req): return view_stats(req, enrol_deploy_poll='edtrac_m_teachers_deployment', attendance_poll='edtrac_m_teachers_attendance', title='Male teachers absenteeism', url_name_district = "male-teacher-district-attd-detail" ) @login_required def time_range_teachers_f(req): return view_stats(req, enrol_deploy_poll='edtrac_f_teachers_deployment', attendance_poll='edtrac_f_teachers_attendance', title='Female teachers absenteeism', url_name_district = "female-teacher-district-attd-detail" ) @login_required def time_range_head_teachers(req): """ Get a date-ranged page for Head teachers """ """ A function that compute time-ranged data for female teachers. This function is split in two: handling of POST data and GET data. It also makes a difference between User groups so you different role players like DEO, Admins, UNICEF Officials """ time_range_form = ResultForm() locations = Location.objects.filter(type='district').filter(pk__in = EmisReporter.objects.values_list('reporting_location__pk',flat=True)) if req.method == 'POST': # handling of POST data time_range_form = ResultForm(data=req.POST) to_ret = [] if time_range_form.is_valid(): from_date = time_range_form.cleaned_data['from_date'] to_date = time_range_form.cleaned_data['to_date'] month_delta = abs(from_date.month - to_date.month) date_weeks = [] if month_delta <= 2: # same month get days in between while from_date <= to_date: if from_date.weekday() == 3: #is to_day a Thursday? date_weeks.append(previous_calendar_week(t = from_date)) # get range from Wed to Thur. from_date += datetime.timedelta(days = 1) else: # case for when more than 2 months is selected while from_date <= to_date: #TODO refine data points date_weeks.append([dateutils.month_start(from_date),dateutils.month_end(from_date)]) from_date = dateutils.increment(from_date, months = 1) # splitting the results by analysing membership of Officials accessing EduTrac if req.user.get_profile().is_member_of('Ministry Officials') or\ req.user.get_profile().is_member_of('Admins') or req.user.get_profile().is_member_of('UNICEF Officials'): schools_temp = School.objects.select_related().\ filter(pk__in = EmisReporter.objects.select_related().\ filter(groups__name = "Head Teachers").values_list('schools__pk',flat=True)) for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True).select_related() location_schools = School.objects.filter(pk__in = schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) else: #Non admin types date_weeks, to_ret = [], [] date_weeks.append(previous_calendar_week(t = datetime.datetime.now())) for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True) location_schools = School.objects.filter(pk__in=schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) return render_to_response('education/timeslider_base.html', {'form':time_range_form, 'dataset':to_ret, 'title':'Female Teacher Absenteeism', 'url_name':"female-teacher-district-attd-detail", 'date_batch':date_weeks}, RequestContext(req)) else: return render_to_response('education/timeslider_base.html', {'form':time_range_form, 'url_name':"female-teacher-district-attd-detail", 'title':'Male Teacher Absenteeism'}, RequestContext(req)) else: # initial GET view is displays difference between 2 weeks of the attendance of female teachers as reported by the Head Teacher date_weeks = [] location_data = [] # get current week date_weeks.append(previous_calendar_week()) temp_date = datetime.datetime(date_weeks[0][0].year, date_weeks[0][0].month, date_weeks[0][0].day) - datetime.timedelta(days = 1) # add previous week to date_weeks list date_weeks.append(previous_calendar_week(t = temp_date)) # cache schools query in memory (these are Schools that have enrollment data) schools_temp = Poll.objects.select_related().get(name = 'edtrac_f_teachers_deployment').responses.\ exclude(contact__emisreporter__schools__name = None).select_related() context_vars = {} for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True) location_schools = School.objects.filter(pk__in = schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) try: diff = temp[0] - temp[1] except TypeError: diff = '--' location_data.append([location, temp[0], temp[1], diff]) context_vars.update({'location_data':location_data}) profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): x = {'url_name':"female-teacher-district-attd-detail", "headings":["District", "Current Week", "Previous Week", "Percentage Change"]} else: x = {'url_name':"school-detail", "headings":["School", "Current Week", "Previous Week", "Percentage Change"]} context_vars.update({'form':time_range_form,'title':'Female Teachers Absenteeism'}) context_vars.update(x) return render_to_response('education/timeslider_base.html', context_vars, RequestContext(req)) def whitelist(request): numbers = [] for c in Connection.objects.exclude(backend__name='yo6200'): if not c.identity.strip() in numbers: numbers.append(c.identity.strip()) return render_to_response( "education/whitelist.txt", {'connections': Connection.objects.exclude(backend__name='yo6200').filter(identity__in=numbers)}, mimetype="text/plain", context_instance=RequestContext(request)) def _reload_whitelists(): refresh_urls = getattr(settings, 'REFRESH_WHITELIST_URL', None) if refresh_urls is not None: if not type(refresh_urls) == list: refresh_urls = [refresh_urls, ] for refresh_url in refresh_urls: try: status_code = urlopen(refresh_url).getcode() if int(status_code / 100) == 2: continue else: return False except Exception as e: return False return True return False def _addto_autoreg(connections): for connection in connections: if not connection.contact and\ not ScriptProgress.objects.filter(script__slug='emis_autoreg', connection=connection).count(): ScriptProgress.objects.create(script=Script.objects.get(slug="edtrac_autoreg"),\ connection=connection) @login_required def add_connection(request): form = NewConnectionForm() if request.method == 'POST': form = NewConnectionForm(request.POST) connections = [] if form.is_valid(): identity = form.cleaned_data['identity'] identity, backend = assign_backend(str(identity.strip())) # create connection, created = Connection.objects.get_or_create(identity=identity, backend=backend) # in case a duplicate process does exist, delete it ScriptProgress.objects.filter(connection=connection).delete() connections.append(connection) other_numbers = request.POST.getlist('other_nums') if len(other_numbers) > 0: for number in other_numbers: identity, backend = assign_backend(str(number.strip())) connection, created = Connection.objects.get_or_create(identity=identity, backend=backend) connections.append(connection) _addto_autoreg(connections) _reload_whitelists() # time.sleep(2) return render_to_response('education/partials/addnumbers_row.html', {'object':connections, 'selectable':False}, RequestContext(request)) return render_to_response("education/partials/new_connection.html", {'form':form}, RequestContext(request)) @login_required def delete_connection(request, connection_id): connection = get_object_or_404(Connection, pk=connection_id) connection.delete() _reload_whitelists() return render_to_response("education/partials/connection_view.html", {'object':connection.contact }, context_instance=RequestContext(request)) @login_required def comments(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('Ministry Officials') or profile.is_member_of('UNICEF Officials'): comments = [(r.get_commentable_display(), r.comment, r.user, r.get_reporting_period_display(), get_range_on_date(r.reporting_period, r) ) for r in ReportComment.objects.order_by('-report_date')] else: # DFO/DEO should get only information on their districts comments = [(r.get_commentable_display(), r.comment, r.user, r.get_reporting_period_display(), get_range_on_date(r.reporting_period, r)) for r in ReportComment.objects.filter(user__profile__location=profile.location).order_by('-report_date')] return render_to_response('education/partials/comments.html', {'data_set':comments}, RequestContext(req)) @login_required def new_comment(req): report_comment_form = ReportCommentForm(initial = {'user':req.user.pk}) if req.method == 'POST': report_comment_form = ReportCommentForm(req.POST) if report_comment_form.is_valid(): with reversion.create_revision(): report_comment_form.save() reversion.set_comment('wrote a comment') return HttpResponseRedirect(reverse('comments')) else: return render_to_response('education/partials/new_comment.html', {'form':report_comment_form}, RequestContext(req)) else: return render_to_response('education/partials/new_comment.html',{'form':report_comment_form}, RequestContext(req)) @login_required def edit_comment(req, report_comment_pk): report_comment = get_object_or_404(ReportComment, pk=report_comment_pk) report_comment_form = ReportCommentForm(instance=report_comment) if req.method == 'POST': report_comment_form = ReportCommentForm(instance=report_comment, data=req.POST) if report_comment_form.is_valid(): with reversion.create_revision(): report_comment_form.save() reversion.set_comment('edited comment') return HttpResponseRedirect(reverse('comments')) else: return render_to_response('education/partials/edit_comment.html', {'form':report_comment_form}, RequestContext(req)) else: return render_to_response('education/partials/edit_comment.html', {'form':report_comment_form}, RequestContext(req)) @login_required def delete_comment(req, report_comment_pk): report_comment = get_object_or_404(ReportComment, pk=report_comment_pk) if req.method == 'POST': with reversion.create_revision(): report_comment.delete() reversion.set_comment('deleted comment') return HttpResponse(status=200) @login_required def delete_reporter(request, reporter_pk): reporter = get_object_or_404(EmisReporter, pk=reporter_pk) reporter_name = reporter.name if request.method == 'POST': with reversion.create_revision(): reversion.set_comment('deleted %s'%reporter_name) reporter.delete() return HttpResponse(status=200) @login_required def edit_reporter(request, reporter_pk): reporter = get_object_or_404(EmisReporter, pk=reporter_pk) reporter_group_name = reporter.groups.all()[0].name if request.method == 'POST': reporter_form = EditReporterForm(instance=reporter,data=request.POST) if reporter_form.is_valid(): with reversion.create_revision(): reporter_form.save() reversion.set_comment('edited %s details' % reporter.name) saved_reporter_grp = EmisReporter.objects.get(pk=reporter_pk).groups.all()[0].name if reporter.default_connection and reporter.groups.count() > 0: # remove from other scripts # if reporter's groups remain the same. if reporter_group_name == saved_reporter_grp: pass else: ScriptProgress.objects.exclude(script__slug="edtrac_autoreg").filter(connection=reporter.default_connection).delete() _schedule_teacher_weekly_scripts(reporter.groups.all()[0], reporter.default_connection, ['Teachers']) _schedule_weekly_scripts(reporter.groups.all()[0], reporter.default_connection, ['Head Teachers', 'SMC']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_head_teachers_monthly', 'last', ['Head Teachers']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_gem_monthly', 20, ['GEM']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_smc_monthly', 5, ['SMC']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_smc_termly', ['SMC']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_p3_enrollment_headteacher_termly', ['Head Teachers']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_p6_enrollment_headteacher_termly', ['Head Teachers']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_teacher_deployment_headteacher_termly', ['Head Teachers']) return redirect("reporter-detail", pk=reporter.pk) else: if reporter.schools.exists(): reporter_form = EditReporterForm(instance=reporter, initial={'schools':reporter.schools.all()[0]}) else: reporter_form = EditReporterForm(instance=reporter) return render_to_response('education/edit_reporter.html', {'reporter_form': reporter_form, 'reporter': reporter}, context_instance=RequestContext(request)) @login_required def add_schools(request): if request.method == 'POST': form = SchoolForm(request.POST) schools = [] if form.is_valid(): names = filter(None, request.POST.getlist('name')) locations = request.POST.getlist('location') if len(names) > 0: for i, name in enumerate(names): location = Location.objects.get(pk=int(locations[i])) name, created = School.objects.get_or_create(name=name, location=location) schools.append(name) return render_to_response('education/partials/addschools_row.html', {'object':schools, 'selectable':False}, RequestContext(request)) else: form = SchoolForm() return render_to_response('education/deo/add_schools.html', {'form': form, }, context_instance=RequestContext(request)) @login_required def delete_school(request, school_pk): school = get_object_or_404(School, pk=school_pk) school_name = school.name if request.method == 'POST': with reversion.create_revision(): school.delete() reversion.set_comment("%s deleted %s"%(request.user.username, school_name)) return HttpResponse(status=200) @login_required def edit_school(request, school_pk): school = get_object_or_404(School, pk=school_pk) school_form = SchoolForm(instance=school) school_name = school.name if request.method == 'POST': school_form = SchoolForm(instance=school, data=request.POST) if school_form.is_valid(): with reversion.create_revision(): school_form.save() reversion.set_comment('edited %s' % school_name) else: return render_to_response('education/partials/edit_school.html' , {'school_form': school_form, 'school' : school}, context_instance=RequestContext(request)) return render_to_response('/education/partials/school_row.html', {'object':School.objects.get(pk=school_pk), 'selectable':True}, context_instance=RequestContext(request)) else: return render_to_response('education/partials/edit_school.html', {'school_form': school_form, 'school': school}, context_instance=RequestContext(request)) @login_required def school_detail(request, school_id): school = School.objects.get(id=school_id) today = date.today() month_ranges = get_month_day_range(today, depth=today.month) month_ranges.reverse() slug_list = ['girlsp3', 'boysp3', 'girlsp6', 'boysp6'] slug_list_tr = ['f_teachers', 'm_teachers'] monthly_data = [] monthly_data_teachers = [] monthly_data_head_teachers = [] monthly_data_violence = [] monthly_data_meals = [] for month_range in month_ranges: monthly_data.append( [return_absent_month( 'edtrac_'+ '%s'%slug + '_attendance', 'edtrac_'+ '%s'%slug + '_enrollment', month_range = month_range, school = school) for slug in slug_list]) monthly_data_teachers.append( [return_absent_month( 'edtrac_'+'%s'%slug + '_attendance', 'edtrac_'+'%s'%slug + '_deployment', month_range = month_range, school=school) for slug in slug_list_tr]) reporters = [] reps = school.emisreporter_set.values() for rep in reps: r = EmisReporter.objects.get(id=rep['id']) reporters.append(r) boys_p3_enrolled = poll_responses_term('edtrac_boysp3_enrollment', belongs_to='schools', school = school) boys_p6_enrolled = poll_responses_term('edtrac_boysp6_enrollment', belongs_to='schools', school = school) girls_p3_enrolled = poll_responses_term('edtrac_girlsp3_enrollment', belongs_to='schools', school = school) girls_p6_enrolled = poll_responses_term('edtrac_girlsp6_enrollment', belongs_to='schools', school = school) m_teachers_deployed = poll_responses_term('edtrac_m_teachers_deployment', belongs_to = 'schools', school = school) f_teachers_deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to = 'schools', school = school) return render_to_response("education/school_detail.html", {\ 'school_name': school.name, 'months' : [d_start for d_start, d_end in month_ranges], 'monthly_data' : monthly_data, 'monthly_data_teachers' : monthly_data_teachers, 'monthly_data_head_teachers': monthly_data_head_teachers, 'monthly_data_violence' : monthly_data_violence, 'monthly_data_meals' : monthly_data_meals, 'reporters' : reporters, 'boys_p3_enrolled': boys_p3_enrolled, 'boys_p6_enrolled': boys_p6_enrolled, 'girls_p3_enrolled' : girls_p3_enrolled, 'girls_p6_enrolled' : girls_p6_enrolled, 'm_teachers_deployed': m_teachers_deployed, 'f_teachers_deployed': f_teachers_deployed }, RequestContext(request)) # analytics specific for emis {copy, but adjust to suit your needs} @login_required def to_excel(request, start_date=None, end_date=None, district_id=None): return create_excel_dataset(request, start_date, end_date, district_id) @login_required def school_reporters_to_excel(req): book = xlwt.Workbook() all_schools = School.objects.all() sheet = book.add_sheet('School Reporters') headings = ['School', 'Reporters'] rowx = 0 for colx, value in enumerate(headings): sheet.write(rowx, colx, value) sheet.set_panes_frozen(True) sheet.set_horz_split_pos(rowx+1) sheet.set_remove_splits(True) for row in all_schools: rowx += 1 for colx, value in enumerate([row.name, ', '.join([reporter.name for reporter in row.emisreporter_set.all()])]): sheet.write(rowx, colx, value) response = HttpResponse(mimetype="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment; filename=school_reporters_data.xls' book.save(response) return response @login_required def system_report(req=None): book = xlwt.Workbook() school_dates = [ getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END'), ] first_date = school_dates[0] last_date = school_dates[1] date_bunches = [] while first_date <= last_date: tmp = get_day_range(first_date) first_date = tmp[0] date_bunches.append(get_day_range(first_date)) first_date = dateutils.increment(first_date, weeks=1) profile = req.user.get_profile() enrolled_answered = \ EnrolledDeployedQuestionsAnswered.objects.select_related() headings = ['School'] + [d.strftime("%d/%m/%Y") for d, _ in date_bunches] if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): district_names = enrolled_answered.values_list( 'school__location__name', flat=True ).distinct() else: location = profile.location district_names = [location.name] district_schools = {} for dn in district_names: district_schools[dn] = School.objects.select_related().filter( pk__in=enrolled_answered.filter( school__location__name=dn ).values_list('school__pk', flat=True)).order_by('name') polls = Poll.objects.select_related().filter( Q(name__icontains="boys") | Q(name__icontains="girls") | Q(name='edtrac_f_teachers_attendance') | Q(name='edtrac_m_teachers_attendance') ) for district_name in district_schools.keys(): container = [] sheet = book.add_sheet(district_name, cell_overwrite_ok=True) rowx = 0 for colx, val_headings in enumerate(headings): sheet.write(rowx, colx, val_headings) sheet.set_panes_frozen(True) # in general, freeze after last heading row sheet.set_horz_split_pos(rowx + 1) # if user does unfreeze, don't leave a split there sheet.set_remove_splits(True) for school in district_schools[district_name]: school_vals = [school.name] for d_bunch in date_bunches: submission_count = 0 for poll in polls: submission_count += poll.responses.filter( contact__in=school.emisreporter_set.values_list( 'connection__contact'), date__range = d_bunch ).count() school_vals.extend([submission_count]) container.append(school_vals) for row in container: rowx += 1 for colx, value in enumerate(row): sheet.write(rowx, colx, value) response = HttpResponse(mimetype="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment; filename=SystemReport.xls' book.save(response) return response @login_required def excel_reports(req): return render_to_response('education/excelreports/excel_dashboard.html',{},RequestContext(req)) @login_required def edit_user(request, user_pk=None): title="" user=User() if request.method == 'POST' and request.user.get_profile().role_id == Role.objects.get(name = 'Admins').id: if user_pk: user = get_object_or_404(User, pk=user_pk) user_form = UserForm(request.POST,instance=user,edit=True) if user_form.is_valid(): with reversion.create_revision(): user = user_form.save() if user.groups.count() == 0: group = Group.objects.get(pk=user_form.cleaned_data['groups'][0].pk) user.groups.add(group) try: profile=UserProfile.objects.get(user=user) profile.location=user_form.cleaned_data['location'] profile.role=Role.objects.get(name=user_form.cleaned_data['groups'][0].name) profile.save() except UserProfile.DoesNotExist: UserProfile.objects.create(name=user.first_name,user=user,role=Role.objects.get(pk=user_form.cleaned_data['groups'][0].pk),location=user_form.cleaned_data['location']) reversion.set_comment("edited %s's profile" % user.username) return HttpResponseRedirect(reverse("emis-users")) elif user_pk: user = get_object_or_404(User, pk=user_pk) user_form = UserForm(instance=user,edit=True) title="Editing "+user.username else: user_form = UserForm(instance=user) return render_to_response('education/partials/edit_user.html', {'user_form': user_form,'title':title}, context_instance=RequestContext(request)) def htattendance(request, start_date=None, end_date=None, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) smc_htpresent = Poll.objects.get(name='emis_absence').responses.exclude(has_errors=True)\ .filter(date__range=(dates.get('start'), dates.get('end')))\ .filter(message__connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all())\ .order_by('message__date') return generic(request, model = Poll, queryset = smc_htpresent, objects_per_page = 50, results_title = 'Head Teacher Presence as Reported by SMCs', columns = [ ('school', False, 'school', None), ('present', False, 'present', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/ht_attendance_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timeslider_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) def gem_htattendance(request, start_date=None, end_date=None, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) gem_htpresent = XFormSubmission.objects.filter(xform__keyword='gemteachers').exclude(has_errors=True)\ .filter(created__range=(dates.get('start'), dates.get('end')))\ .filter(connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all())\ .order_by('created') return generic(request, model = XFormSubmission, queryset = gem_htpresent, objects_per_page = 50, results_title = 'Head Teacher Presence as Reported by GEM', columns = [ ('school', False, 'school', None), ('present', False, 'present', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/gemht_attendance_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timesli`der_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) def meals(request, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) meals = Poll.objects.get(name='emis_meals').responses.exclude(has_errors=True)\ .filter(date__range=(dates.get('start'), dates.get('end')))\ .filter(message__connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all()) return generic(request, model = Poll, queryset = meals, objects_per_page = 50, results_title = 'Pupils who had Meals at School', columns = [ ('school', False, 'school', None), ('estimated number', False, 'number', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/meals_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timeslider_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) @super_user_required def edit_scripts(request): forms = [] for script in Script.objects.exclude(name='Special Script').order_by('slug'): forms.append((script, ScriptsForm(instance=script))) if request.method == 'POST': script_form = ScriptsForm(request.POST,instance=Script.objects.get(slug=request.POST.get('slug'))) if script_form.is_valid(): script_form.save() return render_to_response('education/partials/edit_script.html', {'forms': forms, 'management_for': 'scripts'}, context_instance=RequestContext(request)) def emis_scripts_special(req): scripts = Script.objects.exclude(slug__icontains='weekly').exclude(name='Special Script').exclude(slug='edtrac_autoreg').order_by('slug') if req.method == 'POST': checked_numbers = req.POST.getlist('checked_numbers') checked_numbers = [n for n in checked_numbers if re.match(r'\d+', n)] poll_questions = req.POST.getlist('poll_questions') poll_scripts = [pq.split('-') for pq in poll_questions] #(poll_id, script_slug) d = datetime.datetime.now() _script = Script.objects.create(slug=\ "edtrac_%s %s %s %s:%s:%s"%(d.year,d.month,d.day,d.hour, d.minute, d.second), name="Special Script") _poll_scripts = [] # make sure that the poll/script to sent to just one group not a mixture of groups. reporter_group_name = EmisReporter.objects.get(id=checked_numbers[0]).groups.all()[0].name.lower().replace(' ', '_') for id, script_slug in poll_scripts: if re.search(reporter_group_name, script_slug): _poll_scripts.append((id, script_slug)) for i, li in enumerate(_poll_scripts): poll_id, script_slug = li _script.steps.add(ScriptStep.objects.create( script = _script, poll = Poll.objects.get(id = poll_id), order = i, # using index for different order??? rule = ScriptStep.RESEND_MOVEON, num_tries = 1, start_offset = 60, retry_offset = 86400, giveup_offset = 86400, )) _script.save() if len(checked_numbers) < 25 and len(checked_numbers) > 0: # assuming that "all" is not checked for reporter in EmisReporter.objects.filter(id__in=checked_numbers).exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() else: # what if the reporting location is different? Would you instead want to poll the different districts? single_reporter_location = True # flag reporter_location = EmisReporter.objects.filter(id__in=checked_numbers).\ exclude(reporting_location=None).values_list('reporting_location__name', flat=True) if reporter_location.count() > 0 and len(set(reporter_location)) > 1: single_reporter_location = False reporter_location = EmisReporter.objects.filter(reporting_location__type = 'district').\ values_list('reporting_location__name',flat=True) else: reporter_location = EmisReporter.objects.filter(reporting_location__type='district').\ filter(reporting_location__name = reporter_location[0]).values_list('reporting_location__name',flat=True) single_school = True reporter_schools = EmisReporter.objects.filter(id__in=checked_numbers).\ exclude(schools=None).values_list('schools__name', flat=True) if reporter_schools.count() > 0 and len(set(reporter_schools)) > 1: single_school = False reporter_schools = EmisReporter.objects.values_list('schools__name',flat=True) else: reporter_schools = EmisReporter.objects.filter(schools__name=reporter_schools[0]).values_list( 'schools__name', flat=True ) if single_reporter_location or single_school: for reporter in EmisReporter.objects.filter(schools__name__in=reporter_schools, reporting_location__name__in = reporter_location, groups__name =\ ' '.join([i.capitalize() for i in reporter_group_name.replace('_',' ').split()])).\ exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() else: for reporter in EmisReporter.objects.filter(groups__name =\ ' '.join([i.capitalize() for i in reporter_group_name.replace('_',' ').split()])).exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() return HttpResponseRedirect(reverse('emis-contact')) else: return render_to_response('education/partials/reporters/special_scripts.html',{'scripts':scripts}, RequestContext(req)) def reschedule_scripts(request, script_slug): grp = get_script_grp(script_slug) if script_slug.endswith('_weekly'): reschedule_weekly_polls(grp) elif script_slug.endswith('_monthly'): reschedule_monthly_polls(grp) else: if request.POST.has_key('date'): date = request.POST.get('date') else: date = None reschedule_termly_polls(grp, date) new_scripts = ScriptProgress.objects.filter(script__slug=script_slug) if new_scripts: new_script_date = new_scripts[0].time response = HttpResponse("This Script has been rescheduled to: %s " % new_script_date.strftime("%d-%m-%Y %H:%M")) return response else: return HttpResponse("This script can't be rescheduled. Try again") class EdtracReporter(ListView): model = EmisReporter template_name = "education/emisreporter_list.html" context_object_name = "reporter_list" ########## Maps ################# def attendance_visualization(req): return render_to_response( 'education/partials/map_attendance.html', { 'geoserver_url':getattr(settings, 'GEOSERVER_URL', 'http://localhost/geoserver') }, context_instance = RequestContext(req)) class AbsenteeismForm(forms.Form): error_css_class = 'error' select_choices = [('all', '--'), ('P3Boys', 'P3 Boys'), ('P3Girls', 'P3 Girls'), ('P3Pupils', 'P3 Pupils'), ('P6Boys', 'P6 Boys'), ('P6Girls', 'P6 Girls'), ('P6Pupils', 'P6 Pupils'), ('MaleTeachers', 'Male Teachers'), ('FemaleTeachers', 'Female Teachers'), ('Teachers', 'Teachers'), ('MaleHeadTeachers', 'Male Head Teachers'), ('FemaleHeadTeachers', 'Female Head Teachers'), ('HeadTeachers', 'Head Teachers'), ] from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) indicator = forms.ChoiceField(choices=select_choices, required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: if is_empty(data.get('indicator')): raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data @login_required def detail_attd(request, district=None): locations = get_location_for_absenteeism_view(district, request) time_range_depth = 4 if request.method == 'POST': absenteeism_form = AbsenteeismForm(data=request.POST) if absenteeism_form.is_valid(): indicator = absenteeism_form.cleaned_data['indicator'] week_range = get_date_range(absenteeism_form.cleaned_data['from_date'], absenteeism_form.cleaned_data['to_date'], time_range_depth) else: return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form}, RequestContext(request)) else: absenteeism_form = AbsenteeismForm(initial={'indicator': 'all'}) week_range = get_week_date(time_range_depth) indicator = "all" week_range.reverse() config_list = get_polls_for_keyword(indicator) collective_result, time_data, reporting_school_percent = get_aggregated_report(locations, config_list, week_range) weeks = ["%s - %s" % (i[0].strftime("%m/%d/%Y"), i[1].strftime("%m/%d/%Y")) for i in week_range] return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form, 'collective_result_keys': [config['collective_dict_key'] for config in config_list], 'collective_result': collective_result, 'time_data': mark_safe(json.dumps(time_data)), 'school_percent' : reporting_school_percent, 'weeks': mark_safe(json.dumps(weeks)), "locations": locations}, RequestContext(request)) @login_required def detail_dashboard(request, district=None): locations = get_location_for_absenteeism_view(district, request) time_range_depth = 4 if request.method == 'POST': absenteeism_form = AbsenteeismForm(data=request.POST) if absenteeism_form.is_valid(): indicator = absenteeism_form.cleaned_data['indicator'] week_range = get_date_range(absenteeism_form.cleaned_data['from_date'], absenteeism_form.cleaned_data['to_date'], time_range_depth) else: return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form}, RequestContext(request)) else: absenteeism_form = AbsenteeismForm(initial={'indicator': 'all'}) week_range = get_week_date(time_range_depth) indicator = "all" week_range.reverse() config_list = get_polls_for_keyword(indicator) collective_result, time_data, reporting_school_percent = get_aggregated_report(locations, config_list, week_range) weeks = ["%s - %s" % (i[0].strftime("%m/%d/%Y"), i[1].strftime("%m/%d/%Y")) for i in week_range] return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form, 'collective_result_keys': [config['collective_dict_key'] for config in config_list], 'collective_result': collective_result, 'time_data': mark_safe(json.dumps(time_data)), 'school_percent' : reporting_school_percent, 'weeks': mark_safe(json.dumps(weeks)), "locations": locations}, RequestContext(request)) @login_required def detail_attd_school(request, location): name = request.GET['school'] school_id = School.objects.get(name=name, location__name=location).id return redirect(reverse('school-detail',args=(school_id,))) class ExportPollForm(forms.Form): error_css_class = 'error' select_choices = list(Poll.objects.values_list(*['pk','name'])) from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) poll_name = forms.ChoiceField(choices=select_choices, required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: if is_empty(data.get('poll_name')): raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data def get_district_parent(reporting_location): parent_locations = reporting_location.get_ancestors() district_parent = [parent for parent in parent_locations if parent.type.name == 'district'] return district_parent[0].name def _format_responses(responses): a = [] for response in responses: if response.contact: contact = response.contact sender = contact location_type = contact.reporting_location.type reporting_location = contact.reporting_location.name if not location_type.name == 'district' and not location_type.name == 'country': reporting_location = get_district_parent(contact.reporting_location) location_type = 'district' school = ", ".join(contact.emisreporter.schools.values_list('name', flat=True)) else: sender = response.message.connection.identity location_type = "--" reporting_location = "--" school = "--" date = response.message.date if response.poll.type == "t": value = response.eav.poll_text_value elif response.poll.type == "n": if hasattr(response.eav, 'poll_number_value'): value = response.eav.poll_number_value else: value = 0 elif response.poll.type == 'l': value = response.eav.poll_location_value.name category = response.categories.values_list('category__name',flat=True) if len(category) == 0: category = "--" else: category = ", ".join(category) a.append((sender,location_type,reporting_location,school,date,value,category)) return a def _get_identity(r): return r.default_connection.identity if r.default_connection else "--" def _format_reporters(reporters): return [[r.id,r.name, _get_identity(r),r.reporting_location.type.name, r.reporting_location.name, ", ".join(r.schools.values_list('name', flat=True))] for r in reporters] @login_required def edtrac_export_poll_responses(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': form = ExportPollForm() else: form = ExportPollForm(data=request.POST) if form.is_valid(): poll = get_object_or_404(Poll, pk=form.cleaned_data['poll_name']) responses = poll.responses.all().order_by('-pk') to_date = form.cleaned_data['to_date'] from_date = form.cleaned_data['from_date'] if from_date and to_date: responses = responses.filter(date__range=[from_date, to_date]) resp = render_to_response( 'education/admin/export_poll_responses.csv', { 'responses': _format_responses(responses) }, mimetype='text/csv', context_instance=RequestContext(request) ) resp['Content-Disposition'] = 'attachment;filename="%s.csv"' \ % poll.name return resp return render_to_response('education/admin/export_poll_responses.html', {'form': form}, RequestContext(request), ) @login_required def edit_sub_county_reporters(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': sub_county_reporters = EmisReporter.objects.filter(reporting_location__type = 'sub_county') return render_to_response('education/admin/edit_sub_county_reporters.html', {'reporters':sub_county_reporters},RequestContext(request)) @login_required def export_sub_county_reporters(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': sub_county_reporters = EmisReporter.objects.filter(reporting_location__type='sub_county') resp = render_to_response('education/admin/export_sub_county_reporters.csv', {'responses': _format_reporters(sub_county_reporters)}, mimetype='text/csv', context_instance=RequestContext(request)) resp['Content-Disposition'] = 'attachment;filename="sub_county_reporters.csv"' return resp class ExportMessageForm(forms.Form): error_css_class = 'error' from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data def _get_school(m): if m.connection.contact.emisreporter.schools.all().exists(): return m.connection.contact.emisreporter.schools.all()[0] return None def _format_messages(messages): return[ [m ,m.connection.contact.reporting_location,_get_school(m),m.connection.contact,m.connection,m.date ] for m in messages] @login_required def edtrac_export_error_messages(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': form = ExportMessageForm() else: form = ExportMessageForm(data=request.POST) if form.is_valid(): messages = Message.objects.exclude( connection__identity__in = getattr(settings, 'MODEM_NUMBERS') ).filter(direction='I', connection__contact__emisreporter__reporting_location__in =\ locations.get(name__iexact="Uganda").get_descendants(include_self=True).all() ) messages= messages.filter(poll_responses=None) | messages.filter(poll_responses__has_errors=True) to_date = form.cleaned_data['to_date'] from_date = form.cleaned_data['from_date'] if from_date and to_date: messages = messages.filter(date__range=[from_date, to_date]) resp = render_to_response('education/admin/export_error_messages.csv', {'messages' : _format_messages(messages)}, mimetype='text/csv', context_instance=RequestContext(request)) resp['Content-Disposition'] = 'attachment;filename="error_messages.csv"'\ return resp return render_to_response('education/admin/export_error_messages.html', {'form':form},RequestContext(request)) def get_schools(request): location = request.GET['location'] list_of_schools = [{'text':'--------------','value':''}] if not is_empty(location): filtered_schools = School.objects.filter(location=Location.objects.get(pk=location,type__slug='district')) location_schools = [{'text':school.name,'value':school.pk} for school in filtered_schools] list_of_schools.extend(location_schools) return HttpResponse(json.dumps(list_of_schools)) Default the cache timeout to whatever appears in the settings.py file. from __future__ import division from urllib2 import urlopen import re import operator import copy import json from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render_to_response, redirect from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import DetailView, TemplateView, ListView from django.views.decorators.vary import vary_on_cookie from django.db.models import Q from django.core.cache import cache import xlwt from django.utils.safestring import mark_safe from education.curriculum_progress_helper import get_target_value, get_location_for_curriculum_view, get_curriculum_data, target from rapidsms_httprouter.models import Message from .forms import * from .models import * from uganda_common.utils import * from rapidsms.contrib.locations.models import Location from generic.views import generic from generic.sorters import SimpleSorter from poll.models import Poll, ResponseCategory from script.models import ScriptStep, Script from .reports import * from .utils import * from .utils import _schedule_monthly_script, _schedule_termly_script, _schedule_weekly_scripts, _schedule_teacher_weekly_scripts import reversion from reversion.models import Revision from unregister.models import Blacklist from .utils import themes from education.absenteeism_view_helper import * import datetime from datetime import date from education.view_helper import * from education.view_helper_utils import * Num_REG = re.compile('\d+') super_user_required = \ user_passes_test(lambda u: u.groups.filter( name__in=['Admins', 'DFO', 'UNICEF Officials']).exists() or u.is_superuser) @login_required def index(request, **kwargs): """ kwargs is where we list the variables that can be passed as our context use as follows: index(request, context_vars={'some_model_queryset'=Model.objects.all}) """ if not kwargs: return render_to_response("education/index.html", {}, RequestContext(request)) else: #When choosing to use kwargs, don't forget to include template and context_var variables # if you don't need a template or just need the original template, use template_name=None context_vars = kwargs.get('context_vars') template_name = kwargs['template_name'] if not template_name: #if no template name is given t = "education/index.html" else: t = "education/%s" % template_name return render_to_response(t, context_vars, RequestContext(request)) #MAPS @login_required def dash_map(request): return render_to_response('education/dashboard/map.html', {}, RequestContext(request)) def dash_ministry_map(request): return render_to_response('education/dashboard/map.html', {}, RequestContext(request)) def dash_attdance(request): boysp3_attendance = get_responses_to_polls(poll_name='edtrac_boysp3_attendance') boysp3_enrolled = get_responses_to_polls(poll_name="edtrac_boysp3_enrollment") boysp3_absent = boysp3_enrolled - boysp3_attendance girlsp3_attendance = get_responses_to_polls(poll_name="edtrac_girlsp3_attendance") girlsp3_enrolled = get_responses_to_polls(poll_name="edtrac_girlsp3_enrollment") girlsp3_absent = girlsp3_enrolled - girlsp3_attendance boysp6_attendance = get_responses_to_polls(poll_name="edtrac_boysp6_attendance") boysp6_enrolled = get_responses_to_polls(poll_name="edtrac_boysp6_enrollment") boysp6_absent = boysp6_enrolled - boysp6_attendance girlsp6_attendance = get_responses_to_polls(poll_name="edtrac_girlsp6_attendance") girlsp6_enrolled = get_responses_to_polls(poll_name="edtrac_girlsp6_enrollment") girlsp6_absent = girlsp6_enrolled - girlsp6_attendance total_male_teachers = get_responses_to_polls(poll_name="edtrac_m_teachers_deployment") total_female_teachers = get_responses_to_polls(poll_name="edtrac_f_teachers_deployment") male_teachers_present = get_responses_to_polls(poll_name="edtrac_m_teachers_attendance") male_teachers_absent = total_male_teachers - male_teachers_present female_teachers_present = get_responses_to_polls(poll_name="edtrac_f_teachers_attendance") female_teachers_absent = total_female_teachers - female_teachers_present return render_to_response('education/dashboard/attdance.html', { 'girlsp3_present' : girlsp3_attendance, 'girlsp3_absent' : girlsp3_absent, 'boysp3_present' : boysp3_attendance, 'boysp3_absent' : boysp3_absent, 'girlsp6_present' : girlsp6_attendance, 'girlsp6_absent' : girlsp6_absent, 'boysp6_present' : boysp6_attendance, 'boysp6_absent' : boysp6_absent, 'female_teachers_present' : female_teachers_present, 'female_teachers_absent' : female_teachers_absent, 'male_teachers_present' : male_teachers_present, 'male_teachers_absent' : male_teachers_absent } , RequestContext(request)) def get_mode_progress(mode): try: mode_progress = (100 * sorted(target.values()).index(mode) + 1) / float(len(target.keys())) # offset zero-based index by 1 except ValueError: mode_progress = 0 # when no values are recorded return mode_progress def get_progress_color(current_mode, target_value): on_schedule = 'green' behind_schedule = 'red' if current_mode < target_value: return behind_schedule return on_schedule def get_weeks_in_term(): term_start= getattr(settings,'SCHOOL_TERM_START') first_term_start= getattr(settings,'FIRST_TERM_BEGINS') second_term_start= getattr(settings,'SECOND_TERM_BEGINS') third_term_start= getattr(settings,'THIRD_TERM_BEGINS') weeks = [] for term_starts in [first_term_start, second_term_start, third_term_start]: if term_start == term_starts: weeks.extend(get_weeks(get_week_date()[1],depth=get_week_count(get_week_date()[0],term_starts))) break weeks.extend(get_weeks(dateutils.increment(term_starts, weeks=12),depth=12)) return weeks def format_week(week,sep): day1 = week[0].strftime("%d"+sep+"%b"+sep+"%Y") day2 = week[1].strftime("%d"+sep+"%b"+sep+"%Y") formated_week = "%s to %s" % (day1 , day2) return formated_week def _get_formated_date_choice(week): if week[0] < datetime.datetime.today() < week[1]: return format_week(week, ","), "current week( %s )" % format_week(week, "-") return format_week(week, ","), format_week(week, "-") class CurriculumForm(forms.Form): error_css_class = 'error' SELECT_CHOICES = [_get_formated_date_choice(week) for week in get_weeks_in_term()] choose_week_to_view = forms.ChoiceField(choices=SELECT_CHOICES, required=False) class ReporterDetailView(DetailView): model = EmisReporter def format_to_datetime_object(week_as_string): day1 = week_as_string.split()[0] day2 = week_as_string.split()[2] day_one = datetime.datetime.strptime(day1,"%d,%b,%Y") day_two = datetime.datetime.strptime(day2,"%d,%b,%Y") return [day_one,day_two] def get_modes_and_target(current_mode, target_value): target_progress = get_mode_progress(target_value) if len(current_mode) > 0 and isinstance(current_mode,list): max_mode = max([i[0] for i in current_mode]) mode_progress = get_mode_progress(max_mode) color = get_progress_color(max_mode, target_value) return color, mode_progress, target_progress mode_progress = 0 color = 'red' return color, mode_progress, target_progress def get_mode_if_exception_thrown(loc_data): if "Progress undetermined this week" in loc_data.values(): return "Progress undetermined this week" return "No Reports made this week" @login_required def curriculum_progress(request,district_pk=None): locations, user_location, sub_location_type,template_name = get_location_for_curriculum_view(district_pk, request) if request.method == 'POST': curriculum_form = CurriculumForm(data=request.POST) if curriculum_form.is_valid(): target_week = format_to_datetime_object(curriculum_form.cleaned_data['choose_week_to_view']) target_date = target_week[0] else: return render_to_response('education/progress/admin_progress_details.html', {'form': curriculum_form}, RequestContext(request)) else: target_week = get_week_date() curriculum_form = CurriculumForm(initial={'choose_week_to_view': format_week(target_week, ",")}) target_date = target_week[0] loc_data , valid_responses = get_curriculum_data(locations,target_week) try: current_mode = Statistics(valid_responses).mode except StatisticsException: current_mode = get_mode_if_exception_thrown(loc_data) target_value , term = get_target_value(target_date) if isinstance(current_mode,list) and len(current_mode) == 0: current_mode = "Progress undetermined this week" color, mode_progress, target_progress = get_modes_and_target(current_mode, target_value) return render_to_response(template_name, {'form': curriculum_form, 'location_data': loc_data, 'target': target_value, 'current_mode': current_mode, 'mode_progress': mode_progress, 'target_progress': target_progress, 'class_sent_from_behind': color, 'sub_location_type': sub_location_type, 'term': term}, RequestContext(request)) def dash_admin_meetings(req): profile = req.user.get_profile() location = profile.location p = Poll.objects.get(name = 'edtrac_smc_meetings') if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Ministry Officials'): meeting_stats = get_count_response_to_polls(p, #404 is shortcode for unknown choices = [0, 1, 2, 3, 404], # number of meetings with_percent = True, #percentage counted based on number of schools termly = True, admin=True) return render_to_response("education/admin/admin_meetings.html",{ 'meeting_basis': meeting_stats.get('correctly_answered'), 'titles':",".join(str(k) for k in meeting_stats.get('to_ret').keys()), 'meetings':",".join(str(v) for v in meeting_stats.get('to_ret').values()) }, RequestContext(req)) else: meeting_stats = get_count_response_to_polls(p, location_name = location.name, #404 is shortcode for unknown choices = [0, 1, 2, 3, 404], # number of meetings with_percent = True, #percentage counted based on number of schools termly = True, admin = False ) return render_to_response('education/admin/other_meetings.html', {'location_name':location.name, 'meeting_basis': meeting_stats.get('correctly_answered'), 'meetings':",".join(str(v) for v in meeting_stats.get('to_ret').values()), 'titles':",".join(str(k) for k in meeting_stats.get('to_ret').keys()), 'meeting_basis':meeting_stats.get('correctly_answered')}, RequestContext(req)) def preprocess_response(resp): """ reprocess the response values and return just one value """ if not resp: return '--' elif None in resp: return 'wrong response' else: return resp[0] # assumption only one SMC is attached to that school def dash_district_meetings(req, district_name): district = Location.objects.filter(type="district").get(name = district_name) p = Poll.objects.get(name = 'edtrac_smc_meetings') schools_data = EmisReporter.objects.exclude(connection__in = Blacklist.objects.values_list('connection')).\ filter(groups__name = 'SMC', reporting_location = district).exclude(schools = None).order_by('schools__name').\ values_list('schools__name','schools__id','connection__pk') school_container = {} for school_name, school_id, smc_connection in schools_data: school_container[(school_name, school_id)] = preprocess_response([r.eav.poll_number_value for r in p.responses.filter(contact__connection__pk = smc_connection, date__range =[getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END')] )]) #TODO -> sort the school container items return render_to_response( 'education/admin/district_meetings.html', {'location_name':district_name, 'meeting_count':school_container.items()}, RequestContext(req)) # Dashboard specific view functions @login_required @vary_on_cookie def dashboard(request): return admin_dashboard(request) def capitation_grants(locations): # capitation grants cg = Poll.objects.get(name="edtrac_upe_grant") yes_category = cg.categories.get(name='yes') yeses_cg = cg.responses.filter(contact__reporting_location__in=locations, categories__category=yes_category).values_list('contact').distinct().count() # percent of those that received grants head_teacher_count = EmisReporter.objects.exclude(schools=None, connection__in= \ Blacklist.objects.values_list('connection', flat=True)).filter(groups__name='Head Teachers', \ reporting_location__in=locations).count() try: grant_percent = (100 * yeses_cg) / head_teacher_count except ZeroDivisionError: grant_percent = 0 return {'grant_percent': grant_percent} def month_total(poll_name, locations): poll = Poll.objects.get(name=poll_name) return NumericResponsesFor(poll) \ .forLocations(locations) \ .forDateRange(get_month_day_range(datetime.datetime.now(), depth=1)[0]) \ .total() def violence_numbers_girls(locations): return {'violence_numbers_girls' : month_total('edtrac_violence_girls', locations)} def violence_numbers_boys(locations): return {'violence_numbers_boys' : month_total('edtrac_violence_boys', locations)} def violence_numbers_reported(locations): return {'violence_numbers_reported' : month_total('edtrac_violence_reported', locations)} def gendered_text_responses(date_weeks, locations, options, gender): poll = Poll.objects.get(name='edtrac_head_teachers_attendance') gendered_schools = EmisReporter.objects.filter(reporting_location__in = locations, gender = gender, groups__name = "Head Teachers") \ .exclude(schools = None) \ .values('reporting_location__id') result = Response.objects.filter(poll = poll, has_errors = False, message__direction = 'I', date__range = date_weeks, eav_values__value_text__in = options, contact__reporting_location__id__in = gendered_schools) \ .values('contact__reporting_location__id').count() return result or 0 def compute_percent(x,y): if y != 0: return (100 * x) / y else: return 0 def get_two_weeks_absenteeism(gender, locations, get_time): date_weeks = get_week_date(depth=2, get_time=get_time) if is_holiday(date_weeks[0][0], getattr(settings, 'SCHOOL_HOLIDAYS')) \ or is_holiday(date_weeks[1][0], getattr(settings, 'SCHOOL_HOLIDAYS')): return '--','--' else: poll = Poll.objects.get(name='edtrac_head_teachers_attendance') yesses_this_week = gendered_text_responses(date_weeks[0], locations, ['Yes', 'YES', 'yes'], gender) yesses_last_week = gendered_text_responses(date_weeks[1], locations, ['Yes', 'YES', 'yes'], gender) noes_this_week = gendered_text_responses(date_weeks[0], locations, ['No', 'NO', 'no'], gender) noes_last_week = gendered_text_responses(date_weeks[1], locations, ['No', 'NO', 'no'], gender) this_week_absent = compute_percent(noes_this_week, yesses_this_week + noes_this_week) past_week_absent = compute_percent(noes_last_week, yesses_last_week + noes_last_week) return this_week_absent, past_week_absent def p3_absent_boys(locations, get_time=datetime.datetime.now): """ Attendance of P3 Pupils; this gets the absenteeism """ boysp3, boysp3_past = compute_absenteeism_summary('P3Boys',locations,get_time=get_time) return {'boysp3' : boysp3, 'boysp3_past' : boysp3_past,} def p6_boys_absent(locations, get_time=datetime.datetime.now): boysp6, boysp6_past = compute_absenteeism_summary('P6Boys',locations,get_time=get_time) return {'boysp6' : boysp6, 'boysp6_past' : boysp6_past} def p3_absent_girls(locations, get_time=datetime.datetime.now): girlsp3 ,girlsp3_past = compute_absenteeism_summary('P3Girls',locations,get_time=get_time) return {'girlsp3' : girlsp3, 'girlsp3_past' : girlsp3_past} def p6_girls_absent(locations,get_time=datetime.datetime.now): girlsp6,girlsp6_past = compute_absenteeism_summary('P6Girls',locations,get_time=get_time) return {'girlsp6' : girlsp6, 'girlsp6_past' : girlsp6_past} def f_teachers_absent(locations, get_time=datetime.datetime.now): female_teachers ,female_teachers_past = compute_absenteeism_summary('FemaleTeachers',locations,get_time=get_time) return {'female_teachers' :female_teachers,'female_teachers_past' : female_teachers_past,} def m_teachers_absent(locations, get_time=datetime.datetime.now): male_teachers,male_teachers_past = compute_absenteeism_summary('MaleTeachers',locations, get_time=get_time) return {'male_teachers' : male_teachers, 'male_teachers_past' : male_teachers_past} def get_target_week(): for week in get_weeks_in_term(): if week[0] < datetime.datetime.today() < week[1]: return week def progress(stages, stage): numerator = stages.index(stage) + 1 denominator = len(stages) return 100 * numerator / denominator def p3_curriculum(locations): target_week = get_week_date() poll = Poll.objects.get(name='edtrac_p3curriculum_progress') mode = NumericResponsesFor(poll) \ .forDateRange(target_week) \ .forLocations(locations) \ .forValues(themes.keys()) \ .mode() if mode: return {'mode_progress' : progress(sorted(themes.keys()), mode), 'c_mode' : [[mode]]} else: return {'mode_progress' : 0, 'c_mode' : "Progress undetermined this week"} def meals_missed(locations, get_time): poll = Poll.objects.get(name = "edtrac_headteachers_meals") this_month = get_month_day_range(get_time()) schools_without_meals = NumericResponsesFor(poll) \ .forLocations(locations) \ .forDateRange(this_month) \ .excludeGreaterThan(0) \ .groupBySchools() return {'meals_missed' : len(schools_without_meals)} def head_teachers_female(locations, get_time=datetime.datetime.now): female_d1,female_d2 = get_two_weeks_absenteeism('F', locations, get_time) try: f_head_diff = female_d2 - female_d1 if f_head_diff < 0: f_head_t_class = "decrease" f_head_t_data = 'data-red' elif f_head_diff > 0: f_head_t_class = "increase" f_head_t_data = 'data-green' else: f_head_t_class = "zero" f_head_t_data = 'data-white' except: f_head_diff = '--' f_head_t_class = "zero" f_head_t_data = 'data-white' return {'f_head_t_week' : female_d1, 'f_head_t_week_before' : female_d2, 'f_head_diff' : f_head_diff, 'f_head_t_class' : f_head_t_class, 'f_head_t_data':f_head_t_data} def head_teachers_male(locations, get_time=datetime.datetime.now): male_d1, male_d2 = get_two_weeks_absenteeism('M', locations, get_time=get_time) try: m_head_diff = male_d2 - male_d1 if m_head_diff < 0: m_head_t_class = "decrease" m_head_t_data = 'data-red' elif m_head_diff > 0: m_head_t_class = "increase" m_head_t_data = 'data-green' else: m_head_t_class = "zero" m_head_t_data = 'data-white' except: m_head_diff = '--' m_head_t_class = "zero" m_head_t_data = 'data-white' return {'m_head_t_week' : male_d1, 'm_head_t_data':m_head_t_data, 'm_head_t_week_before' : male_d2, 'm_head_diff' : m_head_diff, 'm_head_t_class' : m_head_t_class} def schools_valid(locations, group_names, blacklisted): school_valid = EmisReporter.objects.filter( groups__name__in=group_names, reporting_location__in=locations ).exclude(connection__in=blacklisted).exclude(schools=None) \ .values('schools__id').distinct().count() return {'total_schools_valid': school_valid} def schools_active(locations): try: count_reps = EmisReporter.objects.filter(groups__name__in=['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'], reporting_location__in = locations).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None).count() count = 0 for p in Poll.objects.filter(name__icontains = 'attendance').select_related(): if len(locations) == 1: count += p.responses.filter( contact__reporting_location__in = locations, date__range = get_week_date(depth = 2)[0] ).distinct().select_related().count() else: count += p.responses.filter(date__range = get_week_date(depth=2)[0]).distinct().select_related().count() school_active = (100 * count) / count_reps except ZeroDivisionError: school_active = 0 return {'school_active': school_active} def smc_meetings(locations): # SMC meetings are count based school_to_date = School.objects.filter(pk__in=EmisReporter.objects.\ filter(reporting_location__name__in = [loc.name for loc in locations]).select_related().\ values_list('schools__pk', flat=True)).count() smc_meeting_poll = Poll.objects.get(name = 'edtrac_smc_meetings') meetings = NumericResponsesFor(smc_meeting_poll) \ .excludeZeros() \ .forDateRange([getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END')]) \ .forLocations(locations) \ .total() try: total_meetings = 100 * meetings / school_to_date except ZeroDivisionError: total_meetings = 0 return {'smc_meetings': total_meetings, 'schools_to_date': school_to_date} def total_reporters(locations, group_names, blacklisted): total_reporters = EmisReporter.objects.filter( groups__name__in=group_names, reporting_location__in=locations ).exclude( connection__in=blacklisted ).exclude( schools=None ).count() return {'total_reporters': total_reporters} # generate context vars def generate_dashboard_vars(location): """ An overly ambitious function that generates context variables for a location if provided This gets populated in the dashboard. """ context_vars = {} if location.name == "Uganda": # get locations from active districts only locations = Location.objects.filter(pk__in=EmisReporter.objects.\ values_list('reporting_location__pk', flat=True)).distinct() else: locations = [location] group_names = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] blacklisted = Blacklist.objects.all().values_list('connection', flat=True) # violence girls context_vars.update(violence_numbers_girls(locations)) #violence boys context_vars.update(violence_numbers_boys(locations)) #violence_reported context_vars.update(violence_numbers_reported(locations)) # capitations grants context_vars.update(capitation_grants(locations)) #active schools context_vars.update(schools_active(locations)) #valid schools context_vars.update(schools_valid(locations, group_names, blacklisted)) #SMC meetings context_vars.update(smc_meetings(locations)) #female head teachers that missed school context_vars.update(head_teachers_female(locations)) #male head teachers that missed school context_vars.update(head_teachers_male(locations)) # time stamps context_vars.update({'month':datetime.datetime.now()}) # progress context_vars.update(p3_curriculum(locations)) # Female teachers context_vars.update(f_teachers_absent(locations)) # P3 teachers male context_vars.update(m_teachers_absent(locations)) # P3 boys context_vars.update(p3_absent_boys(locations)) # P3 Girls context_vars.update(p3_absent_girls(locations)) # P6 Girls context_vars.update(p6_girls_absent(locations)) # P6 Boys context_vars.update(p6_boys_absent(locations)) #Meals context_vars.update(meals_missed(locations, get_time = datetime.datetime.now)) #Total Reporters context_vars.update(total_reporters(locations, group_names, blacklisted)) return context_vars # view generator def view_generator(req, enrol_deploy_poll=None, attendance_poll=None, title=None, url_name_district=None, url_name_school = 'school-detail', template_name='education/timeslider_base.html'): """ A generic function to create views based on time ranges. """ time_range_form = ResultForm() profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): # high level officials will access all districts locations = Location.objects.filter(type='district').filter(pk__in =\ EnrolledDeployedQuestionsAnswered.objects.values_list('school__location__pk',flat=True)) else: # other officials will access individual districts locations = [profile.location] if req.method == 'POST': time_range_form = ResultForm(data=req.POST) to_ret = [] if time_range_form.is_valid(): from_date = time_range_form.cleaned_data['from_date'] to_date = time_range_form.cleaned_data['to_date'] month_delta = abs(from_date.month - to_date.month) date_weeks = [] month_flag = None if month_delta <= 2: # same month get days in between month_flag = False # don't split data in months while from_date <= to_date: if from_date.weekday() == 3: #is to_day a Thursday? date_weeks.append(previous_calendar_week(t = from_date)) # get range from Wed to Thur. from_date += datetime.timedelta(days = 1) else: month_flag = True # split data in months while from_date <= to_date: date_weeks.append([dateutils.month_start(from_date),dateutils.month_end(dateutils.increment(from_date, months=1))]) next_date = dateutils.increment(from_date, months = 1) delta = next_date - from_date from_date += datetime.timedelta(days = abs(delta.days)) if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): schools_temp = School.objects.filter(pk__in = \ EnrolledDeployedQuestionsAnswered.objects.select_related().values_list('school__pk', flat=True)) for location in locations: temp = [] # get schools in this location location_schools = schools_temp.select_related().filter(location = location) # store in memory for d in date_weeks: total_attendance = 0 # per school total_enrollment = 0 # per school for school in location_schools: enrolled = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) if enrolled > 0: if month_flag: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'avg') # use averages else: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_enrollment += enrolled try: percentage = (total_enrollment - total_attendance) * 100 / total_enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) return render_to_response(template_name, {'form':time_range_form, 'dataset':to_ret, 'title': title,'month_flag': month_flag, 'url_name':url_name_district, 'date_batch':date_weeks}, RequestContext(req)) else: location_schools = School.objects.filter(pk__in = EnrolledDeployedQuestionsAnswered.objects.select_related().\ filter(school__location=locations[0]).values_list('school__pk', flat=True)).select_related() #Non admin types# for school in location_schools: for d in date_weeks: temp = [] enrollment = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) if month_flag: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'avg') else: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') try: percentage = (enrollment - attendance) * 100 / enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([school, temp]) return render_to_response(template_name, {'form':time_range_form, 'dataset_school':to_ret, 'title': title,'month_flag':month_flag, 'url_name': url_name_school, 'date_batch':date_weeks}, RequestContext(req)) else: return render_to_response(template_name, {'form':time_range_form, 'url_name':url_name_district, 'title':title}, RequestContext(req)) # NO POST data sent! else: date_weeks = [] date_weeks.append(previous_calendar_week(t = datetime.datetime.now())) sw = date_weeks[0][0] date_weeks.append(previous_calendar_week(t = dateutils.increment(datetime.datetime(sw.year, sw.month, sw.day, 10), weeks = -1))) location_data = [] schools_temp = School.objects.select_related().\ filter(pk__in =\ EnrolledDeployedQuestionsAnswered.objects.select_related().filter(school__location__in=locations).values_list('school__pk',flat=True)) context_vars = {} if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): for location in locations: temp = [] # get schools in this location location_schools = schools_temp.select_related().filter(location = location) for d in date_weeks: total_attendance = 0 # per school total_enrollment = 0 # per school for school in location_schools: enrolled = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_enrollment += enrolled try: percentage = (total_enrollment - total_attendance) * 100 / total_enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) try: diff = temp[0] - temp[1] except TypeError: diff = '--' location_data.append([location, temp[0], temp[1], diff]) context_vars.update({'location_data':location_data}) else: location_schools = School.objects.select_related().filter(pk__in = EnrolledDeployedQuestionsAnswered.objects.select_related().\ filter(school__location=locations[0]).values_list('school__pk', flat=True)) #Non admin types to_ret = [] for school in location_schools: enrollment = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) temp = [] for d in date_weeks: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') try: percentage = (enrollment - attendance) * 100 / enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([school, temp]) context_vars = {'form':time_range_form, 'dataset_school':to_ret, 'title': title, 'url_name': url_name_school, 'date_batch':date_weeks} if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): x = {'url_name':url_name_district, 'headings':['District', 'Current week', 'Previous week', 'Percentage difference']} else: x = {'url_name':url_name_school, 'headings':['School', 'Current week', 'Previous week', 'Percentage difference']} if context_vars.has_key('form') ==False and context_vars.has_key('title') == False: context_vars.update({'form':time_range_form,'title':title}) # add the keys to context_vars dict context_vars.update(x) return render_to_response(template_name, context_vars, RequestContext(req)) @login_required def admin_dashboard(request): if request.user.get_profile().is_member_of('Ministry Officials') or request.user.get_profile().is_member_of('Admins')\ or request.user.get_profile().is_member_of('UNICEF Officials'): location = Location.objects.get(name="Uganda") else: location = request.user.get_profile().location key = "context-vars-for-location-" + str(location.id) context_vars = cache.get(key) if not context_vars: context_vars = generate_dashboard_vars(location=location) cache.set(key, context_vars) return render_to_response("education/admin/admin_dashboard.html", context_vars, RequestContext(request)) class NationalStatistics(TemplateView): template_name = "education/admin/national_statistics.html" groups = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] def compute_percent(self, reps, groups = groups): all_reporters = EmisReporter.objects.filter(groups__name__in=groups).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None) try: reps.count() / all_reporters.count() except ZeroDivisionError: return 0 def get_context_data(self, **kwargs): context = super(NationalStatistics, self).get_context_data(**kwargs) groups = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] all_reporters = EmisReporter.objects.filter(groups__name__in=groups).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None) profile = self.request.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): districts = Location.objects.filter(type="district").\ filter(name__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in=Blacklist.objects.values_list('connection',flat=True)).values_list('reporting_location__name', flat=True)) reps = EmisReporter.objects.select_related().filter(groups__name__in=['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters'], connection__in=Message.objects.\ filter(date__range = get_week_date(depth = 2)[1]).values_list('connection', flat = True)).exclude(schools = None).exclude(connection__in = Blacklist.objects.values_list('connection', flat=True)) district_schools = [ (district, School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).\ filter(reporting_location__name = district.name).distinct().values_list('schools__pk',flat=True)).count()) for district in districts ] context['total_districts'] = districts.count() context['district_schools'] = district_schools schools= School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).\ exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).distinct().values_list('schools__pk',flat=True)) context['school_count'] = schools.count() total_schools = 0 for district in districts: s_count = School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).\ filter(reporting_location__name = district.name).distinct().values_list('schools__pk',flat=True)).count() total_schools += s_count context['total_schools'] = total_schools district_active = [ ( district, self.compute_percent(reps.filter(reporting_location__pk=district.pk), groups=['Head Teachers']) ) for district in districts ] district_active.sort(key=operator.itemgetter(1), reverse=True) context['district_active'] = district_active[:3] context['district_less_active'] = district_active[-3:] head_teacher_count = all_reporters.filter(groups__name='Head Teachers').count() smc_count = all_reporters.filter(groups__name = "SMC").count() p6_teacher_count = all_reporters.filter(groups__name = "Teachers", grade = "P6").count() p3_teacher_count = all_reporters.filter(groups__name = "Teachers", grade = "P3").count() total_teacher_count = all_reporters.filter(groups__name="Teachers").count() deo_count = all_reporters.filter(groups__name="DEO").count() gem_count = all_reporters.filter(groups__name="GEM").count() teacher_data_unclean = total_teacher_count - p3_teacher_count - p6_teacher_count context['head_teacher_count'] = head_teacher_count context['smc_count'] = smc_count context['p6_teacher_count'] = p6_teacher_count context['p3_teacher_count'] = p3_teacher_count context['total_teacher_count'] = total_teacher_count context['teacher_data_unclean'] = teacher_data_unclean context['deo_count'] = deo_count context['gem_count'] = gem_count context['all_reporters'] = all_reporters.count() context['expected_reporters'] = schools.count() * 4 # reporters that used EduTrac the past week active_school_reporters = all_reporters.filter(connection__in=Message.objects.exclude(application='script').\ filter(date__range = get_week_date(depth = 2)[1]).values_list('connection', flat = True)) school_active = [ (school, self.compute_percent(active_school_reporters.filter(schools__pk=school.pk), groups=['Head Teachers', 'Teachers', 'GEM', 'SMC','Other Reporters'])) for school in schools ] school_active.sort(key=operator.itemgetter(1), reverse=True) context['school_active_count'] = School.objects.filter(pk__in = active_school_reporters.values_list('schools__pk', flat=True)).count() context['school_active'] = school_active[:3] context['school_less_active'] = school_active[-3:] return context else: return self.render_to_response(dashboard(self.request)) def get_term_range(term): if term == 'first': return [getattr(settings,'FIRST_TERM_BEGINS'),dateutils.increment(getattr(settings,'FIRST_TERM_BEGINS'),weeks=12)] if term == 'second': return [getattr(settings,'SECOND_TERM_BEGINS'),dateutils.increment(getattr(settings,'SECOND_TERM_BEGINS'),weeks=12)] if term == 'third': return [getattr(settings,'THIRD_TERM_BEGINS'),dateutils.increment(getattr(settings,'THIRD_TERM_BEGINS'),weeks=12)] if term == '' or term =='current' or term is None: return [getattr(settings,'SCHOOL_TERM_START'),getattr(settings,'SCHOOL_TERM_END')] class CapitationGrants(TemplateView): poll_name ='' restrict_group='' def compute_percent(self, x, y): try: return (100 * x) / y except ZeroDivisionError: return 0 def _extract_info(self, list): to_ret = [] for item in list: to_ret.append( [item.get('category__name'), item.get('value')] ) final_ret = {} for li in to_ret: final_ret[li[0]] = li[1] total = sum(filter(None, final_ret.values())) for key in final_ret.keys(): final_ret[key] = self.compute_percent(final_ret.get(key), total) return final_ret def _get_per_category_responses_for_school(self, responses_by_category, school): info = [stat for stat in responses_by_category if stat['response__contact__emisreporter__schools__name'] == school.name] return school, self._extract_info(info).items() def _get_schools_info(self, responses_at_location,location): responses_by_category = responses_at_location.values( 'response__contact__emisreporter__schools__name', 'category__name').annotate(value=Count('pk')) schools = location.schools.all() return [self._get_per_category_responses_for_school(responses_by_category, school) for school in schools] def get_context_data(self, **kwargs): term = self.kwargs.get('term') term_range = get_term_range(term) context = super(CapitationGrants, self).get_context_data(**kwargs) cg = Poll.objects.select_related().get(name=self.poll_name) authorized_users = ['Admins', 'Ministry Officials', 'UNICEF Officials'] authorized_user = False for auth_user in authorized_users: if self.request.user.get_profile().is_member_of(auth_user): authorized_user = True break context['authorized_user'] = authorized_user er = EmisReporter.objects.select_related() unknown_unknowns = cg.responses.filter(~Q(message__text__iregex="i don('?)t know"), categories__category__name="unknown") if authorized_user: reporter_count = er.filter(groups__name=self.restrict_group).exclude(schools=None).count() all_responses = cg.responses_by_category().exclude(response__in=unknown_unknowns).filter(response__date__range=term_range) locs = Location.objects.filter( type="district", pk__in= \ er.exclude(connection__in=Blacklist.objects. \ values_list('connection', flat=True), schools=None).filter(groups__name=self.restrict_group). \ values_list('reporting_location__pk', flat=True)) districts_to_ret = [] for location in locs: info = self._extract_info(all_responses.filter(response__contact__reporting_location=location)) districts_to_ret.append((location, info.items())) total_responses = all_responses.values_list('response__contact').distinct().count() context['responses'] = self._extract_info(all_responses).items() context['location'] = Location.tree.root_nodes()[0] context['sub_locations'] = districts_to_ret context['sub_location_type'] = "district" else: location = self.request.user.get_profile().location all_responses = cg.responses_by_category().exclude(response__in=unknown_unknowns).filter(response__date__range=term_range) responses_at_location = all_responses.filter(response__contact__reporting_location=location) total_responses = responses_at_location.values_list('response__contact').distinct().count() reporter_count = er.exclude(schools=None, connection__in= \ Blacklist.objects.values_list('connection', flat=True)).filter(groups__name=self.restrict_group, \ reporting_location=location).count() context['responses'] = self._extract_info(responses_at_location).items() context['location'] = location context['sub_locations'] = self._get_schools_info(responses_at_location, location) context['sub_location_type'] = "school" context['reporter_count'] = self.compute_percent(total_responses, reporter_count) context['group'] = self.restrict_group return context # Details views... specified by ROLES def set_logged_in_users_location(profile): if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of( 'Admins'): location = Location.objects.get(name='Uganda') else: location = profile.location return location def violence_details_dash(req): profile = req.user.get_profile() context_vars = {} location = set_logged_in_users_location(profile) violence_cases_girls = poll_response_sum("edtrac_violence_girls", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_boys = poll_response_sum("edtrac_violence_boys", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_reported = poll_response_sum("edtrac_violence_reported", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_gem = poll_response_sum('edtrac_gem_abuse', location=location, month_filter='monthly', months=2, ret_type=list) girls_total = [] for name, list_val in violence_cases_girls: girls_total.append((list_val[0], list_val[1])) context_vars['violence_cases_girls'] = violence_cases_girls girls_first_col, girls_second_col = [],[] for first, second in girls_total: girls_first_col.append(first), girls_second_col.append(second) girls_first_col = [i for i in girls_first_col if i != '--'] girls_second_col = [i for i in girls_second_col if i != '--'] context_vars['girls_totals'] = [sum(girls_first_col), sum(girls_second_col)] boys_total = [] for name, list_val in violence_cases_boys: boys_total.append((list_val[0], list_val[1])) context_vars['violence_cases_boys'] = violence_cases_boys boys_first_col, boys_second_col = [],[] for first, second in boys_total: boys_first_col.append(first), boys_second_col.append(second) boys_first_col = [i for i in boys_first_col if i != '--'] boys_second_col = [i for i in boys_second_col if i != '--'] context_vars['boys_totals'] = [sum(boys_first_col), sum(boys_second_col)] reported_total = [] for name, list_val in violence_cases_reported: reported_total.append((list_val[0], list_val[1])) context_vars['violence_cases_reported'] = violence_cases_reported reported_first_col, reported_second_col = [],[] for first, second in reported_total: reported_first_col.append(first), reported_second_col.append(second) reported_first_col = [i for i in reported_first_col if i != '--'] reported_second_col = [i for i in reported_second_col if i != '--'] context_vars['reported_totals'] = [sum(reported_first_col), sum(reported_second_col)] gem_total = [] # total violence cases reported by school for name, list_val in violence_cases_gem: gem_total.append((list_val[0], list_val[1])) context_vars['violence_cases_reported_by_gem'] = violence_cases_gem first_col, second_col = [],[] for first, second in gem_total: first_col.append(first), second_col.append(second) first_col = [i for i in first_col if i != '--'] second_col = [i for i in second_col if i != '--'] context_vars['gem_totals'] = [sum(first_col), sum(second_col)] context_vars['report_dates'] = [start for start, end in get_month_day_range(datetime.datetime.now(), depth=2)] school_report_count = 0 gem_report_count = 0 for dr in get_month_day_range(datetime.datetime.now(), depth=2): if profile.location.type.name == 'country': contacts = Contact.objects.select_related().filter(reporting_location__in=profile.\ location.get_descendants().filter(type="district")) else: contacts = Contact.objects.select_related().filter(reporting_location=profile.location) school_resp_count = Poll.objects.select_related().get(name="edtrac_violence_girls").responses.filter( contact__in = contacts, date__range = dr).count() gem_resp_count = Poll.objects.select_related().get(name="edtrac_gem_abuse").responses.filter( contact__in = contacts, date__range = dr).count() school_report_count += school_resp_count gem_report_count += gem_resp_count try: context_vars['sch_reporting_percentage'] = 100 * ( school_report_count / (float(len(get_month_day_range(datetime.datetime.now(), depth=2))) * school_report_count)) except ZeroDivisionError: context_vars['sch_reporting_percentage'] = 0 try: context_vars['gem_reporting_percentage'] = 100 * ( gem_report_count / (float(len(get_month_day_range(datetime.datetime.now(), depth=2))) * gem_report_count)) except ZeroDivisionError: context_vars['gem_reporting_percentage'] = 0 now = datetime.datetime.now() month_ranges = get_month_day_range(now, depth=now.month) month_ranges.sort() h_teach_month = [] girls_violence_month = [] boys_violence_month =[] reported_violence_month = [] h_teach_data = [] gem_data = [] girls_violence_data = [] boys_violence_data = [] reported_violence_data = [] if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Admins'): for month_range in month_ranges: h_teach_month.append(month_range[0].strftime('%B')) h_teach_data.append(get_numeric_report_data('edtrac_violence_girls',time_range=month_range, to_ret = 'sum')) gem_data.append(get_numeric_report_data('edtrac_gem_abuse',time_range=month_range, to_ret = 'sum')) girls_violence_month.append(month_range[0].strftime('%B')) girls_violence_data.append(get_numeric_report_data('edtrac_violence_girls', time_range=month_range, to_ret='sum')) boys_violence_month.append(month_range[0].strftime('%B')) boys_violence_data.append(get_numeric_report_data('edtrac_violence_boys', time_range=month_range, to_ret='sum')) reported_violence_month.append(month_range[0].strftime('%B')) reported_violence_data.append(get_numeric_report_data('edtrac_violence_reported', time_range=month_range, to_ret='sum')) else: for month_range in month_ranges: h_teach_month.append(month_range[0].strftime('%B')) h_teach_data.append(get_numeric_report_data('edtrac_girls_violence',time_range=month_range, to_ret = 'sum', location=profile.location)) gem_data.append(get_numeric_report_data('edtrac_gem_abuse',time_range=month_range, to_ret = 'sum', location=profile.location)) girls_violence_month.append(month_range[0].strftime('%B')) girls_violence_data.append(get_numeric_report_data('edtrac_violence_girls', time_range=month_range, to_ret='sum', location=profile.location)) boys_violence_month.append(month_range[0].strftime('%B')) boys_violence_data.append(get_numeric_report_data('edtrac_violence_boys', time_range=month_range, to_ret='sum', location=profile.location)) reported_violence_month.append(month_range[0].strftime('%B')) reported_violence_data.append(get_numeric_report_data('edtrac_violence_reported', time_range=month_range, to_ret='sum', location=profile.location)) monthly_data_h_teachers = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(h_teach_month, h_teach_data)]) monthly_violence_data_girls = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(girls_violence_month, girls_violence_data)]) monthly_violence_data_boys = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(boys_violence_month, boys_violence_data)]) monthly_violence_data_reported = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(reported_violence_month, reported_violence_data)]) gem_month = copy.deepcopy(h_teach_month) monthly_data_gem = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(gem_month, gem_data)]) context_vars['monthly_data_gem'] = monthly_data_gem context_vars['monthly_violence_data_girls'] = monthly_violence_data_girls context_vars['monthly_violence_data_boys'] = monthly_violence_data_boys context_vars['monthly_violence_data_reported'] = monthly_violence_data_reported context_vars['monthly_data_h_teach'] = monthly_data_h_teachers context_vars['schools_responding_to_all_questions'] = total_number_of_schools_that_responded_to_all_violence_questions() if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Admins'): return render_to_response('education/admin/admin_violence_details.html', context_vars, RequestContext(req)) elif profile.is_member_of('DEO'): context_vars['location_name'] = profile.location return render_to_response('education/deo/deo2_violence_details.html', context_vars, RequestContext(req)) def total_number_of_schools_that_responded_to_all_violence_questions(): schools_responding_to_boys_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_boys")] schools_responding_to_girls_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_girls")] schools_that_referred_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_reported")] schools_that_answered_all_questions = list(set(schools_responding_to_boys_violence).intersection(schools_responding_to_girls_violence).intersection(schools_that_referred_violence)) valid_school_names = [school for school in schools_that_answered_all_questions if school is not None] return len(valid_school_names) def __get_school_name_from(response): try: school_name = response.contact.emisreporter.schools.all()[0].name except IndexError: school_name = None return school_name def __get_responses_for(poll_name): responses_for_all_questions = Response.objects.filter(poll__name__in =["edtrac_violence_girls","edtrac_violence_boys","edtrac_violence_reported"]) return responses_for_all_questions.filter(poll__name = poll_name) class DistrictViolenceDetails(TemplateView): template_name = "education/dashboard/district_violence_detail.html" def get_context_data(self, **kwargs): context = super(DistrictViolenceDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) or self.request.user.get_profile().location schools = School.objects.filter( pk__in = EmisReporter.objects.filter(reporting_location=location).values_list('schools__pk', flat=True)) school_case = [] month_now, month_before = get_month_day_range(datetime.datetime.now(), depth=2) totalViolence = 0 nowViolence = 0 beforeViolence = 0 for school in schools: # optimize with value queries now_data = get_numeric_report_data( 'edtrac_headteachers_abuse', time_range = month_now, school = school, to_ret = 'sum', belongs_to = 'schools') before_data = get_numeric_report_data('edtrac_headteachers_abuse', time_range = month_before, school = school,\ to_ret = 'sum', belongs_to = 'schools') data = int(now_data + before_data) totalViolence += data nowViolence += now_data beforeViolence += before_data if now_data > 0 or before_data > 0: school_case.append((school, now_data, before_data, data)) context['totalViolence'] = totalViolence context['nowViolence'] = nowViolence context['beforeViolence'] = beforeViolence context['location'] = location context['school_vals'] = school_case context['month_now'] = month_now[0] context['month_before'] = month_before[0] return context class AttendanceAdminDetails(TemplateView): template_name = "education/admin/attendance_details.html" def get_context_data(self, **kwargs): context = super(AttendanceAdminDetails, self).get_context_data(**kwargs) #TODO: proper drilldown of attendance by school # National level ideally "admin" and can be superclassed to suit other roles profile = self.request.user.get_profile() context['role_name'] = profile.role.name if profile.is_member_of("Admins") or profile.is_member_of("Ministry Officials") or profile.is_member_of('UNICEF Officials'): names = list(set(EmisReporter.objects.exclude(reporting_location=None).filter(reporting_location__type="district").\ values_list('reporting_location__name',flat=True))) locations = Location.objects.filter(name__in=names).order_by("name") context['total_disticts'] = locations.count() headings = [ 'Location', 'Boys P3', 'Boys P6', 'Girls P3', 'Girls P6', 'Female Teachers', "Male Teachers"] context['headings'] = headings context['week'] = datetime.datetime.now() context['location'] = profile.location return context # search functionality def search_form(req): searchform = SearchForm() if req.method == 'POST': searchform = SearchForm(req.POST) if searchform.is_valid(): searchform.save() return render_to_response( 'education/partials/search-form.html', {'form': searchform}, RequestContext(req) ) class ProgressAdminDetails(TemplateView): template_name = "education/progress/admin_progress_details.html" def get_context_data(self, **kwargs): context = super(ProgressAdminDetails, self).get_context_data(**kwargs) context['progress'] = list_poll_responses(Poll.objects.get(name="edtrac_p3curriculum_progress")) getcontext().prec = 1 context['progress_figures'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_p3curriculum_progress"),\ location=self.request.user.get_profile().location, choices = [Decimal(str(key)) for key in themes.keys()]) return context CHOICES = [0, 25, 50, 75, 100] class MealsAdminDetails(TemplateView): template_name = "education/admin/admin_meals_details.html" def get_context_data(self, **kwargs): choices = CHOICES context = super(MealsAdminDetails, self).get_context_data(**kwargs) context['school_meals_reports'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_headteachers_meals"),\ month_filter=True, choices=choices) context['community_meals_reports'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_smc_meals"), month_filter=True, choices=choices, with_percent=True) districts = Location.objects.filter(type="district", id__in =\ EmisReporter.objects.exclude(reporting_location = None).\ values_list('reporting_location__id', flat=True)).order_by('name').\ values_list('name', flat=True) # basic filtering for CSS districts = [[d, False] for d in districts] districts[0][1] = True context['districts'] = districts return context # Meals being had at a district class DistrictMealsDetails(DetailView): template_name = "education/admin/district_meal.html" context_object_name = "district_meals" model = Location def get_object(self): return self.model.objects.filter(type="district").get(name = self.kwargs.get('name')) def get_context_data(self, **kwargs): context = super(DistrictMealsDetails, self).get_context_data(**kwargs) location = self.get_object() choices = CHOICES school_meal_reports = get_count_response_to_polls( Poll.objects.get(name="edtrac_headteachers_meals"), location_name = location.name, month_filter=True, choices=choices, with_range = True, with_percent = True ) context['school_meals_reports'] = school_meal_reports context['location'] = location now = datetime.datetime.now() ranges = get_month_day_range(now, depth = now.month) ranges.reverse() context['date_ranges'] = ranges return context @login_required def deo_dashboard(req): location = req.user.get_profile().location return render_to_response("education/deo/deo_dashboard.html", generate_dashboard_vars(location=location), RequestContext(req)) @login_required def quitters(req): quitters = EmisReporter.objects.filter(connection__identity__in=Blacklist.objects.values_list('connection__identity',flat=True)) return render_to_response('education/partials/reporters/quitters.html',{'quitters':quitters}, RequestContext(req)) class ViolenceDeoDetails(TemplateView): template_name = "education/deo/deo_violence_details.html" def get_context_data(self, **kwargs): context = super(ViolenceDeoDetails, self).get_context_data(**kwargs) #context['violence_cases'] = list_poll_responses(Poll.objects.get(name="emis_headteachers_abuse")) context['violence_cases'] = poll_response_sum(Poll.objects.get(name="edtrac_headteachers_abuse"), location=self.request.user.get_profile().location, month_filter=True) return context @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ViolenceDeoDetails, self).dispatch(*args, **kwargs) class ProgressDeoDetails(TemplateView): template_name = "education/deo/deo_progress_details.html" def get_context_data(self, **kwargs): context = super(ProgressDeoDetails, self).get_context_data(**kwargs) #TODO mixins and filters context['progress'] = list_poll_responses(Poll.objects.get(name="edtrac_p3curriculum_progress")) return context ########################################################################################################## ########################################################################################################## ############################ More Generic Views ########################################################## ########################################################################################################## ########################################################################################################## ## management control panel @login_required def control_panel(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Ministry Officials'): return render_to_response('education/partials/control_panel.html', {}, RequestContext(req)) else: return render_to_response('education/partials/control_panel_dist.html',{}, RequestContext(req)) @login_required def audit_trail(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): # aparently the only places where comments are made is functions that involve editing users, reporters, etc. revisions = Revision.objects.exclude(comment='').order_by('-date_created').values_list('user__username','comment','date_created') else: revisions = Revision.objects.exclude(user__username = 'admin', comment='').\ order_by('-date_created').values_list('user__username','comment','date_created') return render_to_response('education/admin/audit_trail.html',{'revisions':revisions}, RequestContext(req)) class DistrictViolenceCommunityDetails(DetailView): context_object_name = "district_violence" model = Location def get_context_data(self, **kwargs): context = super(DistrictViolenceCommunityDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) or self.request.user.get_profile().location emis_reporters = EmisReporter.objects.filter(groups__name="GEM", connection__in =\ Poll.objects.get(name="edtrac_gem_abuse").responses.values_list('contact__connection',flat=True)) context['location'] = location context['reporters'] = emis_reporters context['month'] = datetime.datetime.now() return context # Progress happening in a district class DistrictProgressDetails(DetailView): context_object_name = "district_progress" model = Location #TODO provide filters def get_context_data(self, **kwargs): context = super(DistrictProgressDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) context['location'] = location return context ########################################################################################################## ########################################################################################################## ################################ Other handy views for EduTrac ############################################ ########################################################################################################## ########################################################################################################## HEADINGS = ['District', 'Absent (%) This week', 'Absent (%) Last week'] #define location and school for p3 and p6 students locale = Location.objects.exclude(type="country").filter(type="district") @login_required def boysp3_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_boysp3_enrollment','edtrac_boysp3_attendance') return render_to_response("education/boysp3_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data', 'Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def boysp6_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_boysp6_enrollment','edtrac_boysp6_attendance') return render_to_response("education/boysp6_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def girlsp3_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_girlsp3_enrollment','edtrac_girlsp3_attendance') return render_to_response("education/girlsp3_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def girlsp6_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_girlsp6_enrollment','edtrac_girlsp6_attendance') return render_to_response("education/girlsp6_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def female_t_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_f_teachers_deployment','edtrac_f_teachers_attendance') return render_to_response("education/female_t_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def male_t_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_m_teachers_deployment','edtrac_m_teachers_attendance') return render_to_response("education/male_t_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) def boys_p3_attendance(req, **kwargs): profile = req.user.get_profile() location = profile.location if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): """ This view shows data by district """ locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.select_related().distinct().values_list('reporting_location__name', flat=True)).order_by("name") # return view that will give school-based views # --> ref function just below this <--- return boys_p3_attd_admin(req, locations=locations) else: #DEO dates = kwargs.get('dates') schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] for d in dates: temp.extend(return_absent('edtrac_boysp3_attendance', 'edtrac_boysp3_enrollment', school = school, date_week=d)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location':location } def boys_p3_attd_admin(req, **kwargs): """ Helper function to get differences in absenteeism across districts. """ # P3 attendance /// what to show an admin or Ministry official locations = kwargs.get('locations') to_ret = return_absent('edtrac_boysp3_attendance', 'edtrac_boysp3_enrollment', locations) return {'location_data':to_ret, 'headings': HEADINGS, 'week':datetime.datetime.now()} def boys_p6_attendance(req): profile = req.user.get_profile() location = profile.location if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return boys_p6_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_boysp6_attendance', 'edtrac_boysp6_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def boys_p6_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P6 boys. """ # P6 attendance /// what to show an admin or Ministry official to_ret = return_absent('edtrac_boysp6_attendance', 'edtrac_boysp6_enrollment', locations=locations) return {'location_data':to_ret,'headings':HEADINGS,'week':datetime.datetime.now()} def girls_p3_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return girls_p3_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_girlsp3_attendance', 'edtrac_girlsp3_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def girls_p3_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P3 girls """ to_ret = return_absent('edtrac_girlsp3_attendance', 'edtrac_girlsp3_enrollment', locations=locations) return {'location_data':to_ret,'headings':HEADINGS,'week':datetime.datetime.now()} def girls_p6_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return girls_p6_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_girlsp6_attendance', 'edtrac_girlsp6_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def girls_p6_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P6 girls """ to_ret = return_absent('edtrac_girlsp6_attendance', 'edtrac_girlsp6_enrollment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def female_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.distinct().values_list('reporting_location__name',flat=True)).order_by("name") return female_teacher_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_f_teachers_attendance', 'edtrac_f_teachers_deployment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def female_teacher_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for all female teachers """ to_ret = return_absent('edtrac_f_teachers_attendance', 'edtrac_f_teachers_deployment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def male_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.distinct().values_list('reporting_location__name',flat=True)).order_by("name") return male_teacher_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_m_teachers_attendance', 'edtrac_m_teachers_deployment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def male_teacher_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for all female teachers """ to_ret = return_absent('edtrac_m_teachers_attendance', 'edtrac_m_teachers_deployment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def male_head_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): schools = School.objects.filter(location__name__in=EmisReporter.objects.distinct().\ filter(reporting_location__type = 'district').values_list('reporting_location__name', flat=True)) else: #DEO schools = School.objects.filter(location=location) data_to_render = [] for school in schools: #TODO separate male and female head teachers data = poll_response_sum(Poll.objects.get(name="edtrac_head_teachers_attendance"),month_filter='weekly',location=school.location) data_to_render.append( [ school, school.location, data ] ) return render_to_response( 'education/partials/male_head_teacher_attendance.html', { 'week':datetime.datetime.now(), 'headings':['School', 'District', 'Number'], 'location_data': data_to_render }, RequestContext(req) ) def female_head_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): schools = School.objects.filter(location__name__in= EmisReporter.objects.distinct().\ select_related().filter(reporting_location__type = 'district').values_list('reporting_location__name', flat=True)) else: #DEO schools = School.objects.select_related().filter(location=location).order_by("name", "location__name") data_to_render = [] for school in schools: #TODO separate male and female head teachers data = poll_response_sum(Poll.objects.get(name="edtrac_head_teachers_attendance"),month_filter='weekly',location=school.location) data_to_render.append( [ school, school.location, data ] ) return render_to_response( 'education/partials/female_head_teacher_attendance.html', { 'week':datetime.datetime.now(), 'headings':['School', 'District', 'Number'], 'location_data': data_to_render }, RequestContext(req) ) @login_required def time_range_boysp3(req): return view_stats(req, enrol_deploy_poll='edtrac_boysp3_enrollment', attendance_poll='edtrac_boysp3_attendance', title='P3 Boys Absenteeism', url_name_district = "boysp3-district-attd-detail" ) @login_required def time_range_boysp6(req): return view_stats(req, enrol_deploy_poll='edtrac_boysp6_enrollment', attendance_poll='edtrac_boysp6_attendance', title='P6 Boys Absenteeism', url_name_district = "boysp6-district-attd-detail" ) @login_required def time_range_girlsp3(req): return view_stats(req, enrol_deploy_poll='edtrac_girlsp3_enrollment', attendance_poll='edtrac_girlsp3_attendance', title='P3 Girls Absenteeism', url_name_district = "girlsp3-district-attd-detail" ) @login_required def time_range_girlsp6(req): return view_stats(req, enrol_deploy_poll='edtrac_girlsp6_enrollment', attendance_poll='edtrac_girlsp6_attendance', title='P6 Girls Absenteeism', url_name_district = "girlsp6-district-attd-detail" ) @login_required def time_range_teachers_m(req): return view_stats(req, enrol_deploy_poll='edtrac_m_teachers_deployment', attendance_poll='edtrac_m_teachers_attendance', title='Male teachers absenteeism', url_name_district = "male-teacher-district-attd-detail" ) @login_required def time_range_teachers_f(req): return view_stats(req, enrol_deploy_poll='edtrac_f_teachers_deployment', attendance_poll='edtrac_f_teachers_attendance', title='Female teachers absenteeism', url_name_district = "female-teacher-district-attd-detail" ) @login_required def time_range_head_teachers(req): """ Get a date-ranged page for Head teachers """ """ A function that compute time-ranged data for female teachers. This function is split in two: handling of POST data and GET data. It also makes a difference between User groups so you different role players like DEO, Admins, UNICEF Officials """ time_range_form = ResultForm() locations = Location.objects.filter(type='district').filter(pk__in = EmisReporter.objects.values_list('reporting_location__pk',flat=True)) if req.method == 'POST': # handling of POST data time_range_form = ResultForm(data=req.POST) to_ret = [] if time_range_form.is_valid(): from_date = time_range_form.cleaned_data['from_date'] to_date = time_range_form.cleaned_data['to_date'] month_delta = abs(from_date.month - to_date.month) date_weeks = [] if month_delta <= 2: # same month get days in between while from_date <= to_date: if from_date.weekday() == 3: #is to_day a Thursday? date_weeks.append(previous_calendar_week(t = from_date)) # get range from Wed to Thur. from_date += datetime.timedelta(days = 1) else: # case for when more than 2 months is selected while from_date <= to_date: #TODO refine data points date_weeks.append([dateutils.month_start(from_date),dateutils.month_end(from_date)]) from_date = dateutils.increment(from_date, months = 1) # splitting the results by analysing membership of Officials accessing EduTrac if req.user.get_profile().is_member_of('Ministry Officials') or\ req.user.get_profile().is_member_of('Admins') or req.user.get_profile().is_member_of('UNICEF Officials'): schools_temp = School.objects.select_related().\ filter(pk__in = EmisReporter.objects.select_related().\ filter(groups__name = "Head Teachers").values_list('schools__pk',flat=True)) for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True).select_related() location_schools = School.objects.filter(pk__in = schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) else: #Non admin types date_weeks, to_ret = [], [] date_weeks.append(previous_calendar_week(t = datetime.datetime.now())) for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True) location_schools = School.objects.filter(pk__in=schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) return render_to_response('education/timeslider_base.html', {'form':time_range_form, 'dataset':to_ret, 'title':'Female Teacher Absenteeism', 'url_name':"female-teacher-district-attd-detail", 'date_batch':date_weeks}, RequestContext(req)) else: return render_to_response('education/timeslider_base.html', {'form':time_range_form, 'url_name':"female-teacher-district-attd-detail", 'title':'Male Teacher Absenteeism'}, RequestContext(req)) else: # initial GET view is displays difference between 2 weeks of the attendance of female teachers as reported by the Head Teacher date_weeks = [] location_data = [] # get current week date_weeks.append(previous_calendar_week()) temp_date = datetime.datetime(date_weeks[0][0].year, date_weeks[0][0].month, date_weeks[0][0].day) - datetime.timedelta(days = 1) # add previous week to date_weeks list date_weeks.append(previous_calendar_week(t = temp_date)) # cache schools query in memory (these are Schools that have enrollment data) schools_temp = Poll.objects.select_related().get(name = 'edtrac_f_teachers_deployment').responses.\ exclude(contact__emisreporter__schools__name = None).select_related() context_vars = {} for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True) location_schools = School.objects.filter(pk__in = schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) try: diff = temp[0] - temp[1] except TypeError: diff = '--' location_data.append([location, temp[0], temp[1], diff]) context_vars.update({'location_data':location_data}) profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): x = {'url_name':"female-teacher-district-attd-detail", "headings":["District", "Current Week", "Previous Week", "Percentage Change"]} else: x = {'url_name':"school-detail", "headings":["School", "Current Week", "Previous Week", "Percentage Change"]} context_vars.update({'form':time_range_form,'title':'Female Teachers Absenteeism'}) context_vars.update(x) return render_to_response('education/timeslider_base.html', context_vars, RequestContext(req)) def whitelist(request): numbers = [] for c in Connection.objects.exclude(backend__name='yo6200'): if not c.identity.strip() in numbers: numbers.append(c.identity.strip()) return render_to_response( "education/whitelist.txt", {'connections': Connection.objects.exclude(backend__name='yo6200').filter(identity__in=numbers)}, mimetype="text/plain", context_instance=RequestContext(request)) def _reload_whitelists(): refresh_urls = getattr(settings, 'REFRESH_WHITELIST_URL', None) if refresh_urls is not None: if not type(refresh_urls) == list: refresh_urls = [refresh_urls, ] for refresh_url in refresh_urls: try: status_code = urlopen(refresh_url).getcode() if int(status_code / 100) == 2: continue else: return False except Exception as e: return False return True return False def _addto_autoreg(connections): for connection in connections: if not connection.contact and\ not ScriptProgress.objects.filter(script__slug='emis_autoreg', connection=connection).count(): ScriptProgress.objects.create(script=Script.objects.get(slug="edtrac_autoreg"),\ connection=connection) @login_required def add_connection(request): form = NewConnectionForm() if request.method == 'POST': form = NewConnectionForm(request.POST) connections = [] if form.is_valid(): identity = form.cleaned_data['identity'] identity, backend = assign_backend(str(identity.strip())) # create connection, created = Connection.objects.get_or_create(identity=identity, backend=backend) # in case a duplicate process does exist, delete it ScriptProgress.objects.filter(connection=connection).delete() connections.append(connection) other_numbers = request.POST.getlist('other_nums') if len(other_numbers) > 0: for number in other_numbers: identity, backend = assign_backend(str(number.strip())) connection, created = Connection.objects.get_or_create(identity=identity, backend=backend) connections.append(connection) _addto_autoreg(connections) _reload_whitelists() # time.sleep(2) return render_to_response('education/partials/addnumbers_row.html', {'object':connections, 'selectable':False}, RequestContext(request)) return render_to_response("education/partials/new_connection.html", {'form':form}, RequestContext(request)) @login_required def delete_connection(request, connection_id): connection = get_object_or_404(Connection, pk=connection_id) connection.delete() _reload_whitelists() return render_to_response("education/partials/connection_view.html", {'object':connection.contact }, context_instance=RequestContext(request)) @login_required def comments(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('Ministry Officials') or profile.is_member_of('UNICEF Officials'): comments = [(r.get_commentable_display(), r.comment, r.user, r.get_reporting_period_display(), get_range_on_date(r.reporting_period, r) ) for r in ReportComment.objects.order_by('-report_date')] else: # DFO/DEO should get only information on their districts comments = [(r.get_commentable_display(), r.comment, r.user, r.get_reporting_period_display(), get_range_on_date(r.reporting_period, r)) for r in ReportComment.objects.filter(user__profile__location=profile.location).order_by('-report_date')] return render_to_response('education/partials/comments.html', {'data_set':comments}, RequestContext(req)) @login_required def new_comment(req): report_comment_form = ReportCommentForm(initial = {'user':req.user.pk}) if req.method == 'POST': report_comment_form = ReportCommentForm(req.POST) if report_comment_form.is_valid(): with reversion.create_revision(): report_comment_form.save() reversion.set_comment('wrote a comment') return HttpResponseRedirect(reverse('comments')) else: return render_to_response('education/partials/new_comment.html', {'form':report_comment_form}, RequestContext(req)) else: return render_to_response('education/partials/new_comment.html',{'form':report_comment_form}, RequestContext(req)) @login_required def edit_comment(req, report_comment_pk): report_comment = get_object_or_404(ReportComment, pk=report_comment_pk) report_comment_form = ReportCommentForm(instance=report_comment) if req.method == 'POST': report_comment_form = ReportCommentForm(instance=report_comment, data=req.POST) if report_comment_form.is_valid(): with reversion.create_revision(): report_comment_form.save() reversion.set_comment('edited comment') return HttpResponseRedirect(reverse('comments')) else: return render_to_response('education/partials/edit_comment.html', {'form':report_comment_form}, RequestContext(req)) else: return render_to_response('education/partials/edit_comment.html', {'form':report_comment_form}, RequestContext(req)) @login_required def delete_comment(req, report_comment_pk): report_comment = get_object_or_404(ReportComment, pk=report_comment_pk) if req.method == 'POST': with reversion.create_revision(): report_comment.delete() reversion.set_comment('deleted comment') return HttpResponse(status=200) @login_required def delete_reporter(request, reporter_pk): reporter = get_object_or_404(EmisReporter, pk=reporter_pk) reporter_name = reporter.name if request.method == 'POST': with reversion.create_revision(): reversion.set_comment('deleted %s'%reporter_name) reporter.delete() return HttpResponse(status=200) @login_required def edit_reporter(request, reporter_pk): reporter = get_object_or_404(EmisReporter, pk=reporter_pk) reporter_group_name = reporter.groups.all()[0].name if request.method == 'POST': reporter_form = EditReporterForm(instance=reporter,data=request.POST) if reporter_form.is_valid(): with reversion.create_revision(): reporter_form.save() reversion.set_comment('edited %s details' % reporter.name) saved_reporter_grp = EmisReporter.objects.get(pk=reporter_pk).groups.all()[0].name if reporter.default_connection and reporter.groups.count() > 0: # remove from other scripts # if reporter's groups remain the same. if reporter_group_name == saved_reporter_grp: pass else: ScriptProgress.objects.exclude(script__slug="edtrac_autoreg").filter(connection=reporter.default_connection).delete() _schedule_teacher_weekly_scripts(reporter.groups.all()[0], reporter.default_connection, ['Teachers']) _schedule_weekly_scripts(reporter.groups.all()[0], reporter.default_connection, ['Head Teachers', 'SMC']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_head_teachers_monthly', 'last', ['Head Teachers']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_gem_monthly', 20, ['GEM']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_smc_monthly', 5, ['SMC']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_smc_termly', ['SMC']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_p3_enrollment_headteacher_termly', ['Head Teachers']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_p6_enrollment_headteacher_termly', ['Head Teachers']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_teacher_deployment_headteacher_termly', ['Head Teachers']) return redirect("reporter-detail", pk=reporter.pk) else: if reporter.schools.exists(): reporter_form = EditReporterForm(instance=reporter, initial={'schools':reporter.schools.all()[0]}) else: reporter_form = EditReporterForm(instance=reporter) return render_to_response('education/edit_reporter.html', {'reporter_form': reporter_form, 'reporter': reporter}, context_instance=RequestContext(request)) @login_required def add_schools(request): if request.method == 'POST': form = SchoolForm(request.POST) schools = [] if form.is_valid(): names = filter(None, request.POST.getlist('name')) locations = request.POST.getlist('location') if len(names) > 0: for i, name in enumerate(names): location = Location.objects.get(pk=int(locations[i])) name, created = School.objects.get_or_create(name=name, location=location) schools.append(name) return render_to_response('education/partials/addschools_row.html', {'object':schools, 'selectable':False}, RequestContext(request)) else: form = SchoolForm() return render_to_response('education/deo/add_schools.html', {'form': form, }, context_instance=RequestContext(request)) @login_required def delete_school(request, school_pk): school = get_object_or_404(School, pk=school_pk) school_name = school.name if request.method == 'POST': with reversion.create_revision(): school.delete() reversion.set_comment("%s deleted %s"%(request.user.username, school_name)) return HttpResponse(status=200) @login_required def edit_school(request, school_pk): school = get_object_or_404(School, pk=school_pk) school_form = SchoolForm(instance=school) school_name = school.name if request.method == 'POST': school_form = SchoolForm(instance=school, data=request.POST) if school_form.is_valid(): with reversion.create_revision(): school_form.save() reversion.set_comment('edited %s' % school_name) else: return render_to_response('education/partials/edit_school.html' , {'school_form': school_form, 'school' : school}, context_instance=RequestContext(request)) return render_to_response('/education/partials/school_row.html', {'object':School.objects.get(pk=school_pk), 'selectable':True}, context_instance=RequestContext(request)) else: return render_to_response('education/partials/edit_school.html', {'school_form': school_form, 'school': school}, context_instance=RequestContext(request)) @login_required def school_detail(request, school_id): school = School.objects.get(id=school_id) today = date.today() month_ranges = get_month_day_range(today, depth=today.month) month_ranges.reverse() slug_list = ['girlsp3', 'boysp3', 'girlsp6', 'boysp6'] slug_list_tr = ['f_teachers', 'm_teachers'] monthly_data = [] monthly_data_teachers = [] monthly_data_head_teachers = [] monthly_data_violence = [] monthly_data_meals = [] for month_range in month_ranges: monthly_data.append( [return_absent_month( 'edtrac_'+ '%s'%slug + '_attendance', 'edtrac_'+ '%s'%slug + '_enrollment', month_range = month_range, school = school) for slug in slug_list]) monthly_data_teachers.append( [return_absent_month( 'edtrac_'+'%s'%slug + '_attendance', 'edtrac_'+'%s'%slug + '_deployment', month_range = month_range, school=school) for slug in slug_list_tr]) reporters = [] reps = school.emisreporter_set.values() for rep in reps: r = EmisReporter.objects.get(id=rep['id']) reporters.append(r) boys_p3_enrolled = poll_responses_term('edtrac_boysp3_enrollment', belongs_to='schools', school = school) boys_p6_enrolled = poll_responses_term('edtrac_boysp6_enrollment', belongs_to='schools', school = school) girls_p3_enrolled = poll_responses_term('edtrac_girlsp3_enrollment', belongs_to='schools', school = school) girls_p6_enrolled = poll_responses_term('edtrac_girlsp6_enrollment', belongs_to='schools', school = school) m_teachers_deployed = poll_responses_term('edtrac_m_teachers_deployment', belongs_to = 'schools', school = school) f_teachers_deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to = 'schools', school = school) return render_to_response("education/school_detail.html", {\ 'school_name': school.name, 'months' : [d_start for d_start, d_end in month_ranges], 'monthly_data' : monthly_data, 'monthly_data_teachers' : monthly_data_teachers, 'monthly_data_head_teachers': monthly_data_head_teachers, 'monthly_data_violence' : monthly_data_violence, 'monthly_data_meals' : monthly_data_meals, 'reporters' : reporters, 'boys_p3_enrolled': boys_p3_enrolled, 'boys_p6_enrolled': boys_p6_enrolled, 'girls_p3_enrolled' : girls_p3_enrolled, 'girls_p6_enrolled' : girls_p6_enrolled, 'm_teachers_deployed': m_teachers_deployed, 'f_teachers_deployed': f_teachers_deployed }, RequestContext(request)) # analytics specific for emis {copy, but adjust to suit your needs} @login_required def to_excel(request, start_date=None, end_date=None, district_id=None): return create_excel_dataset(request, start_date, end_date, district_id) @login_required def school_reporters_to_excel(req): book = xlwt.Workbook() all_schools = School.objects.all() sheet = book.add_sheet('School Reporters') headings = ['School', 'Reporters'] rowx = 0 for colx, value in enumerate(headings): sheet.write(rowx, colx, value) sheet.set_panes_frozen(True) sheet.set_horz_split_pos(rowx+1) sheet.set_remove_splits(True) for row in all_schools: rowx += 1 for colx, value in enumerate([row.name, ', '.join([reporter.name for reporter in row.emisreporter_set.all()])]): sheet.write(rowx, colx, value) response = HttpResponse(mimetype="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment; filename=school_reporters_data.xls' book.save(response) return response @login_required def system_report(req=None): book = xlwt.Workbook() school_dates = [ getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END'), ] first_date = school_dates[0] last_date = school_dates[1] date_bunches = [] while first_date <= last_date: tmp = get_day_range(first_date) first_date = tmp[0] date_bunches.append(get_day_range(first_date)) first_date = dateutils.increment(first_date, weeks=1) profile = req.user.get_profile() enrolled_answered = \ EnrolledDeployedQuestionsAnswered.objects.select_related() headings = ['School'] + [d.strftime("%d/%m/%Y") for d, _ in date_bunches] if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): district_names = enrolled_answered.values_list( 'school__location__name', flat=True ).distinct() else: location = profile.location district_names = [location.name] district_schools = {} for dn in district_names: district_schools[dn] = School.objects.select_related().filter( pk__in=enrolled_answered.filter( school__location__name=dn ).values_list('school__pk', flat=True)).order_by('name') polls = Poll.objects.select_related().filter( Q(name__icontains="boys") | Q(name__icontains="girls") | Q(name='edtrac_f_teachers_attendance') | Q(name='edtrac_m_teachers_attendance') ) for district_name in district_schools.keys(): container = [] sheet = book.add_sheet(district_name, cell_overwrite_ok=True) rowx = 0 for colx, val_headings in enumerate(headings): sheet.write(rowx, colx, val_headings) sheet.set_panes_frozen(True) # in general, freeze after last heading row sheet.set_horz_split_pos(rowx + 1) # if user does unfreeze, don't leave a split there sheet.set_remove_splits(True) for school in district_schools[district_name]: school_vals = [school.name] for d_bunch in date_bunches: submission_count = 0 for poll in polls: submission_count += poll.responses.filter( contact__in=school.emisreporter_set.values_list( 'connection__contact'), date__range = d_bunch ).count() school_vals.extend([submission_count]) container.append(school_vals) for row in container: rowx += 1 for colx, value in enumerate(row): sheet.write(rowx, colx, value) response = HttpResponse(mimetype="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment; filename=SystemReport.xls' book.save(response) return response @login_required def excel_reports(req): return render_to_response('education/excelreports/excel_dashboard.html',{},RequestContext(req)) @login_required def edit_user(request, user_pk=None): title="" user=User() if request.method == 'POST' and request.user.get_profile().role_id == Role.objects.get(name = 'Admins').id: if user_pk: user = get_object_or_404(User, pk=user_pk) user_form = UserForm(request.POST,instance=user,edit=True) if user_form.is_valid(): with reversion.create_revision(): user = user_form.save() if user.groups.count() == 0: group = Group.objects.get(pk=user_form.cleaned_data['groups'][0].pk) user.groups.add(group) try: profile=UserProfile.objects.get(user=user) profile.location=user_form.cleaned_data['location'] profile.role=Role.objects.get(name=user_form.cleaned_data['groups'][0].name) profile.save() except UserProfile.DoesNotExist: UserProfile.objects.create(name=user.first_name,user=user,role=Role.objects.get(pk=user_form.cleaned_data['groups'][0].pk),location=user_form.cleaned_data['location']) reversion.set_comment("edited %s's profile" % user.username) return HttpResponseRedirect(reverse("emis-users")) elif user_pk: user = get_object_or_404(User, pk=user_pk) user_form = UserForm(instance=user,edit=True) title="Editing "+user.username else: user_form = UserForm(instance=user) return render_to_response('education/partials/edit_user.html', {'user_form': user_form,'title':title}, context_instance=RequestContext(request)) def htattendance(request, start_date=None, end_date=None, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) smc_htpresent = Poll.objects.get(name='emis_absence').responses.exclude(has_errors=True)\ .filter(date__range=(dates.get('start'), dates.get('end')))\ .filter(message__connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all())\ .order_by('message__date') return generic(request, model = Poll, queryset = smc_htpresent, objects_per_page = 50, results_title = 'Head Teacher Presence as Reported by SMCs', columns = [ ('school', False, 'school', None), ('present', False, 'present', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/ht_attendance_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timeslider_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) def gem_htattendance(request, start_date=None, end_date=None, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) gem_htpresent = XFormSubmission.objects.filter(xform__keyword='gemteachers').exclude(has_errors=True)\ .filter(created__range=(dates.get('start'), dates.get('end')))\ .filter(connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all())\ .order_by('created') return generic(request, model = XFormSubmission, queryset = gem_htpresent, objects_per_page = 50, results_title = 'Head Teacher Presence as Reported by GEM', columns = [ ('school', False, 'school', None), ('present', False, 'present', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/gemht_attendance_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timesli`der_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) def meals(request, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) meals = Poll.objects.get(name='emis_meals').responses.exclude(has_errors=True)\ .filter(date__range=(dates.get('start'), dates.get('end')))\ .filter(message__connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all()) return generic(request, model = Poll, queryset = meals, objects_per_page = 50, results_title = 'Pupils who had Meals at School', columns = [ ('school', False, 'school', None), ('estimated number', False, 'number', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/meals_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timeslider_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) @super_user_required def edit_scripts(request): forms = [] for script in Script.objects.exclude(name='Special Script').order_by('slug'): forms.append((script, ScriptsForm(instance=script))) if request.method == 'POST': script_form = ScriptsForm(request.POST,instance=Script.objects.get(slug=request.POST.get('slug'))) if script_form.is_valid(): script_form.save() return render_to_response('education/partials/edit_script.html', {'forms': forms, 'management_for': 'scripts'}, context_instance=RequestContext(request)) def emis_scripts_special(req): scripts = Script.objects.exclude(slug__icontains='weekly').exclude(name='Special Script').exclude(slug='edtrac_autoreg').order_by('slug') if req.method == 'POST': checked_numbers = req.POST.getlist('checked_numbers') checked_numbers = [n for n in checked_numbers if re.match(r'\d+', n)] poll_questions = req.POST.getlist('poll_questions') poll_scripts = [pq.split('-') for pq in poll_questions] #(poll_id, script_slug) d = datetime.datetime.now() _script = Script.objects.create(slug=\ "edtrac_%s %s %s %s:%s:%s"%(d.year,d.month,d.day,d.hour, d.minute, d.second), name="Special Script") _poll_scripts = [] # make sure that the poll/script to sent to just one group not a mixture of groups. reporter_group_name = EmisReporter.objects.get(id=checked_numbers[0]).groups.all()[0].name.lower().replace(' ', '_') for id, script_slug in poll_scripts: if re.search(reporter_group_name, script_slug): _poll_scripts.append((id, script_slug)) for i, li in enumerate(_poll_scripts): poll_id, script_slug = li _script.steps.add(ScriptStep.objects.create( script = _script, poll = Poll.objects.get(id = poll_id), order = i, # using index for different order??? rule = ScriptStep.RESEND_MOVEON, num_tries = 1, start_offset = 60, retry_offset = 86400, giveup_offset = 86400, )) _script.save() if len(checked_numbers) < 25 and len(checked_numbers) > 0: # assuming that "all" is not checked for reporter in EmisReporter.objects.filter(id__in=checked_numbers).exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() else: # what if the reporting location is different? Would you instead want to poll the different districts? single_reporter_location = True # flag reporter_location = EmisReporter.objects.filter(id__in=checked_numbers).\ exclude(reporting_location=None).values_list('reporting_location__name', flat=True) if reporter_location.count() > 0 and len(set(reporter_location)) > 1: single_reporter_location = False reporter_location = EmisReporter.objects.filter(reporting_location__type = 'district').\ values_list('reporting_location__name',flat=True) else: reporter_location = EmisReporter.objects.filter(reporting_location__type='district').\ filter(reporting_location__name = reporter_location[0]).values_list('reporting_location__name',flat=True) single_school = True reporter_schools = EmisReporter.objects.filter(id__in=checked_numbers).\ exclude(schools=None).values_list('schools__name', flat=True) if reporter_schools.count() > 0 and len(set(reporter_schools)) > 1: single_school = False reporter_schools = EmisReporter.objects.values_list('schools__name',flat=True) else: reporter_schools = EmisReporter.objects.filter(schools__name=reporter_schools[0]).values_list( 'schools__name', flat=True ) if single_reporter_location or single_school: for reporter in EmisReporter.objects.filter(schools__name__in=reporter_schools, reporting_location__name__in = reporter_location, groups__name =\ ' '.join([i.capitalize() for i in reporter_group_name.replace('_',' ').split()])).\ exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() else: for reporter in EmisReporter.objects.filter(groups__name =\ ' '.join([i.capitalize() for i in reporter_group_name.replace('_',' ').split()])).exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() return HttpResponseRedirect(reverse('emis-contact')) else: return render_to_response('education/partials/reporters/special_scripts.html',{'scripts':scripts}, RequestContext(req)) def reschedule_scripts(request, script_slug): grp = get_script_grp(script_slug) if script_slug.endswith('_weekly'): reschedule_weekly_polls(grp) elif script_slug.endswith('_monthly'): reschedule_monthly_polls(grp) else: if request.POST.has_key('date'): date = request.POST.get('date') else: date = None reschedule_termly_polls(grp, date) new_scripts = ScriptProgress.objects.filter(script__slug=script_slug) if new_scripts: new_script_date = new_scripts[0].time response = HttpResponse("This Script has been rescheduled to: %s " % new_script_date.strftime("%d-%m-%Y %H:%M")) return response else: return HttpResponse("This script can't be rescheduled. Try again") class EdtracReporter(ListView): model = EmisReporter template_name = "education/emisreporter_list.html" context_object_name = "reporter_list" ########## Maps ################# def attendance_visualization(req): return render_to_response( 'education/partials/map_attendance.html', { 'geoserver_url':getattr(settings, 'GEOSERVER_URL', 'http://localhost/geoserver') }, context_instance = RequestContext(req)) class AbsenteeismForm(forms.Form): error_css_class = 'error' select_choices = [('all', '--'), ('P3Boys', 'P3 Boys'), ('P3Girls', 'P3 Girls'), ('P3Pupils', 'P3 Pupils'), ('P6Boys', 'P6 Boys'), ('P6Girls', 'P6 Girls'), ('P6Pupils', 'P6 Pupils'), ('MaleTeachers', 'Male Teachers'), ('FemaleTeachers', 'Female Teachers'), ('Teachers', 'Teachers'), ('MaleHeadTeachers', 'Male Head Teachers'), ('FemaleHeadTeachers', 'Female Head Teachers'), ('HeadTeachers', 'Head Teachers'), ] from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) indicator = forms.ChoiceField(choices=select_choices, required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: if is_empty(data.get('indicator')): raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data @login_required def detail_attd(request, district=None): locations = get_location_for_absenteeism_view(district, request) time_range_depth = 4 if request.method == 'POST': absenteeism_form = AbsenteeismForm(data=request.POST) if absenteeism_form.is_valid(): indicator = absenteeism_form.cleaned_data['indicator'] week_range = get_date_range(absenteeism_form.cleaned_data['from_date'], absenteeism_form.cleaned_data['to_date'], time_range_depth) else: return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form}, RequestContext(request)) else: absenteeism_form = AbsenteeismForm(initial={'indicator': 'all'}) week_range = get_week_date(time_range_depth) indicator = "all" week_range.reverse() config_list = get_polls_for_keyword(indicator) collective_result, time_data, reporting_school_percent = get_aggregated_report(locations, config_list, week_range) weeks = ["%s - %s" % (i[0].strftime("%m/%d/%Y"), i[1].strftime("%m/%d/%Y")) for i in week_range] return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form, 'collective_result_keys': [config['collective_dict_key'] for config in config_list], 'collective_result': collective_result, 'time_data': mark_safe(json.dumps(time_data)), 'school_percent' : reporting_school_percent, 'weeks': mark_safe(json.dumps(weeks)), "locations": locations}, RequestContext(request)) @login_required def detail_dashboard(request, district=None): locations = get_location_for_absenteeism_view(district, request) time_range_depth = 4 if request.method == 'POST': absenteeism_form = AbsenteeismForm(data=request.POST) if absenteeism_form.is_valid(): indicator = absenteeism_form.cleaned_data['indicator'] week_range = get_date_range(absenteeism_form.cleaned_data['from_date'], absenteeism_form.cleaned_data['to_date'], time_range_depth) else: return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form}, RequestContext(request)) else: absenteeism_form = AbsenteeismForm(initial={'indicator': 'all'}) week_range = get_week_date(time_range_depth) indicator = "all" week_range.reverse() config_list = get_polls_for_keyword(indicator) collective_result, time_data, reporting_school_percent = get_aggregated_report(locations, config_list, week_range) weeks = ["%s - %s" % (i[0].strftime("%m/%d/%Y"), i[1].strftime("%m/%d/%Y")) for i in week_range] return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form, 'collective_result_keys': [config['collective_dict_key'] for config in config_list], 'collective_result': collective_result, 'time_data': mark_safe(json.dumps(time_data)), 'school_percent' : reporting_school_percent, 'weeks': mark_safe(json.dumps(weeks)), "locations": locations}, RequestContext(request)) @login_required def detail_attd_school(request, location): name = request.GET['school'] school_id = School.objects.get(name=name, location__name=location).id return redirect(reverse('school-detail',args=(school_id,))) class ExportPollForm(forms.Form): error_css_class = 'error' select_choices = list(Poll.objects.values_list(*['pk','name'])) from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) poll_name = forms.ChoiceField(choices=select_choices, required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: if is_empty(data.get('poll_name')): raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data def get_district_parent(reporting_location): parent_locations = reporting_location.get_ancestors() district_parent = [parent for parent in parent_locations if parent.type.name == 'district'] return district_parent[0].name def _format_responses(responses): a = [] for response in responses: if response.contact: contact = response.contact sender = contact location_type = contact.reporting_location.type reporting_location = contact.reporting_location.name if not location_type.name == 'district' and not location_type.name == 'country': reporting_location = get_district_parent(contact.reporting_location) location_type = 'district' school = ", ".join(contact.emisreporter.schools.values_list('name', flat=True)) else: sender = response.message.connection.identity location_type = "--" reporting_location = "--" school = "--" date = response.message.date if response.poll.type == "t": value = response.eav.poll_text_value elif response.poll.type == "n": if hasattr(response.eav, 'poll_number_value'): value = response.eav.poll_number_value else: value = 0 elif response.poll.type == 'l': value = response.eav.poll_location_value.name category = response.categories.values_list('category__name',flat=True) if len(category) == 0: category = "--" else: category = ", ".join(category) a.append((sender,location_type,reporting_location,school,date,value,category)) return a def _get_identity(r): return r.default_connection.identity if r.default_connection else "--" def _format_reporters(reporters): return [[r.id,r.name, _get_identity(r),r.reporting_location.type.name, r.reporting_location.name, ", ".join(r.schools.values_list('name', flat=True))] for r in reporters] @login_required def edtrac_export_poll_responses(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': form = ExportPollForm() else: form = ExportPollForm(data=request.POST) if form.is_valid(): poll = get_object_or_404(Poll, pk=form.cleaned_data['poll_name']) responses = poll.responses.all().order_by('-pk') to_date = form.cleaned_data['to_date'] from_date = form.cleaned_data['from_date'] if from_date and to_date: responses = responses.filter(date__range=[from_date, to_date]) resp = render_to_response( 'education/admin/export_poll_responses.csv', { 'responses': _format_responses(responses) }, mimetype='text/csv', context_instance=RequestContext(request) ) resp['Content-Disposition'] = 'attachment;filename="%s.csv"' \ % poll.name return resp return render_to_response('education/admin/export_poll_responses.html', {'form': form}, RequestContext(request), ) @login_required def edit_sub_county_reporters(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': sub_county_reporters = EmisReporter.objects.filter(reporting_location__type = 'sub_county') return render_to_response('education/admin/edit_sub_county_reporters.html', {'reporters':sub_county_reporters},RequestContext(request)) @login_required def export_sub_county_reporters(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': sub_county_reporters = EmisReporter.objects.filter(reporting_location__type='sub_county') resp = render_to_response('education/admin/export_sub_county_reporters.csv', {'responses': _format_reporters(sub_county_reporters)}, mimetype='text/csv', context_instance=RequestContext(request)) resp['Content-Disposition'] = 'attachment;filename="sub_county_reporters.csv"' return resp class ExportMessageForm(forms.Form): error_css_class = 'error' from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data def _get_school(m): if m.connection.contact.emisreporter.schools.all().exists(): return m.connection.contact.emisreporter.schools.all()[0] return None def _format_messages(messages): return[ [m ,m.connection.contact.reporting_location,_get_school(m),m.connection.contact,m.connection,m.date ] for m in messages] @login_required def edtrac_export_error_messages(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': form = ExportMessageForm() else: form = ExportMessageForm(data=request.POST) if form.is_valid(): messages = Message.objects.exclude( connection__identity__in = getattr(settings, 'MODEM_NUMBERS') ).filter(direction='I', connection__contact__emisreporter__reporting_location__in =\ locations.get(name__iexact="Uganda").get_descendants(include_self=True).all() ) messages= messages.filter(poll_responses=None) | messages.filter(poll_responses__has_errors=True) to_date = form.cleaned_data['to_date'] from_date = form.cleaned_data['from_date'] if from_date and to_date: messages = messages.filter(date__range=[from_date, to_date]) resp = render_to_response('education/admin/export_error_messages.csv', {'messages' : _format_messages(messages)}, mimetype='text/csv', context_instance=RequestContext(request)) resp['Content-Disposition'] = 'attachment;filename="error_messages.csv"'\ return resp return render_to_response('education/admin/export_error_messages.html', {'form':form},RequestContext(request)) def get_schools(request): location = request.GET['location'] list_of_schools = [{'text':'--------------','value':''}] if not is_empty(location): filtered_schools = School.objects.filter(location=Location.objects.get(pk=location,type__slug='district')) location_schools = [{'text':school.name,'value':school.pk} for school in filtered_schools] list_of_schools.extend(location_schools) return HttpResponse(json.dumps(list_of_schools))
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import numpy from nupic.bindings.math import GetNTAReal from nupic.research.monitor_mixin.monitor_mixin_base import MonitorMixinBase from nupic.research.monitor_mixin.temporal_memory_monitor_mixin import ( TemporalMemoryMonitorMixin) from sensorimotor.general_temporal_memory import GeneralTemporalMemory from sensorimotor.temporal_pooler import TemporalPooler from sensorimotor.temporal_pooler_monitor_mixin import ( TemporalPoolerMonitorMixin) class MonitoredGeneralTemporalMemory(TemporalMemoryMonitorMixin, GeneralTemporalMemory): pass class MonitoredTemporalPooler(TemporalPoolerMonitorMixin, TemporalPooler): pass """ Experiment runner class for running networks with layer 4 and layer 3. The client is responsible for setting up universes, agents, and worlds. This class just sets up and runs the HTM learning algorithms. """ realDType = GetNTAReal() class SensorimotorExperimentRunner(object): DEFAULT_TM_PARAMS = { # These should be decent for most experiments, shouldn't need to override # these too often. Might want to increase cellsPerColumn for capacity # experiments. "cellsPerColumn": 8, "initialPermanence": 0.5, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, # We will force client to override these "columnDimensions": "Sorry", "minThreshold": "Sorry", "maxNewSynapseCount": "Sorry", "activationThreshold": "Sorry", } DEFAULT_TP_PARAMS = { # Need to check these parameters and find stable values that will be # consistent across most experiments. "synPermInactiveDec": 0, # TODO: Check we can use class default here. "synPermActiveInc": 0.001, # TODO: Check we can use class default here. "synPredictedInc": 0.5, # TODO: Why so high?? "initConnectedPct": 0.2, # TODO: need to check impact of this for pooling # We will force client to override these "numActiveColumnsPerInhArea": "Sorry", } def __init__(self, tmOverrides=None, tpOverrides=None, seed=42, verbosity=0): # Initialize Layer 4 temporal memory params = dict(self.DEFAULT_TM_PARAMS) params.update(tmOverrides or {}) self._checkParams(params) self.tm = MonitoredGeneralTemporalMemory(__name__="TM", **params) # Initialize Layer 3 temporal pooler params = dict(self.DEFAULT_TP_PARAMS) params["inputDimensions"] = [self.tm.connections.numberOfCells()] params["potentialRadius"] = self.tm.connections.numberOfCells() params.update(tpOverrides or {}) self._checkParams(params) self.tp = MonitoredTemporalPooler(__name__="TP", **params) def _checkParams(self, params): for k,v in params.iteritems(): if v == "Sorry": raise RuntimeError("Param "+k+" must be specified") def feedLayers(self, sequences, tmLearn, tpLearn=None, verbosity=0): """ Feed the given sequences to the HTM algorithms. @param tmLearn: (bool) Either False, or True @param tpLearn: (None,bool) Either None, False, or True. If None, temporal pooler will be skipped. """ (sensorSequence, motorSequence, sensorimotorSequence, sequenceLabels) = sequences self.tm.clearHistory() for i in xrange(len(sensorSequence)): sensorPattern = sensorSequence[i] sensorimotorPattern = sensorimotorSequence[i] sequenceLabel = sequenceLabels[i] if sensorPattern is None: self.tm.reset() else: # Feed the TM self.tm.compute(sensorPattern, activeExternalCells=sensorimotorPattern, formInternalConnections=False, learn=tmLearn, sequenceLabel=sequenceLabel) # If requested, feed the TP if tpLearn is not None: tpInputVector, burstingColumns, correctlyPredictedCells = ( self.formatInputForTP()) activeArray = numpy.zeros(self.tp.getNumColumns()) self.tp.compute(tpInputVector, True, activeArray, burstingColumns, correctlyPredictedCells, sequenceLabel=sequenceLabel) if verbosity >= 2: traces = [] traces += self.tm.getDefaultTraces(verbosity=verbosity) if tpLearn is not None: traces += self.tp.getDefaultTraces(verbosity=verbosity) print MonitorMixinBase.prettyPrintTraces( traces, breakOnResets=self.tm.getTraceResets()) print @staticmethod def generateSequences(length, agents, verbosity=0): """ @param length (int) Length of each sequence to generate, one for each agent @param agents (AbstractAgent) Agents acting in their worlds @return (tuple) (sensor sequence, motor sequence, sensorimotor sequence, sequence labels) """ sensorSequence = [] motorSequence = [] sensorimotorSequence = [] sequenceLabels = [] for agent in agents: s,m,sm = agent.generateSensorimotorSequence(length, verbosity=verbosity) sensorSequence += s motorSequence += m sensorimotorSequence += sm sequenceLabels += [str(agent.world)] * length sensorSequence.append(None) motorSequence.append(None) sensorimotorSequence.append(None) sequenceLabels.append(None) return (sensorSequence, motorSequence, sensorimotorSequence, sequenceLabels) def formatInputForTP(self): """ Given an instance of the TM, format the information we need to send to the TP. """ # all currently active cells in layer 4 tpInputVector = numpy.zeros( self.tm.connections.numberOfCells()).astype(realDType) tpInputVector[list(self.tm.activeCells)] = 1 # bursting columns in layer 4 burstingColumns = numpy.zeros( self.tm.connections.numberOfColumns()).astype(realDType) burstingColumns[ list(self.tm.getTraceUnpredictedActiveColumns().data[-1])] = 1 # correctly predicted cells in layer 4 correctlyPredictedCells = numpy.zeros( self.tm.connections.numberOfCells()).astype(realDType) correctlyPredictedCells[ list(self.tm.getTracePredictedActiveCells().data[-1])] = 1 return (tpInputVector, burstingColumns, correctlyPredictedCells) def formatRow(self, x, formatString = "%d", rowSize = 700): """ Utility routine for pretty printing large vectors """ s = '' for c,v in enumerate(x): if c > 0 and c % 7 == 0: s += ' ' if c > 0 and c % rowSize == 0: s += '\n' s += formatString % v s += ' ' return s Fix bug in sensorimotor experiment runner # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import numpy from nupic.bindings.math import GetNTAReal from nupic.research.monitor_mixin.monitor_mixin_base import MonitorMixinBase from nupic.research.monitor_mixin.temporal_memory_monitor_mixin import ( TemporalMemoryMonitorMixin) from sensorimotor.general_temporal_memory import GeneralTemporalMemory from sensorimotor.temporal_pooler import TemporalPooler from sensorimotor.temporal_pooler_monitor_mixin import ( TemporalPoolerMonitorMixin) class MonitoredGeneralTemporalMemory(TemporalMemoryMonitorMixin, GeneralTemporalMemory): pass class MonitoredTemporalPooler(TemporalPoolerMonitorMixin, TemporalPooler): pass """ Experiment runner class for running networks with layer 4 and layer 3. The client is responsible for setting up universes, agents, and worlds. This class just sets up and runs the HTM learning algorithms. """ realDType = GetNTAReal() class SensorimotorExperimentRunner(object): DEFAULT_TM_PARAMS = { # These should be decent for most experiments, shouldn't need to override # these too often. Might want to increase cellsPerColumn for capacity # experiments. "cellsPerColumn": 8, "initialPermanence": 0.5, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, # We will force client to override these "columnDimensions": "Sorry", "minThreshold": "Sorry", "maxNewSynapseCount": "Sorry", "activationThreshold": "Sorry", } DEFAULT_TP_PARAMS = { # Need to check these parameters and find stable values that will be # consistent across most experiments. "synPermInactiveDec": 0, # TODO: Check we can use class default here. "synPermActiveInc": 0.001, # TODO: Check we can use class default here. "synPredictedInc": 0.5, # TODO: Why so high?? "initConnectedPct": 0.2, # TODO: need to check impact of this for pooling # We will force client to override these "numActiveColumnsPerInhArea": "Sorry", } def __init__(self, tmOverrides=None, tpOverrides=None, seed=42, verbosity=0): # Initialize Layer 4 temporal memory params = dict(self.DEFAULT_TM_PARAMS) params.update(tmOverrides or {}) self._checkParams(params) self.tm = MonitoredGeneralTemporalMemory(__name__="TM", **params) # Initialize Layer 3 temporal pooler params = dict(self.DEFAULT_TP_PARAMS) params["inputDimensions"] = [self.tm.connections.numberOfCells()] params["potentialRadius"] = self.tm.connections.numberOfCells() params.update(tpOverrides or {}) self._checkParams(params) self.tp = MonitoredTemporalPooler(__name__="TP", **params) def _checkParams(self, params): for k,v in params.iteritems(): if v == "Sorry": raise RuntimeError("Param "+k+" must be specified") def feedLayers(self, sequences, tmLearn, tpLearn=None, verbosity=0): """ Feed the given sequences to the HTM algorithms. @param tmLearn: (bool) Either False, or True @param tpLearn: (None,bool) Either None, False, or True. If None, temporal pooler will be skipped. """ (sensorSequence, motorSequence, sensorimotorSequence, sequenceLabels) = sequences self.tm.clearHistory() for i in xrange(len(sensorSequence)): sensorPattern = sensorSequence[i] sensorimotorPattern = sensorimotorSequence[i] sequenceLabel = sequenceLabels[i] if sensorPattern is None: self.tm.reset() else: # Feed the TM self.tm.compute(sensorPattern, activeExternalCells=sensorimotorPattern, formInternalConnections=False, learn=tmLearn, sequenceLabel=sequenceLabel) # If requested, feed the TP if tpLearn is not None: tpInputVector, burstingColumns, correctlyPredictedCells = ( self.formatInputForTP()) activeArray = numpy.zeros(self.tp.getNumColumns()) self.tp.compute(tpInputVector, tpLearn, activeArray, burstingColumns, correctlyPredictedCells, sequenceLabel=sequenceLabel) if verbosity >= 2: traces = [] traces += self.tm.getDefaultTraces(verbosity=verbosity) if tpLearn is not None: traces += self.tp.getDefaultTraces(verbosity=verbosity) print MonitorMixinBase.prettyPrintTraces( traces, breakOnResets=self.tm.getTraceResets()) print @staticmethod def generateSequences(length, agents, verbosity=0): """ @param length (int) Length of each sequence to generate, one for each agent @param agents (AbstractAgent) Agents acting in their worlds @return (tuple) (sensor sequence, motor sequence, sensorimotor sequence, sequence labels) """ sensorSequence = [] motorSequence = [] sensorimotorSequence = [] sequenceLabels = [] for agent in agents: s,m,sm = agent.generateSensorimotorSequence(length, verbosity=verbosity) sensorSequence += s motorSequence += m sensorimotorSequence += sm sequenceLabels += [str(agent.world)] * length sensorSequence.append(None) motorSequence.append(None) sensorimotorSequence.append(None) sequenceLabels.append(None) return (sensorSequence, motorSequence, sensorimotorSequence, sequenceLabels) def formatInputForTP(self): """ Given an instance of the TM, format the information we need to send to the TP. """ # all currently active cells in layer 4 tpInputVector = numpy.zeros( self.tm.connections.numberOfCells()).astype(realDType) tpInputVector[list(self.tm.activeCells)] = 1 # bursting columns in layer 4 burstingColumns = numpy.zeros( self.tm.connections.numberOfColumns()).astype(realDType) burstingColumns[ list(self.tm.getTraceUnpredictedActiveColumns().data[-1])] = 1 # correctly predicted cells in layer 4 correctlyPredictedCells = numpy.zeros( self.tm.connections.numberOfCells()).astype(realDType) correctlyPredictedCells[ list(self.tm.getTracePredictedActiveCells().data[-1])] = 1 return (tpInputVector, burstingColumns, correctlyPredictedCells) def formatRow(self, x, formatString = "%d", rowSize = 700): """ Utility routine for pretty printing large vectors """ s = '' for c,v in enumerate(x): if c > 0 and c % 7 == 0: s += ' ' if c > 0 and c % rowSize == 0: s += '\n' s += formatString % v s += ' ' return s
from bs4 import BeautifulSoup import urllib import re import math import html5lib from html5lib import treebuilders import urlparse def print_parameter_tabel(parameters): def cs(string, length=30): return (string[0+i:length+i] for i in range(0, len(string), length)) def houndred(x): return int(math.ceil(x / 100.0)) * 100 items = parameters for number,item in enumerate(items): name=item name += str(" " * int(29- len(name[0])))+ "|" print("+" + "-" * 32 + "+" ) print(str ( "|" + str(number)+ ") " + "".join(name)) ) print("+" + "-" * 32 + "+" ) def correct_hypertext_scheme(site): if 'https://' in site: pass elif 'http://' in site: pass else: site = "http://"+site return site finalurl = urlparse.urlparse(site) domain = '{uri.scheme}://{uri.netloc}/'.format(uri=finalurl) def find_parameters(site): correct_hypertext_scheme(site) parameters = [] url = correct_hypertext_scheme(site) mhtml = urllib.urlopen(url) soup = BeautifulSoup(mhtml, 'html5lib') inputs = soup.findAll("input", {'type':'text'}) print("[+] No parameters in your url detected, but here are some input fields the page has") if len(inputs) > 0: for elem in inputs: parameter = elem['name'] parameters.append([parameter]) print("[+] Please fill in those fields and see if you can get a url with parameters included ") print_parameter_tabel(parameters) else: print("[+] No input entery points found on this page...") def run(): url_choise = raw_input("[+] Please enter a url ") find_parameters(url_choise) #Todo: find out if there are no parameters in the url # put it all in a class if __name__ == "__main__": run() Delete input_scanner.py
########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # # # # AmCAT is free software: you can redistribute it and/or modify it under # # the terms of the GNU Affero General Public License as published by the # # Free Software Foundation, either version 3 of the License, or (at your # # option) any later version. # # # # AmCAT is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public # # License for more details. # # # # You should have received a copy of the GNU Affero General Public # # License along with AmCAT. If not, see <http://www.gnu.org/licenses/>. # ########################################################################### from django.template.loader import render_to_string import time from amcat.models import Project import api.webscripts from django.db import connection import json from amcat.scripts import scriptmanager, types from django.http import HttpResponse from amcat.scripts.forms import SelectionForm from amcat.forms import InvalidFormException from django.contrib.auth.models import User from amcat.amcatcelery import app from django.http import QueryDict from amcat.tools.djangotoolkit import to_querydict import logging log = logging.getLogger(__name__) mimetypeDict = { #todo: make objects of these 'json':{'extension':'json', 'mime':'text/plain', 'download':False}, 'csv':{'extension':'csv', 'mime':'text/csv', 'download':True}, 'comma-csv':{'extension':'csv', 'mime':'text/csv', 'download':True}, 'excel':{'extension':'xlsx', 'mime':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'download':True}, 'html':{'extension':'html', 'mime':'text/html', 'download':False}, 'spss':{'extension':'sav', 'mime':'application/octet-stream', 'download':True}, 'datatables':{'extension':'json', 'mime':'text/plain', 'download':False}, } @app.task() def webscript_task(cls, **kwargs): return cls(**kwargs).run() class WebScript(object): """ A WebScript is a combination of Scripts, with no input and a Django HttpResponse as output """ name = None # the name of this webscript form_template = None # special markup to display the form, filename form = None # fields specific for this webscript displayLocation = None # should be (a list of) another WebScript name that is displayed in the main form id = None # id used in webforms output_template = None # path to template used for html output solrOnly = False # only for Solr output, not on database queries def __init__(self, project=None, user=None, data=None, **kwargs): if not isinstance(data, QueryDict) and data is not None: data = to_querydict(data, mutable=True) self.initTime = time.time() self.data = data self.output = data.get('output', 'json') self.kwargs = kwargs self.project = project = Project.objects.get(id=project) if isinstance(project, int) else project self.user = User.objects.get(id=user) if isinstance(user, int) else user if self.form: try: form = self.form(project=project, data=data, **kwargs) except TypeError: form = self.form(data=data, **kwargs) if not form.is_valid(): raise InvalidFormException("Invalid or missing options: %r" % form.errors, form.errors) self.options = form.cleaned_data self.formInstance = form else: self.options = None self.formInstance = None @classmethod def formHtml(cls, project=None): if cls.form == None: return '' try: form = cls.form(project=project) except TypeError: log.exception("Could not instantiate {cls.__name__}.form(project={project}".format(**locals())) form = cls.form() return render_to_string(cls.form_template, {'form':form}) if cls.form_template else form.as_p() def getActions(self): for ws in api.webscripts.actionScripts: if self.__class__.__name__ in ws.displayLocation and (ws.solrOnly == False or self.data.get('query')): yield ws.__name__, ws.name def delay(self): return webscript_task.delay(self.__class__, project=self.project.id, user=self.user.id, data=self.data, **self.kwargs) def run(self): raise NotImplementedError() def get_result(self, result): # Webscripts return an HttpResponse object, which we need te contents of return result.content def get_response(self, result): return result def outputJsonHtml(self, scriptoutput): actions = self.getActions() webscriptform = None if self.form: try: webscriptform = self.form(project=self.project, data=self.data) except TypeError: webscriptform = self.form(data=self.data) selectionform = SelectionForm(project=self.project, data=self.data) html = render_to_string('navigator/selection/webscriptoutput.html', { 'scriptoutput':scriptoutput, 'actions': actions, 'selectionform':selectionform, 'webscriptform':webscriptform }) reply = {} reply['html'] = html reply['queries'] = getQueries() reply['querytime'] = '%.2f' % (time.time() - self.initTime) reply['webscriptName'] = self.name reply['webscriptClassname'] = self.__class__.__name__ jsondata = json.dumps(reply, default=lambda o:unicode(o)) return HttpResponse(jsondata, mimetype='text/plain') def outputResponse(self, data, data_type, filename=None): outputFormData = self.data.copy() # need copy, else it's unmutable outputFormData['template'] = self.output_template if self.output == 'json-html': # special output that runs the webscript with html output, # then wraps around this the action buttons and other stuff for the amcat navigator website if data_type == unicode: scriptoutput = data else: cls = scriptmanager.findScript(data_type, 'html') if not cls: raise Exception('html output not supported') scriptoutput = cls(outputFormData).run(data) return self.outputJsonHtml(scriptoutput) else: cls = scriptmanager.findScript(data_type, self.output) if not cls: raise Exception('invalid output type') #cnf = {'template':self.output_template} if self.output == 'html' else None mimetype = mimetypeDict[self.output] out = cls(outputFormData).run(data) response = HttpResponse(mimetype=mimetype['mime']) response.write(out) if filename or mimetype['download'] == True: if not filename: filename = 'AmCAT %s' % self.name response['Content-Disposition'] = 'attachment; filename="%s.%s"' % (filename, mimetype['extension']) return response def getQueries(): return [(x.get('time') or x.get('duration'), x['sql']) for x in connection.queries] def showErrorMsg(text, outputType, fields=None): errormsg = types.ErrorMsg(text, fields=fields) cls = scriptmanager.findScript(types.ErrorMsg, outputType) output = cls().run(errormsg) if cls else text return HttpResponse(output, mimetype='text/plain') stub code for progress ########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # # # # AmCAT is free software: you can redistribute it and/or modify it under # # the terms of the GNU Affero General Public License as published by the # # Free Software Foundation, either version 3 of the License, or (at your # # option) any later version. # # # # AmCAT is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public # # License for more details. # # # # You should have received a copy of the GNU Affero General Public # # License along with AmCAT. If not, see <http://www.gnu.org/licenses/>. # ########################################################################### from django.template.loader import render_to_string import time from amcat.models import Project import api.webscripts from django.db import connection import json from amcat.scripts import scriptmanager, types from django.http import HttpResponse from amcat.scripts.forms import SelectionForm from amcat.forms import InvalidFormException from django.contrib.auth.models import User from amcat.amcatcelery import app from django.http import QueryDict from amcat.tools.djangotoolkit import to_querydict import logging log = logging.getLogger(__name__) mimetypeDict = { #todo: make objects of these 'json':{'extension':'json', 'mime':'text/plain', 'download':False}, 'csv':{'extension':'csv', 'mime':'text/csv', 'download':True}, 'comma-csv':{'extension':'csv', 'mime':'text/csv', 'download':True}, 'excel':{'extension':'xlsx', 'mime':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'download':True}, 'html':{'extension':'html', 'mime':'text/html', 'download':False}, 'spss':{'extension':'sav', 'mime':'application/octet-stream', 'download':True}, 'datatables':{'extension':'json', 'mime':'text/plain', 'download':False}, } @app.task(bind=True) def webscript_task(self, cls, **kwargs): task_id = self.request.id # TODO: Dit moet weg, stub code om status door te geven app.backend.store_result(task_id, {"completed": 42, "message": "ben bezig joh"}, 'INPROGRESS') import time; time.sleep(2) return cls(**kwargs).run() class WebScript(object): """ A WebScript is a combination of Scripts, with no input and a Django HttpResponse as output """ name = None # the name of this webscript form_template = None # special markup to display the form, filename form = None # fields specific for this webscript displayLocation = None # should be (a list of) another WebScript name that is displayed in the main form id = None # id used in webforms output_template = None # path to template used for html output solrOnly = False # only for Solr output, not on database queries def __init__(self, project=None, user=None, data=None, **kwargs): if not isinstance(data, QueryDict) and data is not None: data = to_querydict(data, mutable=True) self.initTime = time.time() self.data = data self.output = data.get('output', 'json') self.kwargs = kwargs self.project = project = Project.objects.get(id=project) if isinstance(project, int) else project self.user = User.objects.get(id=user) if isinstance(user, int) else user if self.form: try: form = self.form(project=project, data=data, **kwargs) except TypeError: form = self.form(data=data, **kwargs) if not form.is_valid(): raise InvalidFormException("Invalid or missing options: %r" % form.errors, form.errors) self.options = form.cleaned_data self.formInstance = form else: self.options = None self.formInstance = None @classmethod def formHtml(cls, project=None): if cls.form == None: return '' try: form = cls.form(project=project) except TypeError: log.exception("Could not instantiate {cls.__name__}.form(project={project}".format(**locals())) form = cls.form() return render_to_string(cls.form_template, {'form':form}) if cls.form_template else form.as_p() def getActions(self): for ws in api.webscripts.actionScripts: if self.__class__.__name__ in ws.displayLocation and (ws.solrOnly == False or self.data.get('query')): yield ws.__name__, ws.name def delay(self): d = webscript_task.delay(self.__class__, project=self.project.id, user=self.user.id, data=self.data, **self.kwargs) # TODO: Dit moet weg, suffe check om te kijken of result er staat import time; time.sleep(.5) print("@@@HACK", d.state, d.result) return d def run(self): raise NotImplementedError() def get_result(self, result): # Webscripts return an HttpResponse object, which we need te contents of return result.content def get_response(self, result): return result def outputJsonHtml(self, scriptoutput): actions = self.getActions() webscriptform = None if self.form: try: webscriptform = self.form(project=self.project, data=self.data) except TypeError: webscriptform = self.form(data=self.data) selectionform = SelectionForm(project=self.project, data=self.data) html = render_to_string('navigator/selection/webscriptoutput.html', { 'scriptoutput':scriptoutput, 'actions': actions, 'selectionform':selectionform, 'webscriptform':webscriptform }) reply = {} reply['html'] = html reply['queries'] = getQueries() reply['querytime'] = '%.2f' % (time.time() - self.initTime) reply['webscriptName'] = self.name reply['webscriptClassname'] = self.__class__.__name__ jsondata = json.dumps(reply, default=lambda o:unicode(o)) return HttpResponse(jsondata, mimetype='text/plain') def outputResponse(self, data, data_type, filename=None): outputFormData = self.data.copy() # need copy, else it's unmutable outputFormData['template'] = self.output_template if self.output == 'json-html': # special output that runs the webscript with html output, # then wraps around this the action buttons and other stuff for the amcat navigator website if data_type == unicode: scriptoutput = data else: cls = scriptmanager.findScript(data_type, 'html') if not cls: raise Exception('html output not supported') scriptoutput = cls(outputFormData).run(data) return self.outputJsonHtml(scriptoutput) else: cls = scriptmanager.findScript(data_type, self.output) if not cls: raise Exception('invalid output type') #cnf = {'template':self.output_template} if self.output == 'html' else None mimetype = mimetypeDict[self.output] out = cls(outputFormData).run(data) response = HttpResponse(mimetype=mimetype['mime']) response.write(out) if filename or mimetype['download'] == True: if not filename: filename = 'AmCAT %s' % self.name response['Content-Disposition'] = 'attachment; filename="%s.%s"' % (filename, mimetype['extension']) return response def getQueries(): return [(x.get('time') or x.get('duration'), x['sql']) for x in connection.queries] def showErrorMsg(text, outputType, fields=None): errormsg = types.ErrorMsg(text, fields=fields) cls = scriptmanager.findScript(types.ErrorMsg, outputType) output = cls().run(errormsg) if cls else text return HttpResponse(output, mimetype='text/plain')
# -*- coding: utf-8 -*- """Poker hand history parser module. It only parses PokerStars and Full Tilt Poker Tournament hands, but the plan is to parse a lot. """ import re from abc import ABCMeta, abstractmethod from collections import MutableMapping, OrderedDict from inspect import ismethod from decimal import Decimal from datetime import datetime import locale import pytz locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # need for abbreviated month names _NORMALIZE = {'STARS': {'pokerstars', 'stars', 'ps'}, 'FTP': {'full tilt poker', 'full tilt', 'ftp'}, 'PKR': {'pkr', 'pkr poker'}, 'USD': {'usd', u'$'}, 'EUR': {'eur', u'€'}, 'GBP': {'gbp', u'£'}, 'TOUR': {'tournament', 'tour'}, 'CASH': {'cash game', 'ring', 'cash'}, 'HOLDEM': {"hold'em", 'holdem'}, 'OMAHA': {'omaha'}, 'NL': {'no limit', 'nl'}, 'PL': {'pot limit', 'pl'}, 'FL': {'fix limit', 'fl'}, 'R': {'real money'}, 'P': {'play money'}} def normalize(value): """Normalize common words which can be in multiple form, but all means the same.""" value = value.lower() for normalized, compare in _NORMALIZE.iteritems(): if value in compare: return normalized return value.upper() class PokerHand(MutableMapping): """Abstract base class for parsers. The attributes can be iterated The class can read like a dictionary. Every attribute default value is None. Public attributes: poker_room -- room ID (4 byte max) ex. STARS, FTP ident -- hand id game_type -- TOUR for tournaments or SNG for Sit&Go-s tournament_ident -- tournament id tournament_level currency -- 3 letter iso code USD, HUF, EUR, etc. buyin -- buyin without rake rake -- if game_type is TOUR it's buyin rake, if CASH it's rake from pot game -- game type: HOLDEM, OMAHA, STUD, RAZZ, etc. limit -- NL, PL or FL sb -- amount of small blind bb -- amount of big blind date -- hand date in UTC table_name -- name of the table. it's 'tournament number[ ]table number' max_player -- maximum players can sit on the table, 2, 4, 6, 7, 8, 9 button_seat -- seat of button player, starting from 1 button -- player name on the button hero -- name of hero hero_seat (int) -- seat of hero, starting from 1 players -- OrderedDict of tuples in form (playername, starting_stack) the sequence is the seating order at the table at the start of the hand hero_hole_cards -- tuple of two cards, ex. ('Ah', 'As') flop -- tuple of flop cards, ex. ('Ah', '2s', '2h') turn -- str of turn card, ex. 'Ah' river -- str of river card, ex. '2d' board -- tuple of board cards, ex. ('4s', 4d', '4c', '5h') preflop actions -- tuple of action lines in str flop_actions -- tuple of flop action lines turn_actions river_actions total_pot -- total pot after end of actions (rake included) show_down -- There was showd_down or wasn't (bool) winners -- tuple of winner names, even when there is only one winner. ex. ('W2lkm2n') """ __metaclass__ = ABCMeta _non_hand_attributes = ('raw', 'parsed', 'header_parsed', 'date_format') @abstractmethod def __init__(self, hand_text, parse=True): """Save raw hand history. Parameters: hand_text -- str of poker hand parse -- if False, hand will not parsed immediately. Useful if you just want to quickly check header first. """ self.raw = hand_text.strip() self.header_parsed = False self.parsed = False def __len__(self): return len(self.keys()) def __getitem__(self, key): if key not in self._non_hand_attributes: return getattr(self, key) else: raise KeyError('You can only get it via the attribute like "hand.%s"' % key) def __setitem__(self, key, value): setattr(self, key, value) def __delitem__(self, key): delattr(self, key) def __iter__(self): return iter(self.keys()) def __unicode__(self): return "<%s: %s hand #%s>" % (self.__class__.__name__, self.poker_room, self.ident) def __str__(self): return unicode(self).encode('utf-8') def keys(self): return [attr for attr in dir(self) if not attr.startswith('_') and attr not in self._non_hand_attributes and not ismethod(getattr(self, attr))] @abstractmethod def parse_header(self): """Parses the first line of a hand history.""" pass @abstractmethod def parse(self): """Parse the body of the hand history, but first parse header if not yet parsed.""" if not self.header_parsed: self.parse_header() @property def board(self): board = [] if self.flop: board.extend(self.flop) if self.turn: board.append(self.turn) if self.river: board.append(self.river) return tuple(board) if board else None def _parse_date(self, date_string): date = datetime.strptime(date_string, self.date_format) self.date = self._time_zone.localize(date).astimezone(pytz.UTC) def _init_seats(self, player_num): return [('Empty Seat %s' % num, Decimal(0)) for num in range(1, player_num + 1)] class PokerStarsHand(PokerHand): """Parses PokerStars Tournament hands. Class specific attributes: poker_room -- STARS """ poker_room = 'STARS' date_format = '%Y/%m/%d %H:%M:%S ET' _time_zone = pytz.timezone('US/Eastern') # ET _split_pattern = re.compile(r" ?\*\*\* ?\n?|\n") _header_pattern = re.compile(r""" ^PokerStars[ ] # Poker Room Hand[ ]\#(?P<ident>\d*):[ ] # Hand number (?P<game_type>Tournament)[ ] # Type \#(?P<tournament_ident>\d*),[ ] # Tournament Number \$(?P<buyin>\d*\.\d{2})\+ # buyin \$(?P<rake>\d*\.\d{2})[ ] # rake (?P<currency>USD|EUR)[ ] # currency (?P<game>.*)[ ] # game (?P<limit>No[ ]Limit)[ ] # limit -[ ]Level[ ](?P<tournament_level>.*)[ ] # Level \((?P<sb>.*)/(?P<bb>.*)\)[ ] # blinds -[ ].*[ ] # localized date \[(?P<date>.*)\]$ # ET date """, re.VERBOSE) _table_pattern = re.compile(r"^Table '(.*)' (\d)-max Seat #(\d) is the button$") _seat_pattern = re.compile(r"^Seat (\d): (.*) \((\d*) in chips\)$") _hole_cards_pattern = re.compile(r"^Dealt to (.*) \[(..) (..)\]$") _pot_pattern = re.compile(r"^Total pot (\d*) .*\| Rake (\d*)$") _winner_pattern = re.compile(r"^Seat (\d): (.*) collected \((\d*)\)$") _showdown_pattern = re.compile(r"^Seat (\d): (.*) showed .* and won") _ante_pattern = re.compile(r".*posts the ante (\d*)") _board_pattern = re.compile(r"(?<=[\[ ])(..)(?=[\] ])") def __init__(self, hand_text, parse=True): """Split hand history by sections and parse.""" super(PokerStarsHand, self).__init__(hand_text, parse) self._splitted = self._split_pattern.split(self.raw) # search split locations (basically empty strings) # sections[0] is before HOLE CARDS # sections[-1] is before SUMMARY self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] if parse: self.parse() def parse_header(self): match = self._header_pattern.match(self._splitted[0]) self.game_type = normalize(match.group('game_type')) self.sb = Decimal(match.group('sb')) self.bb = Decimal(match.group('bb')) self.buyin = Decimal(match.group('buyin')) self.rake = Decimal(match.group('rake')) self._parse_date(match.group('date')) self.game = normalize(match.group('game')) self.limit = normalize(match.group('limit')) self.ident = match.group('ident') self.tournament_ident = match.group('tournament_ident') self.tournament_level = match.group('tournament_level') self.currency = match.group('currency') self.header_parsed = True def parse(self): super(PokerStarsHand, self).parse() self._parse_table() self._parse_seats() self._parse_hole_cards() self._parse_preflop() self._parse_street('flop') self._parse_street('turn') self._parse_street('river') self.show_down = "SHOW DOWN" in self._splitted self._parse_pot() self._parse_board() self._parse_winners() self.parsed = True def _parse_table(self): match = self._table_pattern.match(self._splitted[1]) self.table_name = match.group(1) self.max_players = int(match.group(2)) self.button_seat = int(match.group(3)) def _parse_seats(self): players = self._init_seats(self.max_players) for line in self._splitted[2:]: match = self._seat_pattern.match(line) if not match: break players[int(match.group(1)) - 1] = (match.group(2), int(match.group(3))) self.button = players[self.button_seat - 1][0] self.players = OrderedDict(players) def _parse_hole_cards(self): hole_cards_line = self._splitted[self._sections[0] + 2] match = self._hole_cards_pattern.match(hole_cards_line) self.hero = match.group(1) self.hero_seat = self.players.keys().index(self.hero) + 1 self.hero_hole_cards = match.group(2, 3) def _parse_preflop(self): start = self._sections[0] + 3 stop = self._sections[1] self.preflop_actions = tuple(self._splitted[start:stop]) def _parse_street(self, street): try: start = self._splitted.index(street.upper()) + 2 stop = self._splitted.index('', start) street_actions = self._splitted[start:stop] setattr(self, "%s_actions" % street.lower(), tuple(street_actions) if street_actions else None) except ValueError: setattr(self, street, None) setattr(self, '%s_actions' % street.lower(), None) def _parse_pot(self): potline = self._splitted[self._sections[-1] + 2] match = self._pot_pattern.match(potline) self.total_pot = int(match.group(1)) def _parse_board(self): boardline = self._splitted[self._sections[-1] + 3] if not boardline.startswith('Board'): return cards = self._board_pattern.findall(boardline) self.flop = tuple(cards[:3]) if cards else None self.turn = cards[3] if len(cards) > 3 else None self.river = cards[4] if len(cards) > 4 else None def _parse_winners(self): winners = set() start = self._sections[-1] + 4 for line in self._splitted[start:]: if not self.show_down and "collected" in line: match = self._winner_pattern.match(line) winners.add(match.group(2)) elif self.show_down and "won" in line: match = self._showdown_pattern.match(line) winners.add(match.group(2)) self.winners = tuple(winners) class FullTiltHand(PokerHand): """Parses Full Tilt Poker hands the same way as PokerStarsHand class. PokerStars and Full Tilt hand histories are very similar, so parsing them is almost identical. There are small differences though. Class specific attributes: poker_room -- FTP tournament_level -- None buyin -- None rake -- None currency -- None table_name -- just a number, but str type Extra attributes: flop_pot -- pot size on the flop, before actions flop_num_players -- number of players seen the flop turn_pot -- pot size before turn turn_num_players -- number of players seen the turn river_pot -- pot size before river river_num_players -- number of players seen the river tournament_name -- ex. "$750 Guarantee", "$5 Sit & Go (Super Turbo)" """ poker_room = 'FTP' date_format = '%H:%M:%S ET - %Y/%m/%d' _time_zone = pytz.timezone('US/Eastern') # ET _split_pattern = re.compile(r" ?\*\*\* ?\n?|\n") # header patterns _tournament_pattern = re.compile(r""" ^Full[ ]Tilt[ ]Poker[ ] # Poker Room Game[ ]\#(?P<ident>\d*):[ ] # Hand number (?P<tournament_name>.*)[ ] # Tournament name \((?P<tournament_ident>\d*)\),[ ] # Tournament Number Table[ ](?P<table_name>\d*)[ ]-[ ] # Table name """, re.VERBOSE) _game_pattern = re.compile(r" - (?P<limit>NL|PL|FL|No Limit|Pot Limit|Fix Limit) (?P<game>.*?) - ") _blind_pattern = re.compile(r" - (\d*)/(\d*) - ") _date_pattern = re.compile(r" \[(.*)\]$") _seat_pattern = re.compile(r"^Seat (\d): (.*) \(([\d,]*)\)$") _button_pattern = re.compile(r"^The button is in seat #(\d)$") _hole_cards_pattern = re.compile(r"^Dealt to (.*) \[(..) (..)\]$") _street_pattern = re.compile(r"\[([^\]]*)\] \(Total Pot: (\d*)\, (\d) Players") _pot_pattern = re.compile(r"^Total pot ([\d,]*) .*\| Rake (\d*)$") _winner_pattern = re.compile(r"^Seat (\d): (.*) collected \((\d*)\),") _showdown_pattern = re.compile(r"^Seat (\d): (.*) showed .* and won") def __init__(self, hand_text, parse=True): super(FullTiltHand, self).__init__(hand_text, parse) self._splitted = self._split_pattern.split(self.raw) # search split locations (basically empty strings) # sections[0] is before HOLE CARDS # sections[-1] is before SUMMARY self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] if parse: self.parse() def parse_header(self): header_line = self._splitted[0] match = self._tournament_pattern.match(header_line) self.game_type = 'TOUR' self.ident = match.group('ident') self.tournament_name = match.group('tournament_name') self.tournament_ident = match.group('tournament_ident') self.table_name = match.group('table_name') match = self._game_pattern.search(header_line) self.limit = normalize(match.group('limit')) self.game = normalize(match.group('game')) match = self._blind_pattern.search(header_line) self.sb = Decimal(match.group(1)) self.bb = Decimal(match.group(2)) match = self._date_pattern.search(header_line) self._parse_date(match.group(1)) self.tournament_level = self.buyin = self.rake = self.currency = None self.header_parsed = True def parse(self): super(FullTiltHand, self).parse() self._parse_seats() self._parse_hole_cards() self._parse_preflop() self._parse_street('flop') self._parse_street('turn') self._parse_street('river') self.show_down = 'SHOW DOWN' in self._splitted self._parse_pot() self._parse_winners() self.parsed = True def _parse_seats(self): # In hh there is no indication of max_players, so init for 9. players = self._init_seats(9) for line in self._splitted[1:]: match = self._seat_pattern.match(line) if not match: break seat_number = int(match.group(1)) player_name = match.group(2) stack = int(match.group(3).replace(',', '')) players[seat_number - 1] = (player_name, stack) self.max_players = seat_number self.players = OrderedDict(players[:self.max_players]) # cut off unneccesary seats # one line before the first split. button_line = self._splitted[self._sections[0] - 1] self.button_seat = int(self._button_pattern.match(button_line).group(1)) self.button = players[self.button_seat - 1][0] def _parse_hole_cards(self): hole_cards_line = self._splitted[self._sections[0] + 2] match = self._hole_cards_pattern.match(hole_cards_line) self.hero = match.group(1) self.hero_seat = self.players.keys().index(self.hero) + 1 self.hero_hole_cards = match.group(2, 3) def _parse_preflop(self): start = self._sections[0] + 3 stop = self._sections[1] self.preflop_actions = tuple(self._splitted[start:stop]) def _parse_street(self, street): try: start = self._splitted.index(street.upper()) + 1 self._parse_boardline(start, street) stop = next(v for v in self._sections if v > start) street_actions = self._splitted[start + 1:stop] setattr(self, "%s_actions" % street, tuple(street_actions) if street_actions else None) except ValueError: setattr(self, street, None) setattr(self, '%s_actions' % street, None) setattr(self, '%s_pot' % street, None) setattr(self, '%s_num_players' % street, None) def _parse_boardline(self, start, street): """Parse pot, num players and cards.""" # Exceptions caught in _parse_street. board_line = self._splitted[start] match = self._street_pattern.search(board_line) cards = match.group(1) cards = tuple(cards.split()) if street == 'flop' else cards setattr(self, street, cards) pot = match.group(2) setattr(self, "%s_pot" % street, Decimal(pot)) num_players = int(match.group(3)) setattr(self, "%s_num_players" % street, num_players) def _parse_pot(self): potline = self._splitted[self._sections[-1] + 2] match = self._pot_pattern.match(potline.replace(',', '')) self.total_pot = int(match.group(1)) def _parse_winners(self): winners = set() start = self._sections[-1] + 4 for line in self._splitted[start:]: if not self.show_down and "collected" in line: match = self._winner_pattern.match(line) winners.add(match.group(2)) elif self.show_down and "won" in line: match = self._showdown_pattern.match(line) winners.add(match.group(2)) self.winners = tuple(winners) class PKRHand(PokerHand): """Parses PKR hands. Class specific attributes: poker_room -- PKR table_name -- "#table_number - name of the table" Extra attributes: last_ident -- last hand id money_type -- 'R' for real money, 'P' for play money """ poker_room = 'PKR' date_format = '%d %b %Y %H:%M:%S' currency = 'USD' _time_zone = pytz.UTC _split_pattern = re.compile(r"Dealing |\nDealing Cards\n|Taking |Moving |\n") _blinds_pattern = re.compile(r"^Blinds are now \$([\d.]*) / \$([\d.]*)$") _dealt_pattern = re.compile(r"^\[(. .)\]\[(. .)\] to (.*)$") _seat_pattern = re.compile(r"^Seat (\d\d?): (.*) - \$([\d.]*) ?(.*)$") _sizes_pattern = re.compile(r"^Pot sizes: \$([\d.]*)$") _card_pattern = re.compile(r"\[(. .)\]") _rake_pattern = re.compile(r"Rake of \$([\d.]*) from pot \d$") _win_pattern = re.compile(r"^(.*) wins \$([\d.]*) with: ") def __init__(self, hand_text, parse=True): """Split hand history by sections and parse.""" super(PKRHand, self).__init__(hand_text, parse) self._splitted = self._split_pattern.split(self.raw) # search split locations (basically empty strings) # sections[1] is after blinds, before preflop # section[2] is before flop # sections[-1] is before showdown self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] if parse: self.parse() def parse_header(self): self.table_name = self._splitted[0][6:] # cut off "Table " self.ident = self._splitted[1][15:] # cut off "Starting Hand #" self._parse_date(self._splitted[2][20:]) # cut off "Start time of hand: " self.last_ident = self._splitted[3][11:] # cut off "Last Hand #" self.game = normalize(self._splitted[4][11:]) # cut off "Game Type: " self.limit = normalize(self._splitted[5][12:]) # cut off "Limit Type: " self.game_type = normalize(self._splitted[6][12:]) # cut off "Table Type: " self.money_type = normalize(self._splitted[7][12:]) # cut off "Money Type: " match = self._blinds_pattern.match(self._splitted[8]) self.sb = Decimal(match.group(1)) self.bb = Decimal(match.group(2)) self.buyin = self.bb * 100 self.button = int(self._splitted[9][18:]) # cut off "Button is at seat " self.tournament_ident = None self.tournament_name = None self.tournament_level = None def parse(self): super(PKRHand, self).parse() self._parse_seats() self._parse_hero() self._parse_preflop() self._parse_street('flop') self._parse_street('turn') self._parse_street('river') self._parse_showdown() def _parse_seats(self): # In hh there is no indication of max_players, # so init for 10, as there are 10 player tables on PKR. players = self._init_seats(10) for line in self._splitted[10:]: match = self._seat_pattern.match(line) if not match: break seat_number = int(match.group(1)) player_name = match.group(2) stack = Decimal(match.group(3)) players[seat_number - 1] = (player_name, stack) self.max_players = seat_number self.players = OrderedDict(players[:self.max_players]) button_row = self._splitted[self._sections[0] + 1] # cut last two because there can be 10 seats also # in case of one digit, the first char will be a space # but int() can convert it without hiccups :) self.button_seat = int(button_row[-2:]) self.button = players[self.button_seat - 1][0] def _parse_hero(self): dealt_row = self._splitted[self._sections[1] + 1] match = self._dealt_pattern.match(dealt_row) first = match.group(1)[0:3:2] # split space in the middle second = match.group(2)[0:3:2] self.hero_hole_cards = (first, second) self.hero = match.group(3) self.hero_seat = self.players.keys().index(self.hero) + 1 def _parse_preflop(self): start = self._sections[1] + 2 stop = self._splitted.index('', start + 1) - 1 self.preflop_actions = tuple(self._splitted[start:stop]) def _parse_street(self, street): street_sections = {'flop': 2, 'turn': 3, 'river': 4} section = street_sections[street] try: start = self._sections[section] + 1 street_line = self._splitted[start] cards = map(lambda x: x[0:3:2], self._card_pattern.findall(street_line)) setattr(self, street, tuple(cards) if street == 'flop' else cards[0]) stop = next(v for v in self._sections if v > start) - 1 setattr(self, "%s_actions" % street, tuple(self._splitted[start + 1:stop])) sizes_line = self._splitted[start - 2] pot = Decimal(self._sizes_pattern.match(sizes_line).group(1)) setattr(self, "%s_pot" % street, pot) except IndexError: setattr(self, street, None) setattr(self, "%s_actions" % street, None) setattr(self, "%s_pot" % street, None) def _parse_showdown(self): start = self._sections[-1] + 1 rake_line = self._splitted[start] match = self._rake_pattern.match(rake_line) self.rake = Decimal(match.group(1)) winners = [] total_pot = self.rake for line in self._splitted[start:]: if 'shows' in line: self.show_down = True elif 'wins' in line: match = self._win_pattern.match(line) winners.append(match.group(1)) total_pot += Decimal(match.group(2)) self.winners = tuple(winners) self.total_pot = total_pot Restructured docstrings for automatic generation # -*- coding: utf-8 -*- """Poker hand history parser module.""" import re from abc import ABCMeta, abstractmethod from collections import MutableMapping, OrderedDict from inspect import ismethod from decimal import Decimal from datetime import datetime import locale import pytz locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # need for abbreviated month names _NORMALIZE = {'STARS': {'pokerstars', 'stars', 'ps'}, 'FTP': {'full tilt poker', 'full tilt', 'ftp'}, 'PKR': {'pkr', 'pkr poker'}, 'USD': {'usd', u'$'}, 'EUR': {'eur', u'€'}, 'GBP': {'gbp', u'£'}, 'TOUR': {'tournament', 'tour'}, 'CASH': {'cash game', 'ring', 'cash'}, 'HOLDEM': {"hold'em", 'holdem'}, 'OMAHA': {'omaha'}, 'NL': {'no limit', 'nl'}, 'PL': {'pot limit', 'pl'}, 'FL': {'fix limit', 'fl'}, 'R': {'real money'}, 'P': {'play money'}} def normalize(value): """Normalize common words which can be in multiple form, but all means the same. | For example, PKR calls "Cash game" "ring game", | or there are multiple forms of holdem like "Hold'em", "holdem", "he", etc.. :param value: the word to normalize like "No limit", "Hold'em", "Cash game" :return: Normalized form of the word like ``"NL"``, ``"HOLDEM"``, ``"CASH"``, etc. """ value = value.lower() for normalized, compare in _NORMALIZE.iteritems(): if value in compare: return normalized return value.upper() class PokerHand(MutableMapping): """Abstract base class for *all* room-specific parser. | The attributes can be iterated. | The class can read like a dictionary. | Every attribute default value is ``None``. :ivar str poker_room: room ID (4 byte max) e.g. ``"STARS"``, ``"FTP"`` :ivar str date_format: default date format for the given poker_room :ivar str ident: hand id :ivar str game_type: ``"TOUR"`` for tournaments or ``"SNG"`` for Sit&Go-s :ivar str tournament_ident: tournament id :ivar str tournament_level: level of tournament blinds :ivar str currency: 3 letter iso code ``"USD"``, ``"HUF"``, ``"EUR"``, etc. :ivar Decimal buyin: buyin **without** rake :ivar Decimal rake: if game_type is ``"TOUR"`` it's buyin rake, if ``"CASH"`` it's rake from pot :ivar str game: ``"HOLDEM"``, ``"OMAHA"``, ``"STUD"``, ``"RAZZ"``, etc. you should call :func:`normalize` to generate the correct value :ivar str limit: ``"NL"``, ``"PL"`` or ``"FL"`` :ivar Decimal sb: amount of small blind :ivar Decimal bb: amount of big blind :ivar datetime date: hand date in UTC :ivar str table_name: name of the table. it's ``"tournament_number table_number"`` :ivar int max_player: maximum players can sit on the table, 2, 4, 6, 7, 8, 9 :ivar int button_seat: seat of button player, starting from 1 :ivar str button: player name on the button :ivar unicode hero: name of hero :ivar int hero_seat: seat of hero, starting from 1 :ivar OrderedDict players: tuples in form of ``(playername, starting_stack)`` the sequence is the seating order at the table at the start of the hand :ivar tuple hero_hole_cards: two cards, e.g. ``('Ah', 'As')`` :ivar tuple flop: flop cards, e.g. ``('Ah', '2s', '2h')`` :ivar str turn: turn card, e.g. ``'Ah'`` :ivar str river: river card, e.g. ``'2d'`` :ivar tuple board: board cards, e.g. ``('4s', 4d', '4c', '5h')`` :ivar tuple preflop actions: action lines in str :ivar tuple flop_actions: flop action lines :ivar tuple turn_actions: turn action lines :ivar tuple river_actions: river action lines :ivar Decimal total_pot: total pot after end of actions (rake included) :ivar bool show_down: There was show_down or wasn't :ivar tuple winners: winner names, tuple if even when there is only one winner. e.g. ``('W2lkm2n',)`` """ __metaclass__ = ABCMeta _non_hand_attributes = ('raw', 'parsed', 'header_parsed', 'date_format') @abstractmethod def __init__(self, hand_text, parse=True): """Save raw hand history. Parameters: :param str hand_text: poker hand :param bool parse: if ``False``, hand will not parsed immediately. Useful if you just want to quickly check header first. """ self.raw = hand_text.strip() self.header_parsed = False self.parsed = False def __len__(self): return len(self.keys()) def __getitem__(self, key): if key not in self._non_hand_attributes: return getattr(self, key) else: raise KeyError('You can only get it via the attribute like "hand.%s"' % key) def __setitem__(self, key, value): setattr(self, key, value) def __delitem__(self, key): delattr(self, key) def __iter__(self): return iter(self.keys()) def __unicode__(self): return "<%s: %s hand #%s>" % (self.__class__.__name__, self.poker_room, self.ident) def __str__(self): return unicode(self).encode('utf-8') def keys(self): return [attr for attr in dir(self) if not attr.startswith('_') and attr not in self._non_hand_attributes and not ismethod(getattr(self, attr))] @abstractmethod def parse_header(self): """Parses the first line of a hand history.""" @abstractmethod def parse(self): """Parses the body of the hand history, but first parse header if not yet parsed.""" if not self.header_parsed: self.parse_header() @property def board(self): """Calculates board from flop, turn and river.""" board = [] if self.flop: board.extend(self.flop) if self.turn: board.append(self.turn) if self.river: board.append(self.river) return tuple(board) if board else None def _parse_date(self, date_string): date = datetime.strptime(date_string, self.date_format) self.date = self._time_zone.localize(date).astimezone(pytz.UTC) def _init_seats(self, player_num): return [('Empty Seat %s' % num, Decimal(0)) for num in range(1, player_num + 1)] class PokerStarsHand(PokerHand): """Parses PokerStars Tournament hands. **Class specific** :ivar str poker_room: always ``STARS`` in this class """ poker_room = 'STARS' date_format = '%Y/%m/%d %H:%M:%S ET' _time_zone = pytz.timezone('US/Eastern') # ET _split_pattern = re.compile(r" ?\*\*\* ?\n?|\n") _header_pattern = re.compile(r""" ^PokerStars[ ] # Poker Room Hand[ ]\#(?P<ident>\d*):[ ] # Hand number (?P<game_type>Tournament)[ ] # Type \#(?P<tournament_ident>\d*),[ ] # Tournament Number \$(?P<buyin>\d*\.\d{2})\+ # buyin \$(?P<rake>\d*\.\d{2})[ ] # rake (?P<currency>USD|EUR)[ ] # currency (?P<game>.*)[ ] # game (?P<limit>No[ ]Limit)[ ] # limit -[ ]Level[ ](?P<tournament_level>.*)[ ] # Level \((?P<sb>.*)/(?P<bb>.*)\)[ ] # blinds -[ ].*[ ] # localized date \[(?P<date>.*)\]$ # ET date """, re.VERBOSE) _table_pattern = re.compile(r"^Table '(.*)' (\d)-max Seat #(\d) is the button$") _seat_pattern = re.compile(r"^Seat (\d): (.*) \((\d*) in chips\)$") _hole_cards_pattern = re.compile(r"^Dealt to (.*) \[(..) (..)\]$") _pot_pattern = re.compile(r"^Total pot (\d*) .*\| Rake (\d*)$") _winner_pattern = re.compile(r"^Seat (\d): (.*) collected \((\d*)\)$") _showdown_pattern = re.compile(r"^Seat (\d): (.*) showed .* and won") _ante_pattern = re.compile(r".*posts the ante (\d*)") _board_pattern = re.compile(r"(?<=[\[ ])(..)(?=[\] ])") def __init__(self, hand_text, parse=True): """Split hand history by sections and parse.""" super(PokerStarsHand, self).__init__(hand_text, parse) self._splitted = self._split_pattern.split(self.raw) # search split locations (basically empty strings) # sections[0] is before HOLE CARDS # sections[-1] is before SUMMARY self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] if parse: self.parse() def parse_header(self): match = self._header_pattern.match(self._splitted[0]) self.game_type = normalize(match.group('game_type')) self.sb = Decimal(match.group('sb')) self.bb = Decimal(match.group('bb')) self.buyin = Decimal(match.group('buyin')) self.rake = Decimal(match.group('rake')) self._parse_date(match.group('date')) self.game = normalize(match.group('game')) self.limit = normalize(match.group('limit')) self.ident = match.group('ident') self.tournament_ident = match.group('tournament_ident') self.tournament_level = match.group('tournament_level') self.currency = match.group('currency') self.header_parsed = True def parse(self): super(PokerStarsHand, self).parse() self._parse_table() self._parse_seats() self._parse_hole_cards() self._parse_preflop() self._parse_street('flop') self._parse_street('turn') self._parse_street('river') self.show_down = "SHOW DOWN" in self._splitted self._parse_pot() self._parse_board() self._parse_winners() self.parsed = True def _parse_table(self): match = self._table_pattern.match(self._splitted[1]) self.table_name = match.group(1) self.max_players = int(match.group(2)) self.button_seat = int(match.group(3)) def _parse_seats(self): players = self._init_seats(self.max_players) for line in self._splitted[2:]: match = self._seat_pattern.match(line) if not match: break players[int(match.group(1)) - 1] = (match.group(2), int(match.group(3))) self.button = players[self.button_seat - 1][0] self.players = OrderedDict(players) def _parse_hole_cards(self): hole_cards_line = self._splitted[self._sections[0] + 2] match = self._hole_cards_pattern.match(hole_cards_line) self.hero = match.group(1) self.hero_seat = self.players.keys().index(self.hero) + 1 self.hero_hole_cards = match.group(2, 3) def _parse_preflop(self): start = self._sections[0] + 3 stop = self._sections[1] self.preflop_actions = tuple(self._splitted[start:stop]) def _parse_street(self, street): try: start = self._splitted.index(street.upper()) + 2 stop = self._splitted.index('', start) street_actions = self._splitted[start:stop] setattr(self, "%s_actions" % street.lower(), tuple(street_actions) if street_actions else None) except ValueError: setattr(self, street, None) setattr(self, '%s_actions' % street.lower(), None) def _parse_pot(self): potline = self._splitted[self._sections[-1] + 2] match = self._pot_pattern.match(potline) self.total_pot = int(match.group(1)) def _parse_board(self): boardline = self._splitted[self._sections[-1] + 3] if not boardline.startswith('Board'): return cards = self._board_pattern.findall(boardline) self.flop = tuple(cards[:3]) if cards else None self.turn = cards[3] if len(cards) > 3 else None self.river = cards[4] if len(cards) > 4 else None def _parse_winners(self): winners = set() start = self._sections[-1] + 4 for line in self._splitted[start:]: if not self.show_down and "collected" in line: match = self._winner_pattern.match(line) winners.add(match.group(2)) elif self.show_down and "won" in line: match = self._showdown_pattern.match(line) winners.add(match.group(2)) self.winners = tuple(winners) class FullTiltHand(PokerHand): """Parses Full Tilt Poker hands the same way as PokerStarsHand class. PokerStars and Full Tilt hand histories are very similar, so parsing them is almost identical. There are small differences though. **Class specific** :cvar str poker_room: always ``FTP`` for this class :ivar tournament_level: ``None`` :ivar buyin: ``None``: it's not in the hand history, but the filename :ivar rake: ``None``: also :ivar currency: ``None`` :ivar str table_name: just a number, but str type **Extra** :ivar Decimal flop_pot: pot size on the flop, before actions :ivar int flop_num_players: number of players seen the flop :ivar Decimal turn_pot: pot size before turn :ivar int turn_num_players: number of players seen the turn :ivar Decimal river_pot: pot size before river :ivar int river_num_players: number of players seen the river :ivar unicode tournament_name: e.g. ``"$750 Guarantee"``, ``"$5 Sit & Go (Super Turbo)"`` """ poker_room = 'FTP' date_format = '%H:%M:%S ET - %Y/%m/%d' _time_zone = pytz.timezone('US/Eastern') # ET _split_pattern = re.compile(r" ?\*\*\* ?\n?|\n") # header patterns _tournament_pattern = re.compile(r""" ^Full[ ]Tilt[ ]Poker[ ] # Poker Room Game[ ]\#(?P<ident>\d*):[ ] # Hand number (?P<tournament_name>.*)[ ] # Tournament name \((?P<tournament_ident>\d*)\),[ ] # Tournament Number Table[ ](?P<table_name>\d*)[ ]-[ ] # Table name """, re.VERBOSE) _game_pattern = re.compile(r" - (?P<limit>NL|PL|FL|No Limit|Pot Limit|Fix Limit) (?P<game>.*?) - ") _blind_pattern = re.compile(r" - (\d*)/(\d*) - ") _date_pattern = re.compile(r" \[(.*)\]$") _seat_pattern = re.compile(r"^Seat (\d): (.*) \(([\d,]*)\)$") _button_pattern = re.compile(r"^The button is in seat #(\d)$") _hole_cards_pattern = re.compile(r"^Dealt to (.*) \[(..) (..)\]$") _street_pattern = re.compile(r"\[([^\]]*)\] \(Total Pot: (\d*)\, (\d) Players") _pot_pattern = re.compile(r"^Total pot ([\d,]*) .*\| Rake (\d*)$") _winner_pattern = re.compile(r"^Seat (\d): (.*) collected \((\d*)\),") _showdown_pattern = re.compile(r"^Seat (\d): (.*) showed .* and won") def __init__(self, hand_text, parse=True): super(FullTiltHand, self).__init__(hand_text, parse) self._splitted = self._split_pattern.split(self.raw) # search split locations (basically empty strings) # sections[0] is before HOLE CARDS # sections[-1] is before SUMMARY self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] if parse: self.parse() def parse_header(self): header_line = self._splitted[0] match = self._tournament_pattern.match(header_line) self.game_type = 'TOUR' self.ident = match.group('ident') self.tournament_name = match.group('tournament_name') self.tournament_ident = match.group('tournament_ident') self.table_name = match.group('table_name') match = self._game_pattern.search(header_line) self.limit = normalize(match.group('limit')) self.game = normalize(match.group('game')) match = self._blind_pattern.search(header_line) self.sb = Decimal(match.group(1)) self.bb = Decimal(match.group(2)) match = self._date_pattern.search(header_line) self._parse_date(match.group(1)) self.tournament_level = self.buyin = self.rake = self.currency = None self.header_parsed = True def parse(self): super(FullTiltHand, self).parse() self._parse_seats() self._parse_hole_cards() self._parse_preflop() self._parse_street('flop') self._parse_street('turn') self._parse_street('river') self.show_down = 'SHOW DOWN' in self._splitted self._parse_pot() self._parse_winners() self.parsed = True def _parse_seats(self): # In hh there is no indication of max_players, so init for 9. players = self._init_seats(9) for line in self._splitted[1:]: match = self._seat_pattern.match(line) if not match: break seat_number = int(match.group(1)) player_name = match.group(2) stack = int(match.group(3).replace(',', '')) players[seat_number - 1] = (player_name, stack) self.max_players = seat_number self.players = OrderedDict(players[:self.max_players]) # cut off unneccesary seats # one line before the first split. button_line = self._splitted[self._sections[0] - 1] self.button_seat = int(self._button_pattern.match(button_line).group(1)) self.button = players[self.button_seat - 1][0] def _parse_hole_cards(self): hole_cards_line = self._splitted[self._sections[0] + 2] match = self._hole_cards_pattern.match(hole_cards_line) self.hero = match.group(1) self.hero_seat = self.players.keys().index(self.hero) + 1 self.hero_hole_cards = match.group(2, 3) def _parse_preflop(self): start = self._sections[0] + 3 stop = self._sections[1] self.preflop_actions = tuple(self._splitted[start:stop]) def _parse_street(self, street): try: start = self._splitted.index(street.upper()) + 1 self._parse_boardline(start, street) stop = next(v for v in self._sections if v > start) street_actions = self._splitted[start + 1:stop] setattr(self, "%s_actions" % street, tuple(street_actions) if street_actions else None) except ValueError: setattr(self, street, None) setattr(self, '%s_actions' % street, None) setattr(self, '%s_pot' % street, None) setattr(self, '%s_num_players' % street, None) def _parse_boardline(self, start, street): """Parse pot, num players and cards.""" # Exceptions caught in _parse_street. board_line = self._splitted[start] match = self._street_pattern.search(board_line) cards = match.group(1) cards = tuple(cards.split()) if street == 'flop' else cards setattr(self, street, cards) pot = match.group(2) setattr(self, "%s_pot" % street, Decimal(pot)) num_players = int(match.group(3)) setattr(self, "%s_num_players" % street, num_players) def _parse_pot(self): potline = self._splitted[self._sections[-1] + 2] match = self._pot_pattern.match(potline.replace(',', '')) self.total_pot = int(match.group(1)) def _parse_winners(self): winners = set() start = self._sections[-1] + 4 for line in self._splitted[start:]: if not self.show_down and "collected" in line: match = self._winner_pattern.match(line) winners.add(match.group(2)) elif self.show_down and "won" in line: match = self._showdown_pattern.match(line) winners.add(match.group(2)) self.winners = tuple(winners) class PKRHand(PokerHand): """Parses PKR hands. **Class specific** :cvar str poker_room: ``"PKR"`` for this class :ivar unicode table_name: "#table_number - name_of_the_table" **Extra** :ivar str last_ident: last hand id :ivar str money_type: ``"R"`` for real money, ``"P"`` for play money """ poker_room = 'PKR' date_format = '%d %b %Y %H:%M:%S' currency = 'USD' _time_zone = pytz.UTC _split_pattern = re.compile(r"Dealing |\nDealing Cards\n|Taking |Moving |\n") _blinds_pattern = re.compile(r"^Blinds are now \$([\d.]*) / \$([\d.]*)$") _dealt_pattern = re.compile(r"^\[(. .)\]\[(. .)\] to (.*)$") _seat_pattern = re.compile(r"^Seat (\d\d?): (.*) - \$([\d.]*) ?(.*)$") _sizes_pattern = re.compile(r"^Pot sizes: \$([\d.]*)$") _card_pattern = re.compile(r"\[(. .)\]") _rake_pattern = re.compile(r"Rake of \$([\d.]*) from pot \d$") _win_pattern = re.compile(r"^(.*) wins \$([\d.]*) with: ") def __init__(self, hand_text, parse=True): """Split hand history by sections and parse.""" super(PKRHand, self).__init__(hand_text, parse) self._splitted = self._split_pattern.split(self.raw) # search split locations (basically empty strings) # sections[1] is after blinds, before preflop # section[2] is before flop # sections[-1] is before showdown self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] if parse: self.parse() def parse_header(self): self.table_name = self._splitted[0][6:] # cut off "Table " self.ident = self._splitted[1][15:] # cut off "Starting Hand #" self._parse_date(self._splitted[2][20:]) # cut off "Start time of hand: " self.last_ident = self._splitted[3][11:] # cut off "Last Hand #" self.game = normalize(self._splitted[4][11:]) # cut off "Game Type: " self.limit = normalize(self._splitted[5][12:]) # cut off "Limit Type: " self.game_type = normalize(self._splitted[6][12:]) # cut off "Table Type: " self.money_type = normalize(self._splitted[7][12:]) # cut off "Money Type: " match = self._blinds_pattern.match(self._splitted[8]) self.sb = Decimal(match.group(1)) self.bb = Decimal(match.group(2)) self.buyin = self.bb * 100 self.button = int(self._splitted[9][18:]) # cut off "Button is at seat " self.tournament_ident = None self.tournament_name = None self.tournament_level = None def parse(self): super(PKRHand, self).parse() self._parse_seats() self._parse_hero() self._parse_preflop() self._parse_street('flop') self._parse_street('turn') self._parse_street('river') self._parse_showdown() def _parse_seats(self): # In hh there is no indication of max_players, # so init for 10, as there are 10 player tables on PKR. players = self._init_seats(10) for line in self._splitted[10:]: match = self._seat_pattern.match(line) if not match: break seat_number = int(match.group(1)) player_name = match.group(2) stack = Decimal(match.group(3)) players[seat_number - 1] = (player_name, stack) self.max_players = seat_number self.players = OrderedDict(players[:self.max_players]) button_row = self._splitted[self._sections[0] + 1] # cut last two because there can be 10 seats also # in case of one digit, the first char will be a space # but int() can convert it without hiccups :) self.button_seat = int(button_row[-2:]) self.button = players[self.button_seat - 1][0] def _parse_hero(self): dealt_row = self._splitted[self._sections[1] + 1] match = self._dealt_pattern.match(dealt_row) first = match.group(1)[0:3:2] # split space in the middle second = match.group(2)[0:3:2] self.hero_hole_cards = (first, second) self.hero = match.group(3) self.hero_seat = self.players.keys().index(self.hero) + 1 def _parse_preflop(self): start = self._sections[1] + 2 stop = self._splitted.index('', start + 1) - 1 self.preflop_actions = tuple(self._splitted[start:stop]) def _parse_street(self, street): street_sections = {'flop': 2, 'turn': 3, 'river': 4} section = street_sections[street] try: start = self._sections[section] + 1 street_line = self._splitted[start] cards = map(lambda x: x[0:3:2], self._card_pattern.findall(street_line)) setattr(self, street, tuple(cards) if street == 'flop' else cards[0]) stop = next(v for v in self._sections if v > start) - 1 setattr(self, "%s_actions" % street, tuple(self._splitted[start + 1:stop])) sizes_line = self._splitted[start - 2] pot = Decimal(self._sizes_pattern.match(sizes_line).group(1)) setattr(self, "%s_pot" % street, pot) except IndexError: setattr(self, street, None) setattr(self, "%s_actions" % street, None) setattr(self, "%s_pot" % street, None) def _parse_showdown(self): start = self._sections[-1] + 1 rake_line = self._splitted[start] match = self._rake_pattern.match(rake_line) self.rake = Decimal(match.group(1)) winners = [] total_pot = self.rake for line in self._splitted[start:]: if 'shows' in line: self.show_down = True elif 'wins' in line: match = self._win_pattern.match(line) winners.append(match.group(1)) total_pot += Decimal(match.group(2)) self.winners = tuple(winners) self.total_pot = total_pot
Improve vm create, using from horizontal elasticity
import math import requests from django.conf import settings from django.core.management import BaseCommand from corehq.apps.analytics.utils import ( get_blocked_hubspot_domains, MAX_API_RETRIES, ) from corehq.apps.es import UserES class Command(BaseCommand): help = "Manually cleans up blocked Hubspot contacts" api_key = None def handle(self, **options): self.api_key = settings.ANALYTICS_IDS.get('HUBSPOT_API_KEY', None) if not self.api_key: self.stdout.write("No HubSpot API key found.") blocked_domains = get_blocked_hubspot_domains() for domain in blocked_domains: users_not_blocked = [] user_query = UserES().domain(domain).source(['email', 'username']) total_users = user_query.count() chunk_size = 30 # Hubspot recommends fewer than 100 emails per request num_chunks = int(math.ceil(float(total_users) / float(chunk_size))) for chunk in range(num_chunks): blocked_users = (user_query .size(chunk_size) .start(chunk * chunk_size) .run() .hits) blocked_emails = [] for user in blocked_users: username = user.get('username') user_email = user.get('email') blocked_emails.append(username) if user_email and user_email != username: blocked_emails.append(user_email) users_not_blocked.extend(self.get_blocked_status_for_emails( blocked_emails )) if users_not_blocked: self.stdout.write(f"\n\nFound {len(users_not_blocked)} users in " f"HubSpot who are members of the project {domain} " f"that is blocking HubSpot data:") self.stdout.write("\nEmail\tFirst Conversion") for summary in users_not_blocked: self.stdout.write(f"{summary[0]}\t{summary[1]}") def get_blocked_status_for_emails(self, list_of_emails, retry_num=0): try: req = requests.get( "https://api.hubapi.com/contacts/v1/contact/emails/batch/", params={ 'hapikey': self.api_key, 'email': list_of_emails, }, ) if req.status_code == 404: return [] req.raise_for_status() except (ConnectionError, requests.exceptions.HTTPError) as e: if retry_num <= MAX_API_RETRIES: return self.get_blocked_status_for_emails(list_of_emails, retry_num + 1) else: self.stdout.write(f"Failed to get data from hubspot for " f"{list_of_emails.join(',')}.") else: status_summary = [] for contact_id, data in req.json().items(): first_conversion_status = data.get( 'properties', {} ).get('first_conversion_clustered_', {}).get('value') email = data.get( 'properties', {} ).get('email', {}).get('value') status_summary.append((email, first_conversion_status)) return status_summary return [] add error styling to output messages import math import requests from django.conf import settings from django.core.management import BaseCommand from corehq.apps.analytics.utils import ( get_blocked_hubspot_domains, MAX_API_RETRIES, ) from corehq.apps.es import UserES class Command(BaseCommand): help = "Manually cleans up blocked Hubspot contacts" api_key = None def handle(self, **options): self.api_key = settings.ANALYTICS_IDS.get('HUBSPOT_API_KEY', None) if not self.api_key: self.stdout.write("No HubSpot API key found.") blocked_domains = get_blocked_hubspot_domains() for domain in blocked_domains: users_not_blocked = [] user_query = UserES().domain(domain).source(['email', 'username']) total_users = user_query.count() chunk_size = 30 # Hubspot recommends fewer than 100 emails per request num_chunks = int(math.ceil(float(total_users) / float(chunk_size))) for chunk in range(num_chunks): blocked_users = (user_query .size(chunk_size) .start(chunk * chunk_size) .run() .hits) blocked_emails = [] for user in blocked_users: username = user.get('username') user_email = user.get('email') blocked_emails.append(username) if user_email and user_email != username: blocked_emails.append(user_email) users_not_blocked.extend(self.get_blocked_status_for_emails( blocked_emails )) if users_not_blocked: self.stdout.write(self.style.ERROR( f"\n\nFound {len(users_not_blocked)} users in " f"HubSpot who are members of the project {domain} " f"that is blocking HubSpot data:" )) self.stdout.write("\nEmail\tFirst Conversion") for summary in users_not_blocked: self.stdout.write(f"{summary[0]}\t{summary[1]}") def get_blocked_status_for_emails(self, list_of_emails, retry_num=0): try: req = requests.get( "https://api.hubapi.com/contacts/v1/contact/emails/batch/", params={ 'hapikey': self.api_key, 'email': list_of_emails, }, ) if req.status_code == 404: return [] req.raise_for_status() except (ConnectionError, requests.exceptions.HTTPError) as e: if retry_num <= MAX_API_RETRIES: return self.get_blocked_status_for_emails(list_of_emails, retry_num + 1) else: self.stdout.write(self.style.ERROR( f"Failed to get data from hubspot for " f"{list_of_emails.join(',')}." )) else: status_summary = [] for contact_id, data in req.json().items(): first_conversion_status = data.get( 'properties', {} ).get('first_conversion_clustered_', {}).get('value') email = data.get( 'properties', {} ).get('email', {}).get('value') status_summary.append((email, first_conversion_status)) return status_summary return []
from __future__ import division from urllib2 import urlopen import re import operator import copy import json from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render_to_response, redirect from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import DetailView, TemplateView, ListView from django.views.decorators.vary import vary_on_cookie from django.db.models import Q from django.core.cache import cache import xlwt from django.utils.safestring import mark_safe from education.curriculum_progress_helper import get_target_value, get_location_for_curriculum_view, get_curriculum_data, target from rapidsms_httprouter.models import Message from .forms import * from .models import * from uganda_common.utils import * from rapidsms.contrib.locations.models import Location from generic.views import generic from generic.sorters import SimpleSorter from poll.models import Poll, ResponseCategory from script.models import ScriptStep, Script from .reports import * from .utils import * from .utils import _schedule_monthly_script, _schedule_termly_script, _schedule_weekly_scripts, _schedule_teacher_weekly_scripts import reversion from reversion.models import Revision from unregister.models import Blacklist from .utils import themes from education.absenteeism_view_helper import * import datetime from datetime import date from education.view_helper import * from education.view_helper_utils import * Num_REG = re.compile('\d+') super_user_required = \ user_passes_test(lambda u: u.groups.filter( name__in=['Admins', 'DFO', 'UNICEF Officials']).exists() or u.is_superuser) @login_required def index(request, **kwargs): """ kwargs is where we list the variables that can be passed as our context use as follows: index(request, context_vars={'some_model_queryset'=Model.objects.all}) """ if not kwargs: return render_to_response("education/index.html", {}, RequestContext(request)) else: #When choosing to use kwargs, don't forget to include template and context_var variables # if you don't need a template or just need the original template, use template_name=None context_vars = kwargs.get('context_vars') template_name = kwargs['template_name'] if not template_name: #if no template name is given t = "education/index.html" else: t = "education/%s" % template_name return render_to_response(t, context_vars, RequestContext(request)) #MAPS @login_required def dash_map(request): return render_to_response('education/dashboard/map.html', {}, RequestContext(request)) def dash_ministry_map(request): return render_to_response('education/dashboard/map.html', {}, RequestContext(request)) def dash_attdance(request): boysp3_attendance = get_responses_to_polls(poll_name='edtrac_boysp3_attendance') boysp3_enrolled = get_responses_to_polls(poll_name="edtrac_boysp3_enrollment") boysp3_absent = boysp3_enrolled - boysp3_attendance girlsp3_attendance = get_responses_to_polls(poll_name="edtrac_girlsp3_attendance") girlsp3_enrolled = get_responses_to_polls(poll_name="edtrac_girlsp3_enrollment") girlsp3_absent = girlsp3_enrolled - girlsp3_attendance boysp6_attendance = get_responses_to_polls(poll_name="edtrac_boysp6_attendance") boysp6_enrolled = get_responses_to_polls(poll_name="edtrac_boysp6_enrollment") boysp6_absent = boysp6_enrolled - boysp6_attendance girlsp6_attendance = get_responses_to_polls(poll_name="edtrac_girlsp6_attendance") girlsp6_enrolled = get_responses_to_polls(poll_name="edtrac_girlsp6_enrollment") girlsp6_absent = girlsp6_enrolled - girlsp6_attendance total_male_teachers = get_responses_to_polls(poll_name="edtrac_m_teachers_deployment") total_female_teachers = get_responses_to_polls(poll_name="edtrac_f_teachers_deployment") male_teachers_present = get_responses_to_polls(poll_name="edtrac_m_teachers_attendance") male_teachers_absent = total_male_teachers - male_teachers_present female_teachers_present = get_responses_to_polls(poll_name="edtrac_f_teachers_attendance") female_teachers_absent = total_female_teachers - female_teachers_present return render_to_response('education/dashboard/attdance.html', { 'girlsp3_present' : girlsp3_attendance, 'girlsp3_absent' : girlsp3_absent, 'boysp3_present' : boysp3_attendance, 'boysp3_absent' : boysp3_absent, 'girlsp6_present' : girlsp6_attendance, 'girlsp6_absent' : girlsp6_absent, 'boysp6_present' : boysp6_attendance, 'boysp6_absent' : boysp6_absent, 'female_teachers_present' : female_teachers_present, 'female_teachers_absent' : female_teachers_absent, 'male_teachers_present' : male_teachers_present, 'male_teachers_absent' : male_teachers_absent } , RequestContext(request)) def get_mode_progress(mode): try: mode_progress = (100 * sorted(target.values()).index(mode) + 1) / float(len(target.keys())) # offset zero-based index by 1 except ValueError: mode_progress = 0 # when no values are recorded return mode_progress def get_progress_color(current_mode, target_value): on_schedule = 'green' behind_schedule = 'red' if current_mode < target_value: return behind_schedule return on_schedule def get_weeks_in_term(): term_start= getattr(settings,'SCHOOL_TERM_START') first_term_start= getattr(settings,'FIRST_TERM_BEGINS') second_term_start= getattr(settings,'SECOND_TERM_BEGINS') third_term_start= getattr(settings,'THIRD_TERM_BEGINS') weeks = [] for term_starts in [first_term_start, second_term_start, third_term_start]: if term_start == term_starts: weeks.extend(get_weeks(get_week_date()[1],depth=get_week_count(get_week_date()[0],term_starts))) break weeks.extend(get_weeks(dateutils.increment(term_starts, weeks=12),depth=12)) return weeks def format_week(week,sep): day1 = week[0].strftime("%d"+sep+"%b"+sep+"%Y") day2 = week[1].strftime("%d"+sep+"%b"+sep+"%Y") formated_week = "%s to %s" % (day1 , day2) return formated_week def _get_formated_date_choice(week): if week[0] < datetime.datetime.today() < week[1]: return format_week(week, ","), "current week( %s )" % format_week(week, "-") return format_week(week, ","), format_week(week, "-") class CurriculumForm(forms.Form): error_css_class = 'error' SELECT_CHOICES = [_get_formated_date_choice(week) for week in get_weeks_in_term()] choose_week_to_view = forms.ChoiceField(choices=SELECT_CHOICES, required=False) class ReporterDetailView(DetailView): model = EmisReporter def format_to_datetime_object(week_as_string): day1 = week_as_string.split()[0] day2 = week_as_string.split()[2] day_one = datetime.datetime.strptime(day1,"%d,%b,%Y") day_two = datetime.datetime.strptime(day2,"%d,%b,%Y") return [day_one,day_two] def get_modes_and_target(current_mode, target_value): target_progress = get_mode_progress(target_value) if len(current_mode) > 0 and isinstance(current_mode,list): max_mode = max([i[0] for i in current_mode]) mode_progress = get_mode_progress(max_mode) color = get_progress_color(max_mode, target_value) return color, mode_progress, target_progress mode_progress = 0 color = 'red' return color, mode_progress, target_progress def get_mode_if_exception_thrown(loc_data): if "Progress undetermined this week" in loc_data.values(): return "Progress undetermined this week" return "No Reports made this week" @login_required def curriculum_progress(request,district_pk=None): locations, user_location, sub_location_type,template_name = get_location_for_curriculum_view(district_pk, request) if request.method == 'POST': curriculum_form = CurriculumForm(data=request.POST) if curriculum_form.is_valid(): target_week = format_to_datetime_object(curriculum_form.cleaned_data['choose_week_to_view']) target_date = target_week[0] else: return render_to_response('education/progress/admin_progress_details.html', {'form': curriculum_form}, RequestContext(request)) else: target_week = get_week_date() curriculum_form = CurriculumForm(initial={'choose_week_to_view': format_week(target_week, ",")}) target_date = target_week[0] loc_data , valid_responses = get_curriculum_data(locations,target_week) try: current_mode = Statistics(valid_responses).mode except StatisticsException: current_mode = get_mode_if_exception_thrown(loc_data) target_value , term = get_target_value(target_date) if isinstance(current_mode,list) and len(current_mode) == 0: current_mode = "Progress undetermined this week" color, mode_progress, target_progress = get_modes_and_target(current_mode, target_value) return render_to_response(template_name, {'form': curriculum_form, 'location_data': loc_data, 'target': target_value, 'current_mode': current_mode, 'mode_progress': mode_progress, 'target_progress': target_progress, 'class_sent_from_behind': color, 'sub_location_type': sub_location_type, 'term': term}, RequestContext(request)) def dash_admin_meetings(req): profile = req.user.get_profile() location = profile.location p = Poll.objects.get(name = 'edtrac_smc_meetings') if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Ministry Officials'): meeting_stats = get_count_response_to_polls(p, #404 is shortcode for unknown choices = [0, 1, 2, 3, 404], # number of meetings with_percent = True, #percentage counted based on number of schools termly = True, admin=True) return render_to_response("education/admin/admin_meetings.html",{ 'meeting_basis': meeting_stats.get('correctly_answered'), 'titles':",".join(str(k) for k in meeting_stats.get('to_ret').keys()), 'meetings':",".join(str(v) for v in meeting_stats.get('to_ret').values()) }, RequestContext(req)) else: meeting_stats = get_count_response_to_polls(p, location_name = location.name, #404 is shortcode for unknown choices = [0, 1, 2, 3, 404], # number of meetings with_percent = True, #percentage counted based on number of schools termly = True, admin = False ) return render_to_response('education/admin/other_meetings.html', {'location_name':location.name, 'meeting_basis': meeting_stats.get('correctly_answered'), 'meetings':",".join(str(v) for v in meeting_stats.get('to_ret').values()), 'titles':",".join(str(k) for k in meeting_stats.get('to_ret').keys()), 'meeting_basis':meeting_stats.get('correctly_answered')}, RequestContext(req)) def preprocess_response(resp): """ reprocess the response values and return just one value """ if not resp: return '--' elif None in resp: return 'wrong response' else: return resp[0] # assumption only one SMC is attached to that school def dash_district_meetings(req, district_name): district = Location.objects.filter(type="district").get(name = district_name) p = Poll.objects.get(name = 'edtrac_smc_meetings') schools_data = EmisReporter.objects.exclude(connection__in = Blacklist.objects.values_list('connection')).\ filter(groups__name = 'SMC', reporting_location = district).exclude(schools = None).order_by('schools__name').\ values_list('schools__name','schools__id','connection__pk') school_container = {} for school_name, school_id, smc_connection in schools_data: school_container[(school_name, school_id)] = preprocess_response([r.eav.poll_number_value for r in p.responses.filter(contact__connection__pk = smc_connection, date__range =[getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END')] )]) #TODO -> sort the school container items return render_to_response( 'education/admin/district_meetings.html', {'location_name':district_name, 'meeting_count':school_container.items()}, RequestContext(req)) # Dashboard specific view functions @login_required @vary_on_cookie def dashboard(request): return admin_dashboard(request) def capitation_grants(locations): # capitation grants cg = Poll.objects.get(name="edtrac_upe_grant") yes_category = cg.categories.get(name='yes') yeses_cg = cg.responses.filter(contact__reporting_location__in=locations, categories__category=yes_category).values_list('contact').distinct().count() # percent of those that received grants head_teacher_count = EmisReporter.objects.exclude(schools=None, connection__in= \ Blacklist.objects.values_list('connection', flat=True)).filter(groups__name='Head Teachers', \ reporting_location__in=locations).count() try: grant_percent = (100 * yeses_cg) / head_teacher_count except ZeroDivisionError: grant_percent = 0 return {'grant_percent': grant_percent} def violence_numbers_girls(locations): """ Percentage change in violance from the previous month """ responses_to_violence_girls = poll_response_sum("edtrac_violence_girls", month_filter = 'monthly', locations = locations) return {'violence_numbers_girls' : abs(responses_to_violence_girls[0])} def violence_numbers_boys(locations): """ Percentage change in violance from the previous month """ responses_to_violence_boys = poll_response_sum("edtrac_violence_boys", month_filter = 'monthly', locations = locations) return {'violence_numbers_boys': abs(responses_to_violence_boys[0])} def violence_numbers_reported(locations): """ Percentage change in violance from the previous month """ responses_to_violence_reported = poll_response_sum("edtrac_violence_reported", month_filter = 'monthly', locations = locations) return {'violence_numbers_reported': abs(responses_to_violence_reported[0])} def get_two_weeks_absenteeism(indicator, locations, get_time): date_weeks = get_week_date(depth=2, get_time=get_time) holiday = False this_week_absent = '--' past_week_absent = '--' if is_holiday(date_weeks[0][0], getattr(settings, 'SCHOOL_HOLIDAYS')): this_week_absent = '--' holiday = True if is_holiday(date_weeks[1][0], getattr(settings, 'SCHOOL_HOLIDAYS')): past_week_absent = '--' holiday = True if not holiday: config_list = get_polls_for_keyword(indicator) function_to_invoke = config_list[0].get('func') absent_by_location, absent_by_time, school_percent = function_to_invoke(locations, config_list[0], date_weeks) try: this_week_absent = absent_by_time[0] except IndexError: this_week_absent = 0 try: past_week_absent = absent_by_time[1] except IndexError: past_week_absent = 0 return this_week_absent, past_week_absent def p3_absent_boys(locations, get_time=datetime.datetime.now): """ Attendance of P3 Pupils; this gets the absenteeism """ boysp3, boysp3_past = compute_absenteeism_summary('P3Boys',locations,get_time=get_time) return {'boysp3' : boysp3, 'boysp3_past' : boysp3_past,} def p6_boys_absent(locations, get_time=datetime.datetime.now): boysp6, boysp6_past = compute_absenteeism_summary('P6Boys',locations,get_time=get_time) return {'boysp6' : boysp6, 'boysp6_past' : boysp6_past} def p3_absent_girls(locations, get_time=datetime.datetime.now): girlsp3 ,girlsp3_past = compute_absenteeism_summary('P3Girls',locations,get_time=get_time) return {'girlsp3' : girlsp3, 'girlsp3_past' : girlsp3_past} def p6_girls_absent(locations,get_time=datetime.datetime.now): girlsp6,girlsp6_past = compute_absenteeism_summary('P6Girls',locations,get_time=get_time) return {'girlsp6' : girlsp6, 'girlsp6_past' : girlsp6_past} def f_teachers_absent(locations, get_time=datetime.datetime.now): female_teachers ,female_teachers_past = compute_absenteeism_summary('FemaleTeachers',locations,get_time=get_time) return {'female_teachers' :female_teachers,'female_teachers_past' : female_teachers_past,} def m_teachers_absent(locations, get_time=datetime.datetime.now): male_teachers,male_teachers_past = compute_absenteeism_summary('MaleTeachers',locations, get_time=get_time) return {'male_teachers' : male_teachers, 'male_teachers_past' : male_teachers_past} def get_target_week(): for week in get_weeks_in_term(): if week[0] < datetime.datetime.today() < week[1]: return week def progress(stages, stage): numerator = stages.index(stage) + 1 denominator = len(stages) return 100 * numerator / denominator def p3_curriculum(locations): target_week = get_week_date() poll = Poll.objects.get(name='edtrac_p3curriculum_progress') mode = NumericResponsesFor(poll) \ .forDateRange(target_week) \ .forLocations(locations) \ .forValues(themes.keys()) \ .mode() if mode: return {'mode_progress' : progress(sorted(themes.keys()), mode), 'c_mode' : [[mode]]} else: return {'mode_progress' : 0, 'c_mode' : "Progress undetermined this week"} def meals_missed(locations, get_time): poll = Poll.objects.get(name = "edtrac_headteachers_meals") this_month = get_month_day_range(get_time()) schools_without_meals = NumericResponsesFor(poll) \ .forLocations(locations) \ .forDateRange(this_month) \ .excludeGreaterThan(0) \ .groupBySchools() return {'meals_missed' : len(schools_without_meals)} def head_teachers_female(locations, get_time=datetime.datetime.now): female_d1,female_d2 = get_two_weeks_absenteeism('FemaleHeadTeachers',locations,get_time) try: f_head_diff = female_d2 - female_d1 if f_head_diff < 0: f_head_t_class = "decrease" f_head_t_data = 'data-red' elif f_head_diff > 0: f_head_t_class = "increase" f_head_t_data = 'data-green' else: f_head_t_class = "zero" f_head_t_data = 'data-white' except: f_head_diff = '--' f_head_t_class = "zero" f_head_t_data = 'data-white' return {'f_head_t_week' : female_d1, 'f_head_t_week_before' : female_d2, 'f_head_diff' : f_head_diff, 'f_head_t_class' : f_head_t_class, 'f_head_t_data':f_head_t_data} def head_teachers_male(locations, get_time=datetime.datetime.now): male_d1, male_d2 = get_two_weeks_absenteeism('MaleHeadTeachers',locations,get_time=get_time) try: m_head_diff = male_d2 - male_d1 if m_head_diff < 0: m_head_t_class = "decrease" m_head_t_data = 'data-red' elif m_head_diff > 0: m_head_t_class = "increase" m_head_t_data = 'data-green' else: m_head_t_class = "zero" m_head_t_data = 'data-white' except: m_head_diff = '--' m_head_t_class = "zero" m_head_t_data = 'data-white' return {'m_head_t_week' : male_d1, 'm_head_t_data':m_head_t_data, 'm_head_t_week_before' : male_d2, 'm_head_diff' : m_head_diff, 'm_head_t_class' : m_head_t_class} def schools_valid(locations, group_names, blacklisted): school_valid = EmisReporter.objects.filter( groups__name__in=group_names, reporting_location__in=locations ).exclude(connection__in=blacklisted).exclude(schools=None) \ .values('schools__id').distinct().count() return {'total_schools_valid': school_valid} def schools_active(locations): try: count_reps = EmisReporter.objects.filter(groups__name__in=['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'], reporting_location__in = locations).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None).count() count = 0 for p in Poll.objects.filter(name__icontains = 'attendance').select_related(): if len(locations) == 1: count += p.responses.filter( contact__reporting_location__in = locations, date__range = get_week_date(depth = 2)[0] ).distinct().select_related().count() else: count += p.responses.filter(date__range = get_week_date(depth=2)[0]).distinct().select_related().count() school_active = (100 * count) / count_reps except ZeroDivisionError: school_active = 0 return {'school_active': school_active} def smc_meetings(locations): # SMC meetings are count based school_to_date = School.objects.filter(pk__in=EmisReporter.objects.\ filter(reporting_location__name__in = [loc.name for loc in locations]).select_related().\ values_list('schools__pk', flat=True)).count() smc_meeting_poll = Poll.objects.get(name = 'edtrac_smc_meetings') meetings = NumericResponsesFor(smc_meeting_poll) \ .excludeZeros() \ .forDateRange([getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END')]) \ .forLocations(locations) \ .total() try: total_meetings = 100 * meetings / school_to_date except ZeroDivisionError: total_meetings = 0 return {'smc_meetings': total_meetings, 'schools_to_date': school_to_date} def total_reporters(locations, group_names, blacklisted): total_reporters = EmisReporter.objects.filter( groups__name__in=group_names, reporting_location__in=locations ).exclude( connection__in=blacklisted ).exclude( schools=None ).count() return {'total_reporters': total_reporters} # generate context vars def generate_dashboard_vars(location): """ An overly ambitious function that generates context variables for a location if provided This gets populated in the dashboard. """ context_vars = {} if location.name == "Uganda": # get locations from active districts only locations = Location.objects.filter(pk__in=EmisReporter.objects.\ values_list('reporting_location__pk', flat=True)).distinct() else: locations = [location] group_names = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] blacklisted = Blacklist.objects.all().values_list('connection', flat=True) # violence girls context_vars.update(violence_numbers_girls(locations)) #violence boys context_vars.update(violence_numbers_boys(locations)) #violence_reported context_vars.update(violence_numbers_reported(locations)) # capitations grants context_vars.update(capitation_grants(locations)) #active schools context_vars.update(schools_active(locations)) #valid schools context_vars.update(schools_valid(locations, group_names, blacklisted)) #SMC meetings context_vars.update(smc_meetings(locations)) #female head teachers that missed school context_vars.update(head_teachers_female(locations)) #male head teachers that missed school context_vars.update(head_teachers_male(locations)) # time stamps context_vars.update({'month':datetime.datetime.now()}) # progress context_vars.update(p3_curriculum(locations)) # Female teachers context_vars.update(f_teachers_absent(locations)) # P3 teachers male context_vars.update(m_teachers_absent(locations)) # P3 boys context_vars.update(p3_absent_boys(locations)) # P3 Girls context_vars.update(p3_absent_girls(locations)) # P6 Girls context_vars.update(p6_girls_absent(locations)) # P6 Boys context_vars.update(p6_boys_absent(locations)) #Meals context_vars.update(meals_missed(locations, get_time = datetime.datetime.now)) #Total Reporters context_vars.update(total_reporters(locations, group_names, blacklisted)) return context_vars # view generator def view_generator(req, enrol_deploy_poll=None, attendance_poll=None, title=None, url_name_district=None, url_name_school = 'school-detail', template_name='education/timeslider_base.html'): """ A generic function to create views based on time ranges. """ time_range_form = ResultForm() profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): # high level officials will access all districts locations = Location.objects.filter(type='district').filter(pk__in =\ EnrolledDeployedQuestionsAnswered.objects.values_list('school__location__pk',flat=True)) else: # other officials will access individual districts locations = [profile.location] if req.method == 'POST': time_range_form = ResultForm(data=req.POST) to_ret = [] if time_range_form.is_valid(): from_date = time_range_form.cleaned_data['from_date'] to_date = time_range_form.cleaned_data['to_date'] month_delta = abs(from_date.month - to_date.month) date_weeks = [] month_flag = None if month_delta <= 2: # same month get days in between month_flag = False # don't split data in months while from_date <= to_date: if from_date.weekday() == 3: #is to_day a Thursday? date_weeks.append(previous_calendar_week(t = from_date)) # get range from Wed to Thur. from_date += datetime.timedelta(days = 1) else: month_flag = True # split data in months while from_date <= to_date: date_weeks.append([dateutils.month_start(from_date),dateutils.month_end(dateutils.increment(from_date, months=1))]) next_date = dateutils.increment(from_date, months = 1) delta = next_date - from_date from_date += datetime.timedelta(days = abs(delta.days)) if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): schools_temp = School.objects.filter(pk__in = \ EnrolledDeployedQuestionsAnswered.objects.select_related().values_list('school__pk', flat=True)) for location in locations: temp = [] # get schools in this location location_schools = schools_temp.select_related().filter(location = location) # store in memory for d in date_weeks: total_attendance = 0 # per school total_enrollment = 0 # per school for school in location_schools: enrolled = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) if enrolled > 0: if month_flag: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'avg') # use averages else: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_enrollment += enrolled try: percentage = (total_enrollment - total_attendance) * 100 / total_enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) return render_to_response(template_name, {'form':time_range_form, 'dataset':to_ret, 'title': title,'month_flag': month_flag, 'url_name':url_name_district, 'date_batch':date_weeks}, RequestContext(req)) else: location_schools = School.objects.filter(pk__in = EnrolledDeployedQuestionsAnswered.objects.select_related().\ filter(school__location=locations[0]).values_list('school__pk', flat=True)).select_related() #Non admin types# for school in location_schools: for d in date_weeks: temp = [] enrollment = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) if month_flag: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'avg') else: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') try: percentage = (enrollment - attendance) * 100 / enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([school, temp]) return render_to_response(template_name, {'form':time_range_form, 'dataset_school':to_ret, 'title': title,'month_flag':month_flag, 'url_name': url_name_school, 'date_batch':date_weeks}, RequestContext(req)) else: return render_to_response(template_name, {'form':time_range_form, 'url_name':url_name_district, 'title':title}, RequestContext(req)) # NO POST data sent! else: date_weeks = [] date_weeks.append(previous_calendar_week(t = datetime.datetime.now())) sw = date_weeks[0][0] date_weeks.append(previous_calendar_week(t = dateutils.increment(datetime.datetime(sw.year, sw.month, sw.day, 10), weeks = -1))) location_data = [] schools_temp = School.objects.select_related().\ filter(pk__in =\ EnrolledDeployedQuestionsAnswered.objects.select_related().filter(school__location__in=locations).values_list('school__pk',flat=True)) context_vars = {} if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): for location in locations: temp = [] # get schools in this location location_schools = schools_temp.select_related().filter(location = location) for d in date_weeks: total_attendance = 0 # per school total_enrollment = 0 # per school for school in location_schools: enrolled = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_enrollment += enrolled try: percentage = (total_enrollment - total_attendance) * 100 / total_enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) try: diff = temp[0] - temp[1] except TypeError: diff = '--' location_data.append([location, temp[0], temp[1], diff]) context_vars.update({'location_data':location_data}) else: location_schools = School.objects.select_related().filter(pk__in = EnrolledDeployedQuestionsAnswered.objects.select_related().\ filter(school__location=locations[0]).values_list('school__pk', flat=True)) #Non admin types to_ret = [] for school in location_schools: enrollment = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) temp = [] for d in date_weeks: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') try: percentage = (enrollment - attendance) * 100 / enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([school, temp]) context_vars = {'form':time_range_form, 'dataset_school':to_ret, 'title': title, 'url_name': url_name_school, 'date_batch':date_weeks} if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): x = {'url_name':url_name_district, 'headings':['District', 'Current week', 'Previous week', 'Percentage difference']} else: x = {'url_name':url_name_school, 'headings':['School', 'Current week', 'Previous week', 'Percentage difference']} if context_vars.has_key('form') ==False and context_vars.has_key('title') == False: context_vars.update({'form':time_range_form,'title':title}) # add the keys to context_vars dict context_vars.update(x) return render_to_response(template_name, context_vars, RequestContext(req)) @login_required def admin_dashboard(request): if request.user.get_profile().is_member_of('Ministry Officials') or request.user.get_profile().is_member_of('Admins')\ or request.user.get_profile().is_member_of('UNICEF Officials'): location = Location.objects.get(name="Uganda") else: location = request.user.get_profile().location key = "context-vars-for-location-" + str(location.id) context_vars = cache.get(key) if not context_vars: context_vars = generate_dashboard_vars(location=location) cache.set(key, context_vars, 60 * 60) return render_to_response("education/admin/admin_dashboard.html", context_vars, RequestContext(request)) class NationalStatistics(TemplateView): template_name = "education/admin/national_statistics.html" groups = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] def compute_percent(self, reps, groups = groups): all_reporters = EmisReporter.objects.filter(groups__name__in=groups).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None) try: reps.count() / all_reporters.count() except ZeroDivisionError: return 0 def get_context_data(self, **kwargs): context = super(NationalStatistics, self).get_context_data(**kwargs) groups = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] all_reporters = EmisReporter.objects.filter(groups__name__in=groups).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None) profile = self.request.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): districts = Location.objects.filter(type="district").\ filter(name__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in=Blacklist.objects.values_list('connection',flat=True)).values_list('reporting_location__name', flat=True)) reps = EmisReporter.objects.select_related().filter(groups__name__in=['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters'], connection__in=Message.objects.\ filter(date__range = get_week_date(depth = 2)[1]).values_list('connection', flat = True)).exclude(schools = None).exclude(connection__in = Blacklist.objects.values_list('connection', flat=True)) district_schools = [ (district, School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).\ filter(reporting_location__name = district.name).distinct().values_list('schools__pk',flat=True)).count()) for district in districts ] context['total_districts'] = districts.count() context['district_schools'] = district_schools schools= School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).\ exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).distinct().values_list('schools__pk',flat=True)) context['school_count'] = schools.count() total_schools = 0 for district in districts: s_count = School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).\ filter(reporting_location__name = district.name).distinct().values_list('schools__pk',flat=True)).count() total_schools += s_count context['total_schools'] = total_schools district_active = [ ( district, self.compute_percent(reps.filter(reporting_location__pk=district.pk), groups=['Head Teachers']) ) for district in districts ] district_active.sort(key=operator.itemgetter(1), reverse=True) context['district_active'] = district_active[:3] context['district_less_active'] = district_active[-3:] head_teacher_count = all_reporters.filter(groups__name='Head Teachers').count() smc_count = all_reporters.filter(groups__name = "SMC").count() p6_teacher_count = all_reporters.filter(groups__name = "Teachers", grade = "P6").count() p3_teacher_count = all_reporters.filter(groups__name = "Teachers", grade = "P3").count() total_teacher_count = all_reporters.filter(groups__name="Teachers").count() deo_count = all_reporters.filter(groups__name="DEO").count() gem_count = all_reporters.filter(groups__name="GEM").count() teacher_data_unclean = total_teacher_count - p3_teacher_count - p6_teacher_count context['head_teacher_count'] = head_teacher_count context['smc_count'] = smc_count context['p6_teacher_count'] = p6_teacher_count context['p3_teacher_count'] = p3_teacher_count context['total_teacher_count'] = total_teacher_count context['teacher_data_unclean'] = teacher_data_unclean context['deo_count'] = deo_count context['gem_count'] = gem_count context['all_reporters'] = all_reporters.count() context['expected_reporters'] = schools.count() * 4 # reporters that used EduTrac the past week active_school_reporters = all_reporters.filter(connection__in=Message.objects.exclude(application='script').\ filter(date__range = get_week_date(depth = 2)[1]).values_list('connection', flat = True)) school_active = [ (school, self.compute_percent(active_school_reporters.filter(schools__pk=school.pk), groups=['Head Teachers', 'Teachers', 'GEM', 'SMC','Other Reporters'])) for school in schools ] school_active.sort(key=operator.itemgetter(1), reverse=True) context['school_active_count'] = School.objects.filter(pk__in = active_school_reporters.values_list('schools__pk', flat=True)).count() context['school_active'] = school_active[:3] context['school_less_active'] = school_active[-3:] return context else: return self.render_to_response(dashboard(self.request)) def get_term_range(term): if term == 'first': return [getattr(settings,'FIRST_TERM_BEGINS'),dateutils.increment(getattr(settings,'FIRST_TERM_BEGINS'),weeks=12)] if term == 'second': return [getattr(settings,'SECOND_TERM_BEGINS'),dateutils.increment(getattr(settings,'SECOND_TERM_BEGINS'),weeks=12)] if term == 'third': return [getattr(settings,'THIRD_TERM_BEGINS'),dateutils.increment(getattr(settings,'THIRD_TERM_BEGINS'),weeks=12)] if term == '' or term =='current' or term is None: return [getattr(settings,'SCHOOL_TERM_START'),getattr(settings,'SCHOOL_TERM_END')] class CapitationGrants(TemplateView): poll_name ='' restrict_group='' def compute_percent(self, x, y): try: return (100 * x) / y except ZeroDivisionError: return 0 def _extract_info(self, list): to_ret = [] for item in list: to_ret.append( [item.get('category__name'), item.get('value')] ) final_ret = {} for li in to_ret: final_ret[li[0]] = li[1] total = sum(filter(None, final_ret.values())) for key in final_ret.keys(): final_ret[key] = self.compute_percent(final_ret.get(key), total) return final_ret def _get_per_category_responses_for_school(self, responses_by_category, school): info = [stat for stat in responses_by_category if stat['response__contact__emisreporter__schools__name'] == school.name] return school, self._extract_info(info).items() def _get_schools_info(self, responses_at_location,location): responses_by_category = responses_at_location.values( 'response__contact__emisreporter__schools__name', 'category__name').annotate(value=Count('pk')) schools = location.schools.all() return [self._get_per_category_responses_for_school(responses_by_category, school) for school in schools] def get_context_data(self, **kwargs): term = self.kwargs.get('term') term_range = get_term_range(term) context = super(CapitationGrants, self).get_context_data(**kwargs) cg = Poll.objects.select_related().get(name=self.poll_name) authorized_users = ['Admins', 'Ministry Officials', 'UNICEF Officials'] authorized_user = False for auth_user in authorized_users: if self.request.user.get_profile().is_member_of(auth_user): authorized_user = True break context['authorized_user'] = authorized_user er = EmisReporter.objects.select_related() unknown_unknowns = cg.responses.filter(~Q(message__text__iregex="i don('?)t know"), categories__category__name="unknown") if authorized_user: reporter_count = er.filter(groups__name=self.restrict_group).exclude(schools=None).count() all_responses = cg.responses_by_category().exclude(response__in=unknown_unknowns).filter(response__date__range=term_range) locs = Location.objects.filter( type="district", pk__in= \ er.exclude(connection__in=Blacklist.objects. \ values_list('connection', flat=True), schools=None).filter(groups__name=self.restrict_group). \ values_list('reporting_location__pk', flat=True)) districts_to_ret = [] for location in locs: info = self._extract_info(all_responses.filter(response__contact__reporting_location=location)) districts_to_ret.append((location, info.items())) total_responses = all_responses.values_list('response__contact').distinct().count() context['responses'] = self._extract_info(all_responses).items() context['location'] = Location.tree.root_nodes()[0] context['sub_locations'] = districts_to_ret context['sub_location_type'] = "district" else: location = self.request.user.get_profile().location all_responses = cg.responses_by_category().exclude(response__in=unknown_unknowns).filter(response__date__range=term_range) responses_at_location = all_responses.filter(response__contact__reporting_location=location) total_responses = responses_at_location.values_list('response__contact').distinct().count() reporter_count = er.exclude(schools=None, connection__in= \ Blacklist.objects.values_list('connection', flat=True)).filter(groups__name=self.restrict_group, \ reporting_location=location).count() context['responses'] = self._extract_info(responses_at_location).items() context['location'] = location context['sub_locations'] = self._get_schools_info(responses_at_location, location) context['sub_location_type'] = "school" context['reporter_count'] = self.compute_percent(total_responses, reporter_count) context['group'] = self.restrict_group return context # Details views... specified by ROLES def set_logged_in_users_location(profile): if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of( 'Admins'): location = Location.objects.get(name='Uganda') else: location = profile.location return location def violence_details_dash(req): profile = req.user.get_profile() context_vars = {} location = set_logged_in_users_location(profile) violence_cases_girls = poll_response_sum("edtrac_violence_girls", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_boys = poll_response_sum("edtrac_violence_boys", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_reported = poll_response_sum("edtrac_violence_reported", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_gem = poll_response_sum('edtrac_gem_abuse', location=location, month_filter='monthly', months=2, ret_type=list) girls_total = [] for name, list_val in violence_cases_girls: girls_total.append((list_val[0], list_val[1])) context_vars['violence_cases_girls'] = violence_cases_girls girls_first_col, girls_second_col = [],[] for first, second in girls_total: girls_first_col.append(first), girls_second_col.append(second) girls_first_col = [i for i in girls_first_col if i != '--'] girls_second_col = [i for i in girls_second_col if i != '--'] context_vars['girls_totals'] = [sum(girls_first_col), sum(girls_second_col)] boys_total = [] for name, list_val in violence_cases_boys: boys_total.append((list_val[0], list_val[1])) context_vars['violence_cases_boys'] = violence_cases_boys boys_first_col, boys_second_col = [],[] for first, second in boys_total: boys_first_col.append(first), boys_second_col.append(second) boys_first_col = [i for i in boys_first_col if i != '--'] boys_second_col = [i for i in boys_second_col if i != '--'] context_vars['boys_totals'] = [sum(boys_first_col), sum(boys_second_col)] reported_total = [] for name, list_val in violence_cases_reported: reported_total.append((list_val[0], list_val[1])) context_vars['violence_cases_reported'] = violence_cases_reported reported_first_col, reported_second_col = [],[] for first, second in reported_total: reported_first_col.append(first), reported_second_col.append(second) reported_first_col = [i for i in reported_first_col if i != '--'] reported_second_col = [i for i in reported_second_col if i != '--'] context_vars['reported_totals'] = [sum(reported_first_col), sum(reported_second_col)] gem_total = [] # total violence cases reported by school for name, list_val in violence_cases_gem: gem_total.append((list_val[0], list_val[1])) context_vars['violence_cases_reported_by_gem'] = violence_cases_gem first_col, second_col = [],[] for first, second in gem_total: first_col.append(first), second_col.append(second) first_col = [i for i in first_col if i != '--'] second_col = [i for i in second_col if i != '--'] context_vars['gem_totals'] = [sum(first_col), sum(second_col)] context_vars['report_dates'] = [start for start, end in get_month_day_range(datetime.datetime.now(), depth=2)] school_report_count = 0 gem_report_count = 0 for dr in get_month_day_range(datetime.datetime.now(), depth=2): if profile.location.type.name == 'country': contacts = Contact.objects.select_related().filter(reporting_location__in=profile.\ location.get_descendants().filter(type="district")) else: contacts = Contact.objects.select_related().filter(reporting_location=profile.location) school_resp_count = Poll.objects.select_related().get(name="edtrac_violence_girls").responses.filter( contact__in = contacts, date__range = dr).count() gem_resp_count = Poll.objects.select_related().get(name="edtrac_gem_abuse").responses.filter( contact__in = contacts, date__range = dr).count() school_report_count += school_resp_count gem_report_count += gem_resp_count try: context_vars['sch_reporting_percentage'] = 100 * ( school_report_count / (float(len(get_month_day_range(datetime.datetime.now(), depth=2))) * school_report_count)) except ZeroDivisionError: context_vars['sch_reporting_percentage'] = 0 try: context_vars['gem_reporting_percentage'] = 100 * ( gem_report_count / (float(len(get_month_day_range(datetime.datetime.now(), depth=2))) * gem_report_count)) except ZeroDivisionError: context_vars['gem_reporting_percentage'] = 0 now = datetime.datetime.now() month_ranges = get_month_day_range(now, depth=now.month) month_ranges.sort() h_teach_month = [] girls_violence_month = [] boys_violence_month =[] reported_violence_month = [] h_teach_data = [] gem_data = [] girls_violence_data = [] boys_violence_data = [] reported_violence_data = [] if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Admins'): for month_range in month_ranges: h_teach_month.append(month_range[0].strftime('%B')) h_teach_data.append(get_numeric_report_data('edtrac_violence_girls',time_range=month_range, to_ret = 'sum')) gem_data.append(get_numeric_report_data('edtrac_gem_abuse',time_range=month_range, to_ret = 'sum')) girls_violence_month.append(month_range[0].strftime('%B')) girls_violence_data.append(get_numeric_report_data('edtrac_violence_girls', time_range=month_range, to_ret='sum')) boys_violence_month.append(month_range[0].strftime('%B')) boys_violence_data.append(get_numeric_report_data('edtrac_violence_boys', time_range=month_range, to_ret='sum')) reported_violence_month.append(month_range[0].strftime('%B')) reported_violence_data.append(get_numeric_report_data('edtrac_violence_reported', time_range=month_range, to_ret='sum')) else: for month_range in month_ranges: h_teach_month.append(month_range[0].strftime('%B')) h_teach_data.append(get_numeric_report_data('edtrac_girls_violence',time_range=month_range, to_ret = 'sum', location=profile.location)) gem_data.append(get_numeric_report_data('edtrac_gem_abuse',time_range=month_range, to_ret = 'sum', location=profile.location)) girls_violence_month.append(month_range[0].strftime('%B')) girls_violence_data.append(get_numeric_report_data('edtrac_violence_girls', time_range=month_range, to_ret='sum', location=profile.location)) boys_violence_month.append(month_range[0].strftime('%B')) boys_violence_data.append(get_numeric_report_data('edtrac_violence_boys', time_range=month_range, to_ret='sum', location=profile.location)) reported_violence_month.append(month_range[0].strftime('%B')) reported_violence_data.append(get_numeric_report_data('edtrac_violence_reported', time_range=month_range, to_ret='sum', location=profile.location)) monthly_data_h_teachers = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(h_teach_month, h_teach_data)]) monthly_violence_data_girls = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(girls_violence_month, girls_violence_data)]) monthly_violence_data_boys = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(boys_violence_month, boys_violence_data)]) monthly_violence_data_reported = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(reported_violence_month, reported_violence_data)]) gem_month = copy.deepcopy(h_teach_month) monthly_data_gem = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(gem_month, gem_data)]) context_vars['monthly_data_gem'] = monthly_data_gem context_vars['monthly_violence_data_girls'] = monthly_violence_data_girls context_vars['monthly_violence_data_boys'] = monthly_violence_data_boys context_vars['monthly_violence_data_reported'] = monthly_violence_data_reported context_vars['monthly_data_h_teach'] = monthly_data_h_teachers context_vars['schools_responding_to_all_questions'] = total_number_of_schools_that_responded_to_all_violence_questions() if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Admins'): return render_to_response('education/admin/admin_violence_details.html', context_vars, RequestContext(req)) elif profile.is_member_of('DEO'): context_vars['location_name'] = profile.location return render_to_response('education/deo/deo2_violence_details.html', context_vars, RequestContext(req)) def total_number_of_schools_that_responded_to_all_violence_questions(): schools_responding_to_boys_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_boys")] schools_responding_to_girls_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_girls")] schools_that_referred_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_reported")] schools_that_answered_all_questions = list(set(schools_responding_to_boys_violence).intersection(schools_responding_to_girls_violence).intersection(schools_that_referred_violence)) valid_school_names = [school for school in schools_that_answered_all_questions if school is not None] return len(valid_school_names) def __get_school_name_from(response): try: school_name = response.contact.emisreporter.schools.all()[0].name except IndexError: school_name = None return school_name def __get_responses_for(poll_name): responses_for_all_questions = Response.objects.filter(poll__name__in =["edtrac_violence_girls","edtrac_violence_boys","edtrac_violence_reported"]) return responses_for_all_questions.filter(poll__name = poll_name) class DistrictViolenceDetails(TemplateView): template_name = "education/dashboard/district_violence_detail.html" def get_context_data(self, **kwargs): context = super(DistrictViolenceDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) or self.request.user.get_profile().location schools = School.objects.filter( pk__in = EmisReporter.objects.filter(reporting_location=location).values_list('schools__pk', flat=True)) school_case = [] month_now, month_before = get_month_day_range(datetime.datetime.now(), depth=2) totalViolence = 0 nowViolence = 0 beforeViolence = 0 for school in schools: # optimize with value queries now_data = get_numeric_report_data( 'edtrac_headteachers_abuse', time_range = month_now, school = school, to_ret = 'sum', belongs_to = 'schools') before_data = get_numeric_report_data('edtrac_headteachers_abuse', time_range = month_before, school = school,\ to_ret = 'sum', belongs_to = 'schools') data = int(now_data + before_data) totalViolence += data nowViolence += now_data beforeViolence += before_data if now_data > 0 or before_data > 0: school_case.append((school, now_data, before_data, data)) context['totalViolence'] = totalViolence context['nowViolence'] = nowViolence context['beforeViolence'] = beforeViolence context['location'] = location context['school_vals'] = school_case context['month_now'] = month_now[0] context['month_before'] = month_before[0] return context class AttendanceAdminDetails(TemplateView): template_name = "education/admin/attendance_details.html" def get_context_data(self, **kwargs): context = super(AttendanceAdminDetails, self).get_context_data(**kwargs) #TODO: proper drilldown of attendance by school # National level ideally "admin" and can be superclassed to suit other roles profile = self.request.user.get_profile() context['role_name'] = profile.role.name if profile.is_member_of("Admins") or profile.is_member_of("Ministry Officials") or profile.is_member_of('UNICEF Officials'): names = list(set(EmisReporter.objects.exclude(reporting_location=None).filter(reporting_location__type="district").\ values_list('reporting_location__name',flat=True))) locations = Location.objects.filter(name__in=names).order_by("name") context['total_disticts'] = locations.count() headings = [ 'Location', 'Boys P3', 'Boys P6', 'Girls P3', 'Girls P6', 'Female Teachers', "Male Teachers"] context['headings'] = headings context['week'] = datetime.datetime.now() context['location'] = profile.location return context # search functionality def search_form(req): searchform = SearchForm() if req.method == 'POST': searchform = SearchForm(req.POST) if searchform.is_valid(): searchform.save() return render_to_response( 'education/partials/search-form.html', {'form': searchform}, RequestContext(req) ) class ProgressAdminDetails(TemplateView): template_name = "education/progress/admin_progress_details.html" def get_context_data(self, **kwargs): context = super(ProgressAdminDetails, self).get_context_data(**kwargs) context['progress'] = list_poll_responses(Poll.objects.get(name="edtrac_p3curriculum_progress")) getcontext().prec = 1 context['progress_figures'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_p3curriculum_progress"),\ location=self.request.user.get_profile().location, choices = [Decimal(str(key)) for key in themes.keys()]) return context CHOICES = [0, 25, 50, 75, 100] class MealsAdminDetails(TemplateView): template_name = "education/admin/admin_meals_details.html" def get_context_data(self, **kwargs): choices = CHOICES context = super(MealsAdminDetails, self).get_context_data(**kwargs) context['school_meals_reports'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_headteachers_meals"),\ month_filter=True, choices=choices) context['community_meals_reports'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_smc_meals"), month_filter=True, choices=choices, with_percent=True) districts = Location.objects.filter(type="district", id__in =\ EmisReporter.objects.exclude(reporting_location = None).\ values_list('reporting_location__id', flat=True)).order_by('name').\ values_list('name', flat=True) # basic filtering for CSS districts = [[d, False] for d in districts] districts[0][1] = True context['districts'] = districts return context # Meals being had at a district class DistrictMealsDetails(DetailView): template_name = "education/admin/district_meal.html" context_object_name = "district_meals" model = Location def get_object(self): return self.model.objects.filter(type="district").get(name = self.kwargs.get('name')) def get_context_data(self, **kwargs): context = super(DistrictMealsDetails, self).get_context_data(**kwargs) location = self.get_object() choices = CHOICES school_meal_reports = get_count_response_to_polls( Poll.objects.get(name="edtrac_headteachers_meals"), location_name = location.name, month_filter=True, choices=choices, with_range = True, with_percent = True ) context['school_meals_reports'] = school_meal_reports context['location'] = location now = datetime.datetime.now() ranges = get_month_day_range(now, depth = now.month) ranges.reverse() context['date_ranges'] = ranges return context @login_required def deo_dashboard(req): location = req.user.get_profile().location return render_to_response("education/deo/deo_dashboard.html", generate_dashboard_vars(location=location), RequestContext(req)) @login_required def quitters(req): quitters = EmisReporter.objects.filter(connection__identity__in=Blacklist.objects.values_list('connection__identity',flat=True)) return render_to_response('education/partials/reporters/quitters.html',{'quitters':quitters}, RequestContext(req)) class ViolenceDeoDetails(TemplateView): template_name = "education/deo/deo_violence_details.html" def get_context_data(self, **kwargs): context = super(ViolenceDeoDetails, self).get_context_data(**kwargs) #context['violence_cases'] = list_poll_responses(Poll.objects.get(name="emis_headteachers_abuse")) context['violence_cases'] = poll_response_sum(Poll.objects.get(name="edtrac_headteachers_abuse"), location=self.request.user.get_profile().location, month_filter=True) return context @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ViolenceDeoDetails, self).dispatch(*args, **kwargs) class ProgressDeoDetails(TemplateView): template_name = "education/deo/deo_progress_details.html" def get_context_data(self, **kwargs): context = super(ProgressDeoDetails, self).get_context_data(**kwargs) #TODO mixins and filters context['progress'] = list_poll_responses(Poll.objects.get(name="edtrac_p3curriculum_progress")) return context ########################################################################################################## ########################################################################################################## ############################ More Generic Views ########################################################## ########################################################################################################## ########################################################################################################## ## management control panel @login_required def control_panel(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Ministry Officials'): return render_to_response('education/partials/control_panel.html', {}, RequestContext(req)) else: return render_to_response('education/partials/control_panel_dist.html',{}, RequestContext(req)) @login_required def audit_trail(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): # aparently the only places where comments are made is functions that involve editing users, reporters, etc. revisions = Revision.objects.exclude(comment='').order_by('-date_created').values_list('user__username','comment','date_created') else: revisions = Revision.objects.exclude(user__username = 'admin', comment='').\ order_by('-date_created').values_list('user__username','comment','date_created') return render_to_response('education/admin/audit_trail.html',{'revisions':revisions}, RequestContext(req)) class DistrictViolenceCommunityDetails(DetailView): context_object_name = "district_violence" model = Location def get_context_data(self, **kwargs): context = super(DistrictViolenceCommunityDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) or self.request.user.get_profile().location emis_reporters = EmisReporter.objects.filter(groups__name="GEM", connection__in =\ Poll.objects.get(name="edtrac_gem_abuse").responses.values_list('contact__connection',flat=True)) context['location'] = location context['reporters'] = emis_reporters context['month'] = datetime.datetime.now() return context # Progress happening in a district class DistrictProgressDetails(DetailView): context_object_name = "district_progress" model = Location #TODO provide filters def get_context_data(self, **kwargs): context = super(DistrictProgressDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) context['location'] = location return context ########################################################################################################## ########################################################################################################## ################################ Other handy views for EduTrac ############################################ ########################################################################################################## ########################################################################################################## HEADINGS = ['District', 'Absent (%) This week', 'Absent (%) Last week'] #define location and school for p3 and p6 students locale = Location.objects.exclude(type="country").filter(type="district") @login_required def boysp3_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_boysp3_enrollment','edtrac_boysp3_attendance') return render_to_response("education/boysp3_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data', 'Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def boysp6_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_boysp6_enrollment','edtrac_boysp6_attendance') return render_to_response("education/boysp6_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def girlsp3_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_girlsp3_enrollment','edtrac_girlsp3_attendance') return render_to_response("education/girlsp3_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def girlsp6_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_girlsp6_enrollment','edtrac_girlsp6_attendance') return render_to_response("education/girlsp6_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def female_t_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_f_teachers_deployment','edtrac_f_teachers_attendance') return render_to_response("education/female_t_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def male_t_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_m_teachers_deployment','edtrac_m_teachers_attendance') return render_to_response("education/male_t_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) def boys_p3_attendance(req, **kwargs): profile = req.user.get_profile() location = profile.location if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): """ This view shows data by district """ locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.select_related().distinct().values_list('reporting_location__name', flat=True)).order_by("name") # return view that will give school-based views # --> ref function just below this <--- return boys_p3_attd_admin(req, locations=locations) else: #DEO dates = kwargs.get('dates') schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] for d in dates: temp.extend(return_absent('edtrac_boysp3_attendance', 'edtrac_boysp3_enrollment', school = school, date_week=d)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location':location } def boys_p3_attd_admin(req, **kwargs): """ Helper function to get differences in absenteeism across districts. """ # P3 attendance /// what to show an admin or Ministry official locations = kwargs.get('locations') to_ret = return_absent('edtrac_boysp3_attendance', 'edtrac_boysp3_enrollment', locations) return {'location_data':to_ret, 'headings': HEADINGS, 'week':datetime.datetime.now()} def boys_p6_attendance(req): profile = req.user.get_profile() location = profile.location if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return boys_p6_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_boysp6_attendance', 'edtrac_boysp6_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def boys_p6_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P6 boys. """ # P6 attendance /// what to show an admin or Ministry official to_ret = return_absent('edtrac_boysp6_attendance', 'edtrac_boysp6_enrollment', locations=locations) return {'location_data':to_ret,'headings':HEADINGS,'week':datetime.datetime.now()} def girls_p3_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return girls_p3_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_girlsp3_attendance', 'edtrac_girlsp3_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def girls_p3_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P3 girls """ to_ret = return_absent('edtrac_girlsp3_attendance', 'edtrac_girlsp3_enrollment', locations=locations) return {'location_data':to_ret,'headings':HEADINGS,'week':datetime.datetime.now()} def girls_p6_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return girls_p6_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_girlsp6_attendance', 'edtrac_girlsp6_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def girls_p6_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P6 girls """ to_ret = return_absent('edtrac_girlsp6_attendance', 'edtrac_girlsp6_enrollment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def female_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.distinct().values_list('reporting_location__name',flat=True)).order_by("name") return female_teacher_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_f_teachers_attendance', 'edtrac_f_teachers_deployment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def female_teacher_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for all female teachers """ to_ret = return_absent('edtrac_f_teachers_attendance', 'edtrac_f_teachers_deployment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def male_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.distinct().values_list('reporting_location__name',flat=True)).order_by("name") return male_teacher_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_m_teachers_attendance', 'edtrac_m_teachers_deployment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def male_teacher_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for all female teachers """ to_ret = return_absent('edtrac_m_teachers_attendance', 'edtrac_m_teachers_deployment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def male_head_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): schools = School.objects.filter(location__name__in=EmisReporter.objects.distinct().\ filter(reporting_location__type = 'district').values_list('reporting_location__name', flat=True)) else: #DEO schools = School.objects.filter(location=location) data_to_render = [] for school in schools: #TODO separate male and female head teachers data = poll_response_sum(Poll.objects.get(name="edtrac_head_teachers_attendance"),month_filter='weekly',location=school.location) data_to_render.append( [ school, school.location, data ] ) return render_to_response( 'education/partials/male_head_teacher_attendance.html', { 'week':datetime.datetime.now(), 'headings':['School', 'District', 'Number'], 'location_data': data_to_render }, RequestContext(req) ) def female_head_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): schools = School.objects.filter(location__name__in= EmisReporter.objects.distinct().\ select_related().filter(reporting_location__type = 'district').values_list('reporting_location__name', flat=True)) else: #DEO schools = School.objects.select_related().filter(location=location).order_by("name", "location__name") data_to_render = [] for school in schools: #TODO separate male and female head teachers data = poll_response_sum(Poll.objects.get(name="edtrac_head_teachers_attendance"),month_filter='weekly',location=school.location) data_to_render.append( [ school, school.location, data ] ) return render_to_response( 'education/partials/female_head_teacher_attendance.html', { 'week':datetime.datetime.now(), 'headings':['School', 'District', 'Number'], 'location_data': data_to_render }, RequestContext(req) ) @login_required def time_range_boysp3(req): return view_stats(req, enrol_deploy_poll='edtrac_boysp3_enrollment', attendance_poll='edtrac_boysp3_attendance', title='P3 Boys Absenteeism', url_name_district = "boysp3-district-attd-detail" ) @login_required def time_range_boysp6(req): return view_stats(req, enrol_deploy_poll='edtrac_boysp6_enrollment', attendance_poll='edtrac_boysp6_attendance', title='P6 Boys Absenteeism', url_name_district = "boysp6-district-attd-detail" ) @login_required def time_range_girlsp3(req): return view_stats(req, enrol_deploy_poll='edtrac_girlsp3_enrollment', attendance_poll='edtrac_girlsp3_attendance', title='P3 Girls Absenteeism', url_name_district = "girlsp3-district-attd-detail" ) @login_required def time_range_girlsp6(req): return view_stats(req, enrol_deploy_poll='edtrac_girlsp6_enrollment', attendance_poll='edtrac_girlsp6_attendance', title='P6 Girls Absenteeism', url_name_district = "girlsp6-district-attd-detail" ) @login_required def time_range_teachers_m(req): return view_stats(req, enrol_deploy_poll='edtrac_m_teachers_deployment', attendance_poll='edtrac_m_teachers_attendance', title='Male teachers absenteeism', url_name_district = "male-teacher-district-attd-detail" ) @login_required def time_range_teachers_f(req): return view_stats(req, enrol_deploy_poll='edtrac_f_teachers_deployment', attendance_poll='edtrac_f_teachers_attendance', title='Female teachers absenteeism', url_name_district = "female-teacher-district-attd-detail" ) @login_required def time_range_head_teachers(req): """ Get a date-ranged page for Head teachers """ """ A function that compute time-ranged data for female teachers. This function is split in two: handling of POST data and GET data. It also makes a difference between User groups so you different role players like DEO, Admins, UNICEF Officials """ time_range_form = ResultForm() locations = Location.objects.filter(type='district').filter(pk__in = EmisReporter.objects.values_list('reporting_location__pk',flat=True)) if req.method == 'POST': # handling of POST data time_range_form = ResultForm(data=req.POST) to_ret = [] if time_range_form.is_valid(): from_date = time_range_form.cleaned_data['from_date'] to_date = time_range_form.cleaned_data['to_date'] month_delta = abs(from_date.month - to_date.month) date_weeks = [] if month_delta <= 2: # same month get days in between while from_date <= to_date: if from_date.weekday() == 3: #is to_day a Thursday? date_weeks.append(previous_calendar_week(t = from_date)) # get range from Wed to Thur. from_date += datetime.timedelta(days = 1) else: # case for when more than 2 months is selected while from_date <= to_date: #TODO refine data points date_weeks.append([dateutils.month_start(from_date),dateutils.month_end(from_date)]) from_date = dateutils.increment(from_date, months = 1) # splitting the results by analysing membership of Officials accessing EduTrac if req.user.get_profile().is_member_of('Ministry Officials') or\ req.user.get_profile().is_member_of('Admins') or req.user.get_profile().is_member_of('UNICEF Officials'): schools_temp = School.objects.select_related().\ filter(pk__in = EmisReporter.objects.select_related().\ filter(groups__name = "Head Teachers").values_list('schools__pk',flat=True)) for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True).select_related() location_schools = School.objects.filter(pk__in = schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) else: #Non admin types date_weeks, to_ret = [], [] date_weeks.append(previous_calendar_week(t = datetime.datetime.now())) for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True) location_schools = School.objects.filter(pk__in=schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) return render_to_response('education/timeslider_base.html', {'form':time_range_form, 'dataset':to_ret, 'title':'Female Teacher Absenteeism', 'url_name':"female-teacher-district-attd-detail", 'date_batch':date_weeks}, RequestContext(req)) else: return render_to_response('education/timeslider_base.html', {'form':time_range_form, 'url_name':"female-teacher-district-attd-detail", 'title':'Male Teacher Absenteeism'}, RequestContext(req)) else: # initial GET view is displays difference between 2 weeks of the attendance of female teachers as reported by the Head Teacher date_weeks = [] location_data = [] # get current week date_weeks.append(previous_calendar_week()) temp_date = datetime.datetime(date_weeks[0][0].year, date_weeks[0][0].month, date_weeks[0][0].day) - datetime.timedelta(days = 1) # add previous week to date_weeks list date_weeks.append(previous_calendar_week(t = temp_date)) # cache schools query in memory (these are Schools that have enrollment data) schools_temp = Poll.objects.select_related().get(name = 'edtrac_f_teachers_deployment').responses.\ exclude(contact__emisreporter__schools__name = None).select_related() context_vars = {} for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True) location_schools = School.objects.filter(pk__in = schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) try: diff = temp[0] - temp[1] except TypeError: diff = '--' location_data.append([location, temp[0], temp[1], diff]) context_vars.update({'location_data':location_data}) profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): x = {'url_name':"female-teacher-district-attd-detail", "headings":["District", "Current Week", "Previous Week", "Percentage Change"]} else: x = {'url_name':"school-detail", "headings":["School", "Current Week", "Previous Week", "Percentage Change"]} context_vars.update({'form':time_range_form,'title':'Female Teachers Absenteeism'}) context_vars.update(x) return render_to_response('education/timeslider_base.html', context_vars, RequestContext(req)) def whitelist(request): numbers = [] for c in Connection.objects.exclude(backend__name='yo6200'): if not c.identity.strip() in numbers: numbers.append(c.identity.strip()) return render_to_response( "education/whitelist.txt", {'connections': Connection.objects.exclude(backend__name='yo6200').filter(identity__in=numbers)}, mimetype="text/plain", context_instance=RequestContext(request)) def _reload_whitelists(): refresh_urls = getattr(settings, 'REFRESH_WHITELIST_URL', None) if refresh_urls is not None: if not type(refresh_urls) == list: refresh_urls = [refresh_urls, ] for refresh_url in refresh_urls: try: status_code = urlopen(refresh_url).getcode() if int(status_code / 100) == 2: continue else: return False except Exception as e: return False return True return False def _addto_autoreg(connections): for connection in connections: if not connection.contact and\ not ScriptProgress.objects.filter(script__slug='emis_autoreg', connection=connection).count(): ScriptProgress.objects.create(script=Script.objects.get(slug="edtrac_autoreg"),\ connection=connection) @login_required def add_connection(request): form = NewConnectionForm() if request.method == 'POST': form = NewConnectionForm(request.POST) connections = [] if form.is_valid(): identity = form.cleaned_data['identity'] identity, backend = assign_backend(str(identity.strip())) # create connection, created = Connection.objects.get_or_create(identity=identity, backend=backend) # in case a duplicate process does exist, delete it ScriptProgress.objects.filter(connection=connection).delete() connections.append(connection) other_numbers = request.POST.getlist('other_nums') if len(other_numbers) > 0: for number in other_numbers: identity, backend = assign_backend(str(number.strip())) connection, created = Connection.objects.get_or_create(identity=identity, backend=backend) connections.append(connection) _addto_autoreg(connections) _reload_whitelists() # time.sleep(2) return render_to_response('education/partials/addnumbers_row.html', {'object':connections, 'selectable':False}, RequestContext(request)) return render_to_response("education/partials/new_connection.html", {'form':form}, RequestContext(request)) @login_required def delete_connection(request, connection_id): connection = get_object_or_404(Connection, pk=connection_id) connection.delete() _reload_whitelists() return render_to_response("education/partials/connection_view.html", {'object':connection.contact }, context_instance=RequestContext(request)) @login_required def comments(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('Ministry Officials') or profile.is_member_of('UNICEF Officials'): comments = [(r.get_commentable_display(), r.comment, r.user, r.get_reporting_period_display(), get_range_on_date(r.reporting_period, r) ) for r in ReportComment.objects.order_by('-report_date')] else: # DFO/DEO should get only information on their districts comments = [(r.get_commentable_display(), r.comment, r.user, r.get_reporting_period_display(), get_range_on_date(r.reporting_period, r)) for r in ReportComment.objects.filter(user__profile__location=profile.location).order_by('-report_date')] return render_to_response('education/partials/comments.html', {'data_set':comments}, RequestContext(req)) @login_required def new_comment(req): report_comment_form = ReportCommentForm(initial = {'user':req.user.pk}) if req.method == 'POST': report_comment_form = ReportCommentForm(req.POST) if report_comment_form.is_valid(): with reversion.create_revision(): report_comment_form.save() reversion.set_comment('wrote a comment') return HttpResponseRedirect(reverse('comments')) else: return render_to_response('education/partials/new_comment.html', {'form':report_comment_form}, RequestContext(req)) else: return render_to_response('education/partials/new_comment.html',{'form':report_comment_form}, RequestContext(req)) @login_required def edit_comment(req, report_comment_pk): report_comment = get_object_or_404(ReportComment, pk=report_comment_pk) report_comment_form = ReportCommentForm(instance=report_comment) if req.method == 'POST': report_comment_form = ReportCommentForm(instance=report_comment, data=req.POST) if report_comment_form.is_valid(): with reversion.create_revision(): report_comment_form.save() reversion.set_comment('edited comment') return HttpResponseRedirect(reverse('comments')) else: return render_to_response('education/partials/edit_comment.html', {'form':report_comment_form}, RequestContext(req)) else: return render_to_response('education/partials/edit_comment.html', {'form':report_comment_form}, RequestContext(req)) @login_required def delete_comment(req, report_comment_pk): report_comment = get_object_or_404(ReportComment, pk=report_comment_pk) if req.method == 'POST': with reversion.create_revision(): report_comment.delete() reversion.set_comment('deleted comment') return HttpResponse(status=200) @login_required def delete_reporter(request, reporter_pk): reporter = get_object_or_404(EmisReporter, pk=reporter_pk) reporter_name = reporter.name if request.method == 'POST': with reversion.create_revision(): reversion.set_comment('deleted %s'%reporter_name) reporter.delete() return HttpResponse(status=200) @login_required def edit_reporter(request, reporter_pk): reporter = get_object_or_404(EmisReporter, pk=reporter_pk) reporter_group_name = reporter.groups.all()[0].name if request.method == 'POST': reporter_form = EditReporterForm(instance=reporter,data=request.POST) if reporter_form.is_valid(): with reversion.create_revision(): reporter_form.save() reversion.set_comment('edited %s details' % reporter.name) saved_reporter_grp = EmisReporter.objects.get(pk=reporter_pk).groups.all()[0].name if reporter.default_connection and reporter.groups.count() > 0: # remove from other scripts # if reporter's groups remain the same. if reporter_group_name == saved_reporter_grp: pass else: ScriptProgress.objects.exclude(script__slug="edtrac_autoreg").filter(connection=reporter.default_connection).delete() _schedule_teacher_weekly_scripts(reporter.groups.all()[0], reporter.default_connection, ['Teachers']) _schedule_weekly_scripts(reporter.groups.all()[0], reporter.default_connection, ['Head Teachers', 'SMC']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_head_teachers_monthly', 'last', ['Head Teachers']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_gem_monthly', 20, ['GEM']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_smc_monthly', 5, ['SMC']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_smc_termly', ['SMC']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_p3_enrollment_headteacher_termly', ['Head Teachers']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_p6_enrollment_headteacher_termly', ['Head Teachers']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_teacher_deployment_headteacher_termly', ['Head Teachers']) return redirect("reporter-detail", pk=reporter.pk) else: if reporter.schools.exists(): reporter_form = EditReporterForm(instance=reporter, initial={'schools':reporter.schools.all()[0]}) else: reporter_form = EditReporterForm(instance=reporter) return render_to_response('education/edit_reporter.html', {'reporter_form': reporter_form, 'reporter': reporter}, context_instance=RequestContext(request)) @login_required def add_schools(request): if request.method == 'POST': form = SchoolForm(request.POST) schools = [] if form.is_valid(): names = filter(None, request.POST.getlist('name')) locations = request.POST.getlist('location') if len(names) > 0: for i, name in enumerate(names): location = Location.objects.get(pk=int(locations[i])) name, created = School.objects.get_or_create(name=name, location=location) schools.append(name) return render_to_response('education/partials/addschools_row.html', {'object':schools, 'selectable':False}, RequestContext(request)) else: form = SchoolForm() return render_to_response('education/deo/add_schools.html', {'form': form, }, context_instance=RequestContext(request)) @login_required def delete_school(request, school_pk): school = get_object_or_404(School, pk=school_pk) school_name = school.name if request.method == 'POST': with reversion.create_revision(): school.delete() reversion.set_comment("%s deleted %s"%(request.user.username, school_name)) return HttpResponse(status=200) @login_required def edit_school(request, school_pk): school = get_object_or_404(School, pk=school_pk) school_form = SchoolForm(instance=school) school_name = school.name if request.method == 'POST': school_form = SchoolForm(instance=school, data=request.POST) if school_form.is_valid(): with reversion.create_revision(): school_form.save() reversion.set_comment('edited %s' % school_name) else: return render_to_response('education/partials/edit_school.html' , {'school_form': school_form, 'school' : school}, context_instance=RequestContext(request)) return render_to_response('/education/partials/school_row.html', {'object':School.objects.get(pk=school_pk), 'selectable':True}, context_instance=RequestContext(request)) else: return render_to_response('education/partials/edit_school.html', {'school_form': school_form, 'school': school}, context_instance=RequestContext(request)) @login_required def school_detail(request, school_id): school = School.objects.get(id=school_id) today = date.today() month_ranges = get_month_day_range(today, depth=today.month) month_ranges.reverse() slug_list = ['girlsp3', 'boysp3', 'girlsp6', 'boysp6'] slug_list_tr = ['f_teachers', 'm_teachers'] monthly_data = [] monthly_data_teachers = [] monthly_data_head_teachers = [] monthly_data_violence = [] monthly_data_meals = [] for month_range in month_ranges: monthly_data.append( [return_absent_month( 'edtrac_'+ '%s'%slug + '_attendance', 'edtrac_'+ '%s'%slug + '_enrollment', month_range = month_range, school = school) for slug in slug_list]) monthly_data_teachers.append( [return_absent_month( 'edtrac_'+'%s'%slug + '_attendance', 'edtrac_'+'%s'%slug + '_deployment', month_range = month_range, school=school) for slug in slug_list_tr]) reporters = [] reps = school.emisreporter_set.values() for rep in reps: r = EmisReporter.objects.get(id=rep['id']) reporters.append(r) boys_p3_enrolled = poll_responses_term('edtrac_boysp3_enrollment', belongs_to='schools', school = school) boys_p6_enrolled = poll_responses_term('edtrac_boysp6_enrollment', belongs_to='schools', school = school) girls_p3_enrolled = poll_responses_term('edtrac_girlsp3_enrollment', belongs_to='schools', school = school) girls_p6_enrolled = poll_responses_term('edtrac_girlsp6_enrollment', belongs_to='schools', school = school) m_teachers_deployed = poll_responses_term('edtrac_m_teachers_deployment', belongs_to = 'schools', school = school) f_teachers_deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to = 'schools', school = school) return render_to_response("education/school_detail.html", {\ 'school_name': school.name, 'months' : [d_start for d_start, d_end in month_ranges], 'monthly_data' : monthly_data, 'monthly_data_teachers' : monthly_data_teachers, 'monthly_data_head_teachers': monthly_data_head_teachers, 'monthly_data_violence' : monthly_data_violence, 'monthly_data_meals' : monthly_data_meals, 'reporters' : reporters, 'boys_p3_enrolled': boys_p3_enrolled, 'boys_p6_enrolled': boys_p6_enrolled, 'girls_p3_enrolled' : girls_p3_enrolled, 'girls_p6_enrolled' : girls_p6_enrolled, 'm_teachers_deployed': m_teachers_deployed, 'f_teachers_deployed': f_teachers_deployed }, RequestContext(request)) # analytics specific for emis {copy, but adjust to suit your needs} @login_required def to_excel(request, start_date=None, end_date=None, district_id=None): return create_excel_dataset(request, start_date, end_date, district_id) @login_required def school_reporters_to_excel(req): book = xlwt.Workbook() all_schools = School.objects.all() sheet = book.add_sheet('School Reporters') headings = ['School', 'Reporters'] rowx = 0 for colx, value in enumerate(headings): sheet.write(rowx, colx, value) sheet.set_panes_frozen(True) sheet.set_horz_split_pos(rowx+1) sheet.set_remove_splits(True) for row in all_schools: rowx += 1 for colx, value in enumerate([row.name, ', '.join([reporter.name for reporter in row.emisreporter_set.all()])]): sheet.write(rowx, colx, value) response = HttpResponse(mimetype="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment; filename=school_reporters_data.xls' book.save(response) return response @login_required def system_report(req=None): book = xlwt.Workbook() school_dates = [ getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END'), ] first_date = school_dates[0] last_date = school_dates[1] date_bunches = [] while first_date <= last_date: tmp = get_day_range(first_date) first_date = tmp[0] date_bunches.append(get_day_range(first_date)) first_date = dateutils.increment(first_date, weeks=1) profile = req.user.get_profile() enrolled_answered = \ EnrolledDeployedQuestionsAnswered.objects.select_related() headings = ['School'] + [d.strftime("%d/%m/%Y") for d, _ in date_bunches] if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): district_names = enrolled_answered.values_list( 'school__location__name', flat=True ).distinct() else: location = profile.location district_names = [location.name] district_schools = {} for dn in district_names: district_schools[dn] = School.objects.select_related().filter( pk__in=enrolled_answered.filter( school__location__name=dn ).values_list('school__pk', flat=True)).order_by('name') polls = Poll.objects.select_related().filter( Q(name__icontains="boys") | Q(name__icontains="girls") | Q(name='edtrac_f_teachers_attendance') | Q(name='edtrac_m_teachers_attendance') ) for district_name in district_schools.keys(): container = [] sheet = book.add_sheet(district_name, cell_overwrite_ok=True) rowx = 0 for colx, val_headings in enumerate(headings): sheet.write(rowx, colx, val_headings) sheet.set_panes_frozen(True) # in general, freeze after last heading row sheet.set_horz_split_pos(rowx + 1) # if user does unfreeze, don't leave a split there sheet.set_remove_splits(True) for school in district_schools[district_name]: school_vals = [school.name] for d_bunch in date_bunches: submission_count = 0 for poll in polls: submission_count += poll.responses.filter( contact__in=school.emisreporter_set.values_list( 'connection__contact'), date__range = d_bunch ).count() school_vals.extend([submission_count]) container.append(school_vals) for row in container: rowx += 1 for colx, value in enumerate(row): sheet.write(rowx, colx, value) response = HttpResponse(mimetype="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment; filename=SystemReport.xls' book.save(response) return response @login_required def excel_reports(req): return render_to_response('education/excelreports/excel_dashboard.html',{},RequestContext(req)) @login_required def edit_user(request, user_pk=None): title="" user=User() if request.method == 'POST' and request.user.get_profile().role_id == Role.objects.get(name = 'Admins').id: if user_pk: user = get_object_or_404(User, pk=user_pk) user_form = UserForm(request.POST,instance=user,edit=True) if user_form.is_valid(): with reversion.create_revision(): user = user_form.save() if user.groups.count() == 0: group = Group.objects.get(pk=user_form.cleaned_data['groups'][0].pk) user.groups.add(group) try: profile=UserProfile.objects.get(user=user) profile.location=user_form.cleaned_data['location'] profile.role=Role.objects.get(name=user_form.cleaned_data['groups'][0].name) profile.save() except UserProfile.DoesNotExist: UserProfile.objects.create(name=user.first_name,user=user,role=Role.objects.get(pk=user_form.cleaned_data['groups'][0].pk),location=user_form.cleaned_data['location']) reversion.set_comment("edited %s's profile" % user.username) return HttpResponseRedirect(reverse("emis-users")) elif user_pk: user = get_object_or_404(User, pk=user_pk) user_form = UserForm(instance=user,edit=True) title="Editing "+user.username else: user_form = UserForm(instance=user) return render_to_response('education/partials/edit_user.html', {'user_form': user_form,'title':title}, context_instance=RequestContext(request)) def htattendance(request, start_date=None, end_date=None, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) smc_htpresent = Poll.objects.get(name='emis_absence').responses.exclude(has_errors=True)\ .filter(date__range=(dates.get('start'), dates.get('end')))\ .filter(message__connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all())\ .order_by('message__date') return generic(request, model = Poll, queryset = smc_htpresent, objects_per_page = 50, results_title = 'Head Teacher Presence as Reported by SMCs', columns = [ ('school', False, 'school', None), ('present', False, 'present', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/ht_attendance_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timeslider_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) def gem_htattendance(request, start_date=None, end_date=None, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) gem_htpresent = XFormSubmission.objects.filter(xform__keyword='gemteachers').exclude(has_errors=True)\ .filter(created__range=(dates.get('start'), dates.get('end')))\ .filter(connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all())\ .order_by('created') return generic(request, model = XFormSubmission, queryset = gem_htpresent, objects_per_page = 50, results_title = 'Head Teacher Presence as Reported by GEM', columns = [ ('school', False, 'school', None), ('present', False, 'present', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/gemht_attendance_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timesli`der_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) def meals(request, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) meals = Poll.objects.get(name='emis_meals').responses.exclude(has_errors=True)\ .filter(date__range=(dates.get('start'), dates.get('end')))\ .filter(message__connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all()) return generic(request, model = Poll, queryset = meals, objects_per_page = 50, results_title = 'Pupils who had Meals at School', columns = [ ('school', False, 'school', None), ('estimated number', False, 'number', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/meals_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timeslider_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) @super_user_required def edit_scripts(request): forms = [] for script in Script.objects.exclude(name='Special Script').order_by('slug'): forms.append((script, ScriptsForm(instance=script))) if request.method == 'POST': script_form = ScriptsForm(request.POST,instance=Script.objects.get(slug=request.POST.get('slug'))) if script_form.is_valid(): script_form.save() return render_to_response('education/partials/edit_script.html', {'forms': forms, 'management_for': 'scripts'}, context_instance=RequestContext(request)) def emis_scripts_special(req): scripts = Script.objects.exclude(slug__icontains='weekly').exclude(name='Special Script').exclude(slug='edtrac_autoreg').order_by('slug') if req.method == 'POST': checked_numbers = req.POST.getlist('checked_numbers') checked_numbers = [n for n in checked_numbers if re.match(r'\d+', n)] poll_questions = req.POST.getlist('poll_questions') poll_scripts = [pq.split('-') for pq in poll_questions] #(poll_id, script_slug) d = datetime.datetime.now() _script = Script.objects.create(slug=\ "edtrac_%s %s %s %s:%s:%s"%(d.year,d.month,d.day,d.hour, d.minute, d.second), name="Special Script") _poll_scripts = [] # make sure that the poll/script to sent to just one group not a mixture of groups. reporter_group_name = EmisReporter.objects.get(id=checked_numbers[0]).groups.all()[0].name.lower().replace(' ', '_') for id, script_slug in poll_scripts: if re.search(reporter_group_name, script_slug): _poll_scripts.append((id, script_slug)) for i, li in enumerate(_poll_scripts): poll_id, script_slug = li _script.steps.add(ScriptStep.objects.create( script = _script, poll = Poll.objects.get(id = poll_id), order = i, # using index for different order??? rule = ScriptStep.RESEND_MOVEON, num_tries = 1, start_offset = 60, retry_offset = 86400, giveup_offset = 86400, )) _script.save() if len(checked_numbers) < 25 and len(checked_numbers) > 0: # assuming that "all" is not checked for reporter in EmisReporter.objects.filter(id__in=checked_numbers).exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() else: # what if the reporting location is different? Would you instead want to poll the different districts? single_reporter_location = True # flag reporter_location = EmisReporter.objects.filter(id__in=checked_numbers).\ exclude(reporting_location=None).values_list('reporting_location__name', flat=True) if reporter_location.count() > 0 and len(set(reporter_location)) > 1: single_reporter_location = False reporter_location = EmisReporter.objects.filter(reporting_location__type = 'district').\ values_list('reporting_location__name',flat=True) else: reporter_location = EmisReporter.objects.filter(reporting_location__type='district').\ filter(reporting_location__name = reporter_location[0]).values_list('reporting_location__name',flat=True) single_school = True reporter_schools = EmisReporter.objects.filter(id__in=checked_numbers).\ exclude(schools=None).values_list('schools__name', flat=True) if reporter_schools.count() > 0 and len(set(reporter_schools)) > 1: single_school = False reporter_schools = EmisReporter.objects.values_list('schools__name',flat=True) else: reporter_schools = EmisReporter.objects.filter(schools__name=reporter_schools[0]).values_list( 'schools__name', flat=True ) if single_reporter_location or single_school: for reporter in EmisReporter.objects.filter(schools__name__in=reporter_schools, reporting_location__name__in = reporter_location, groups__name =\ ' '.join([i.capitalize() for i in reporter_group_name.replace('_',' ').split()])).\ exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() else: for reporter in EmisReporter.objects.filter(groups__name =\ ' '.join([i.capitalize() for i in reporter_group_name.replace('_',' ').split()])).exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() return HttpResponseRedirect(reverse('emis-contact')) else: return render_to_response('education/partials/reporters/special_scripts.html',{'scripts':scripts}, RequestContext(req)) def reschedule_scripts(request, script_slug): grp = get_script_grp(script_slug) if script_slug.endswith('_weekly'): reschedule_weekly_polls(grp) elif script_slug.endswith('_monthly'): reschedule_monthly_polls(grp) else: if request.POST.has_key('date'): date = request.POST.get('date') else: date = None reschedule_termly_polls(grp, date) new_scripts = ScriptProgress.objects.filter(script__slug=script_slug) if new_scripts: new_script_date = new_scripts[0].time response = HttpResponse("This Script has been rescheduled to: %s " % new_script_date.strftime("%d-%m-%Y %H:%M")) return response else: return HttpResponse("This script can't be rescheduled. Try again") class EdtracReporter(ListView): model = EmisReporter template_name = "education/emisreporter_list.html" context_object_name = "reporter_list" ########## Maps ################# def attendance_visualization(req): return render_to_response( 'education/partials/map_attendance.html', { 'geoserver_url':getattr(settings, 'GEOSERVER_URL', 'http://localhost/geoserver') }, context_instance = RequestContext(req)) class AbsenteeismForm(forms.Form): error_css_class = 'error' select_choices = [('all', '--'), ('P3Boys', 'P3 Boys'), ('P3Girls', 'P3 Girls'), ('P3Pupils', 'P3 Pupils'), ('P6Boys', 'P6 Boys'), ('P6Girls', 'P6 Girls'), ('P6Pupils', 'P6 Pupils'), ('MaleTeachers', 'Male Teachers'), ('FemaleTeachers', 'Female Teachers'), ('Teachers', 'Teachers'), ('MaleHeadTeachers', 'Male Head Teachers'), ('FemaleHeadTeachers', 'Female Head Teachers'), ('HeadTeachers', 'Head Teachers'), ] from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) indicator = forms.ChoiceField(choices=select_choices, required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: if is_empty(data.get('indicator')): raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data @login_required def detail_attd(request, district=None): locations = get_location_for_absenteeism_view(district, request) time_range_depth = 4 if request.method == 'POST': absenteeism_form = AbsenteeismForm(data=request.POST) if absenteeism_form.is_valid(): indicator = absenteeism_form.cleaned_data['indicator'] week_range = get_date_range(absenteeism_form.cleaned_data['from_date'], absenteeism_form.cleaned_data['to_date'], time_range_depth) else: return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form}, RequestContext(request)) else: absenteeism_form = AbsenteeismForm(initial={'indicator': 'all'}) week_range = get_week_date(time_range_depth) indicator = "all" week_range.reverse() config_list = get_polls_for_keyword(indicator) collective_result, time_data, reporting_school_percent = get_aggregated_report(locations, config_list, week_range) weeks = ["%s - %s" % (i[0].strftime("%m/%d/%Y"), i[1].strftime("%m/%d/%Y")) for i in week_range] return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form, 'collective_result_keys': [config['collective_dict_key'] for config in config_list], 'collective_result': collective_result, 'time_data': mark_safe(json.dumps(time_data)), 'school_percent' : reporting_school_percent, 'weeks': mark_safe(json.dumps(weeks)), "locations": locations}, RequestContext(request)) @login_required def detail_dashboard(request, district=None): locations = get_location_for_absenteeism_view(district, request) time_range_depth = 4 if request.method == 'POST': absenteeism_form = AbsenteeismForm(data=request.POST) if absenteeism_form.is_valid(): indicator = absenteeism_form.cleaned_data['indicator'] week_range = get_date_range(absenteeism_form.cleaned_data['from_date'], absenteeism_form.cleaned_data['to_date'], time_range_depth) else: return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form}, RequestContext(request)) else: absenteeism_form = AbsenteeismForm(initial={'indicator': 'all'}) week_range = get_week_date(time_range_depth) indicator = "all" week_range.reverse() config_list = get_polls_for_keyword(indicator) collective_result, time_data, reporting_school_percent = get_aggregated_report(locations, config_list, week_range) weeks = ["%s - %s" % (i[0].strftime("%m/%d/%Y"), i[1].strftime("%m/%d/%Y")) for i in week_range] return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form, 'collective_result_keys': [config['collective_dict_key'] for config in config_list], 'collective_result': collective_result, 'time_data': mark_safe(json.dumps(time_data)), 'school_percent' : reporting_school_percent, 'weeks': mark_safe(json.dumps(weeks)), "locations": locations}, RequestContext(request)) @login_required def detail_attd_school(request, location): name = request.GET['school'] school_id = School.objects.get(name=name, location__name=location).id return redirect(reverse('school-detail',args=(school_id,))) class ExportPollForm(forms.Form): error_css_class = 'error' select_choices = list(Poll.objects.values_list(*['pk','name'])) from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) poll_name = forms.ChoiceField(choices=select_choices, required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: if is_empty(data.get('poll_name')): raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data def get_district_parent(reporting_location): parent_locations = reporting_location.get_ancestors() district_parent = [parent for parent in parent_locations if parent.type.name == 'district'] return district_parent[0].name def _format_responses(responses): a = [] for response in responses: if response.contact: contact = response.contact sender = contact location_type = contact.reporting_location.type reporting_location = contact.reporting_location.name if not location_type.name == 'district' and not location_type.name == 'country': reporting_location = get_district_parent(contact.reporting_location) location_type = 'district' school = ", ".join(contact.emisreporter.schools.values_list('name', flat=True)) else: sender = response.message.connection.identity location_type = "--" reporting_location = "--" school = "--" date = response.message.date if response.poll.type == "t": value = response.eav.poll_text_value elif response.poll.type == "n": if hasattr(response.eav, 'poll_number_value'): value = response.eav.poll_number_value else: value = 0 elif response.poll.type == 'l': value = response.eav.poll_location_value.name category = response.categories.values_list('category__name',flat=True) if len(category) == 0: category = "--" else: category = ", ".join(category) a.append((sender,location_type,reporting_location,school,date,value,category)) return a def _get_identity(r): return r.default_connection.identity if r.default_connection else "--" def _format_reporters(reporters): return [[r.id,r.name, _get_identity(r),r.reporting_location.type.name, r.reporting_location.name, ", ".join(r.schools.values_list('name', flat=True))] for r in reporters] @login_required def edtrac_export_poll_responses(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': form = ExportPollForm() else: form = ExportPollForm(data=request.POST) if form.is_valid(): poll = get_object_or_404(Poll, pk=form.cleaned_data['poll_name']) responses = poll.responses.all().order_by('-pk') to_date = form.cleaned_data['to_date'] from_date = form.cleaned_data['from_date'] if from_date and to_date: responses = responses.filter(date__range=[from_date, to_date]) resp = render_to_response( 'education/admin/export_poll_responses.csv', { 'responses': _format_responses(responses) }, mimetype='text/csv', context_instance=RequestContext(request) ) resp['Content-Disposition'] = 'attachment;filename="%s.csv"' \ % poll.name return resp return render_to_response('education/admin/export_poll_responses.html', {'form': form}, RequestContext(request), ) @login_required def edit_sub_county_reporters(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': sub_county_reporters = EmisReporter.objects.filter(reporting_location__type = 'sub_county') return render_to_response('education/admin/edit_sub_county_reporters.html', {'reporters':sub_county_reporters},RequestContext(request)) @login_required def export_sub_county_reporters(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': sub_county_reporters = EmisReporter.objects.filter(reporting_location__type='sub_county') resp = render_to_response('education/admin/export_sub_county_reporters.csv', {'responses': _format_reporters(sub_county_reporters)}, mimetype='text/csv', context_instance=RequestContext(request)) resp['Content-Disposition'] = 'attachment;filename="sub_county_reporters.csv"' return resp class ExportMessageForm(forms.Form): error_css_class = 'error' from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data def _get_school(m): if m.connection.contact.emisreporter.schools.all().exists(): return m.connection.contact.emisreporter.schools.all()[0] return None def _format_messages(messages): return[ [m ,m.connection.contact.reporting_location,_get_school(m),m.connection.contact,m.connection,m.date ] for m in messages] @login_required def edtrac_export_error_messages(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': form = ExportMessageForm() else: form = ExportMessageForm(data=request.POST) if form.is_valid(): messages = Message.objects.exclude( connection__identity__in = getattr(settings, 'MODEM_NUMBERS') ).filter(direction='I', connection__contact__emisreporter__reporting_location__in =\ locations.get(name__iexact="Uganda").get_descendants(include_self=True).all() ) messages= messages.filter(poll_responses=None) | messages.filter(poll_responses__has_errors=True) to_date = form.cleaned_data['to_date'] from_date = form.cleaned_data['from_date'] if from_date and to_date: messages = messages.filter(date__range=[from_date, to_date]) resp = render_to_response('education/admin/export_error_messages.csv', {'messages' : _format_messages(messages)}, mimetype='text/csv', context_instance=RequestContext(request)) resp['Content-Disposition'] = 'attachment;filename="error_messages.csv"'\ return resp return render_to_response('education/admin/export_error_messages.html', {'form':form},RequestContext(request)) def get_schools(request): location = request.GET['location'] list_of_schools = [{'text':'--------------','value':''}] if not is_empty(location): filtered_schools = School.objects.filter(location=Location.objects.get(pk=location,type__slug='district')) location_schools = [{'text':school.name,'value':school.pk} for school in filtered_schools] list_of_schools.extend(location_schools) return HttpResponse(json.dumps(list_of_schools)) Refactor so that it's more obvious how the holiday calculation works. It's still wrong, but it's clearer now. from __future__ import division from urllib2 import urlopen import re import operator import copy import json from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render_to_response, redirect from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import DetailView, TemplateView, ListView from django.views.decorators.vary import vary_on_cookie from django.db.models import Q from django.core.cache import cache import xlwt from django.utils.safestring import mark_safe from education.curriculum_progress_helper import get_target_value, get_location_for_curriculum_view, get_curriculum_data, target from rapidsms_httprouter.models import Message from .forms import * from .models import * from uganda_common.utils import * from rapidsms.contrib.locations.models import Location from generic.views import generic from generic.sorters import SimpleSorter from poll.models import Poll, ResponseCategory from script.models import ScriptStep, Script from .reports import * from .utils import * from .utils import _schedule_monthly_script, _schedule_termly_script, _schedule_weekly_scripts, _schedule_teacher_weekly_scripts import reversion from reversion.models import Revision from unregister.models import Blacklist from .utils import themes from education.absenteeism_view_helper import * import datetime from datetime import date from education.view_helper import * from education.view_helper_utils import * Num_REG = re.compile('\d+') super_user_required = \ user_passes_test(lambda u: u.groups.filter( name__in=['Admins', 'DFO', 'UNICEF Officials']).exists() or u.is_superuser) @login_required def index(request, **kwargs): """ kwargs is where we list the variables that can be passed as our context use as follows: index(request, context_vars={'some_model_queryset'=Model.objects.all}) """ if not kwargs: return render_to_response("education/index.html", {}, RequestContext(request)) else: #When choosing to use kwargs, don't forget to include template and context_var variables # if you don't need a template or just need the original template, use template_name=None context_vars = kwargs.get('context_vars') template_name = kwargs['template_name'] if not template_name: #if no template name is given t = "education/index.html" else: t = "education/%s" % template_name return render_to_response(t, context_vars, RequestContext(request)) #MAPS @login_required def dash_map(request): return render_to_response('education/dashboard/map.html', {}, RequestContext(request)) def dash_ministry_map(request): return render_to_response('education/dashboard/map.html', {}, RequestContext(request)) def dash_attdance(request): boysp3_attendance = get_responses_to_polls(poll_name='edtrac_boysp3_attendance') boysp3_enrolled = get_responses_to_polls(poll_name="edtrac_boysp3_enrollment") boysp3_absent = boysp3_enrolled - boysp3_attendance girlsp3_attendance = get_responses_to_polls(poll_name="edtrac_girlsp3_attendance") girlsp3_enrolled = get_responses_to_polls(poll_name="edtrac_girlsp3_enrollment") girlsp3_absent = girlsp3_enrolled - girlsp3_attendance boysp6_attendance = get_responses_to_polls(poll_name="edtrac_boysp6_attendance") boysp6_enrolled = get_responses_to_polls(poll_name="edtrac_boysp6_enrollment") boysp6_absent = boysp6_enrolled - boysp6_attendance girlsp6_attendance = get_responses_to_polls(poll_name="edtrac_girlsp6_attendance") girlsp6_enrolled = get_responses_to_polls(poll_name="edtrac_girlsp6_enrollment") girlsp6_absent = girlsp6_enrolled - girlsp6_attendance total_male_teachers = get_responses_to_polls(poll_name="edtrac_m_teachers_deployment") total_female_teachers = get_responses_to_polls(poll_name="edtrac_f_teachers_deployment") male_teachers_present = get_responses_to_polls(poll_name="edtrac_m_teachers_attendance") male_teachers_absent = total_male_teachers - male_teachers_present female_teachers_present = get_responses_to_polls(poll_name="edtrac_f_teachers_attendance") female_teachers_absent = total_female_teachers - female_teachers_present return render_to_response('education/dashboard/attdance.html', { 'girlsp3_present' : girlsp3_attendance, 'girlsp3_absent' : girlsp3_absent, 'boysp3_present' : boysp3_attendance, 'boysp3_absent' : boysp3_absent, 'girlsp6_present' : girlsp6_attendance, 'girlsp6_absent' : girlsp6_absent, 'boysp6_present' : boysp6_attendance, 'boysp6_absent' : boysp6_absent, 'female_teachers_present' : female_teachers_present, 'female_teachers_absent' : female_teachers_absent, 'male_teachers_present' : male_teachers_present, 'male_teachers_absent' : male_teachers_absent } , RequestContext(request)) def get_mode_progress(mode): try: mode_progress = (100 * sorted(target.values()).index(mode) + 1) / float(len(target.keys())) # offset zero-based index by 1 except ValueError: mode_progress = 0 # when no values are recorded return mode_progress def get_progress_color(current_mode, target_value): on_schedule = 'green' behind_schedule = 'red' if current_mode < target_value: return behind_schedule return on_schedule def get_weeks_in_term(): term_start= getattr(settings,'SCHOOL_TERM_START') first_term_start= getattr(settings,'FIRST_TERM_BEGINS') second_term_start= getattr(settings,'SECOND_TERM_BEGINS') third_term_start= getattr(settings,'THIRD_TERM_BEGINS') weeks = [] for term_starts in [first_term_start, second_term_start, third_term_start]: if term_start == term_starts: weeks.extend(get_weeks(get_week_date()[1],depth=get_week_count(get_week_date()[0],term_starts))) break weeks.extend(get_weeks(dateutils.increment(term_starts, weeks=12),depth=12)) return weeks def format_week(week,sep): day1 = week[0].strftime("%d"+sep+"%b"+sep+"%Y") day2 = week[1].strftime("%d"+sep+"%b"+sep+"%Y") formated_week = "%s to %s" % (day1 , day2) return formated_week def _get_formated_date_choice(week): if week[0] < datetime.datetime.today() < week[1]: return format_week(week, ","), "current week( %s )" % format_week(week, "-") return format_week(week, ","), format_week(week, "-") class CurriculumForm(forms.Form): error_css_class = 'error' SELECT_CHOICES = [_get_formated_date_choice(week) for week in get_weeks_in_term()] choose_week_to_view = forms.ChoiceField(choices=SELECT_CHOICES, required=False) class ReporterDetailView(DetailView): model = EmisReporter def format_to_datetime_object(week_as_string): day1 = week_as_string.split()[0] day2 = week_as_string.split()[2] day_one = datetime.datetime.strptime(day1,"%d,%b,%Y") day_two = datetime.datetime.strptime(day2,"%d,%b,%Y") return [day_one,day_two] def get_modes_and_target(current_mode, target_value): target_progress = get_mode_progress(target_value) if len(current_mode) > 0 and isinstance(current_mode,list): max_mode = max([i[0] for i in current_mode]) mode_progress = get_mode_progress(max_mode) color = get_progress_color(max_mode, target_value) return color, mode_progress, target_progress mode_progress = 0 color = 'red' return color, mode_progress, target_progress def get_mode_if_exception_thrown(loc_data): if "Progress undetermined this week" in loc_data.values(): return "Progress undetermined this week" return "No Reports made this week" @login_required def curriculum_progress(request,district_pk=None): locations, user_location, sub_location_type,template_name = get_location_for_curriculum_view(district_pk, request) if request.method == 'POST': curriculum_form = CurriculumForm(data=request.POST) if curriculum_form.is_valid(): target_week = format_to_datetime_object(curriculum_form.cleaned_data['choose_week_to_view']) target_date = target_week[0] else: return render_to_response('education/progress/admin_progress_details.html', {'form': curriculum_form}, RequestContext(request)) else: target_week = get_week_date() curriculum_form = CurriculumForm(initial={'choose_week_to_view': format_week(target_week, ",")}) target_date = target_week[0] loc_data , valid_responses = get_curriculum_data(locations,target_week) try: current_mode = Statistics(valid_responses).mode except StatisticsException: current_mode = get_mode_if_exception_thrown(loc_data) target_value , term = get_target_value(target_date) if isinstance(current_mode,list) and len(current_mode) == 0: current_mode = "Progress undetermined this week" color, mode_progress, target_progress = get_modes_and_target(current_mode, target_value) return render_to_response(template_name, {'form': curriculum_form, 'location_data': loc_data, 'target': target_value, 'current_mode': current_mode, 'mode_progress': mode_progress, 'target_progress': target_progress, 'class_sent_from_behind': color, 'sub_location_type': sub_location_type, 'term': term}, RequestContext(request)) def dash_admin_meetings(req): profile = req.user.get_profile() location = profile.location p = Poll.objects.get(name = 'edtrac_smc_meetings') if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Ministry Officials'): meeting_stats = get_count_response_to_polls(p, #404 is shortcode for unknown choices = [0, 1, 2, 3, 404], # number of meetings with_percent = True, #percentage counted based on number of schools termly = True, admin=True) return render_to_response("education/admin/admin_meetings.html",{ 'meeting_basis': meeting_stats.get('correctly_answered'), 'titles':",".join(str(k) for k in meeting_stats.get('to_ret').keys()), 'meetings':",".join(str(v) for v in meeting_stats.get('to_ret').values()) }, RequestContext(req)) else: meeting_stats = get_count_response_to_polls(p, location_name = location.name, #404 is shortcode for unknown choices = [0, 1, 2, 3, 404], # number of meetings with_percent = True, #percentage counted based on number of schools termly = True, admin = False ) return render_to_response('education/admin/other_meetings.html', {'location_name':location.name, 'meeting_basis': meeting_stats.get('correctly_answered'), 'meetings':",".join(str(v) for v in meeting_stats.get('to_ret').values()), 'titles':",".join(str(k) for k in meeting_stats.get('to_ret').keys()), 'meeting_basis':meeting_stats.get('correctly_answered')}, RequestContext(req)) def preprocess_response(resp): """ reprocess the response values and return just one value """ if not resp: return '--' elif None in resp: return 'wrong response' else: return resp[0] # assumption only one SMC is attached to that school def dash_district_meetings(req, district_name): district = Location.objects.filter(type="district").get(name = district_name) p = Poll.objects.get(name = 'edtrac_smc_meetings') schools_data = EmisReporter.objects.exclude(connection__in = Blacklist.objects.values_list('connection')).\ filter(groups__name = 'SMC', reporting_location = district).exclude(schools = None).order_by('schools__name').\ values_list('schools__name','schools__id','connection__pk') school_container = {} for school_name, school_id, smc_connection in schools_data: school_container[(school_name, school_id)] = preprocess_response([r.eav.poll_number_value for r in p.responses.filter(contact__connection__pk = smc_connection, date__range =[getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END')] )]) #TODO -> sort the school container items return render_to_response( 'education/admin/district_meetings.html', {'location_name':district_name, 'meeting_count':school_container.items()}, RequestContext(req)) # Dashboard specific view functions @login_required @vary_on_cookie def dashboard(request): return admin_dashboard(request) def capitation_grants(locations): # capitation grants cg = Poll.objects.get(name="edtrac_upe_grant") yes_category = cg.categories.get(name='yes') yeses_cg = cg.responses.filter(contact__reporting_location__in=locations, categories__category=yes_category).values_list('contact').distinct().count() # percent of those that received grants head_teacher_count = EmisReporter.objects.exclude(schools=None, connection__in= \ Blacklist.objects.values_list('connection', flat=True)).filter(groups__name='Head Teachers', \ reporting_location__in=locations).count() try: grant_percent = (100 * yeses_cg) / head_teacher_count except ZeroDivisionError: grant_percent = 0 return {'grant_percent': grant_percent} def violence_numbers_girls(locations): """ Percentage change in violance from the previous month """ responses_to_violence_girls = poll_response_sum("edtrac_violence_girls", month_filter = 'monthly', locations = locations) return {'violence_numbers_girls' : abs(responses_to_violence_girls[0])} def violence_numbers_boys(locations): """ Percentage change in violance from the previous month """ responses_to_violence_boys = poll_response_sum("edtrac_violence_boys", month_filter = 'monthly', locations = locations) return {'violence_numbers_boys': abs(responses_to_violence_boys[0])} def violence_numbers_reported(locations): """ Percentage change in violance from the previous month """ responses_to_violence_reported = poll_response_sum("edtrac_violence_reported", month_filter = 'monthly', locations = locations) return {'violence_numbers_reported': abs(responses_to_violence_reported[0])} def get_two_weeks_absenteeism(indicator, locations, get_time): date_weeks = get_week_date(depth=2, get_time=get_time) if is_holiday(date_weeks[0][0], getattr(settings, 'SCHOOL_HOLIDAYS')) \ or is_holiday(date_weeks[1][0], getattr(settings, 'SCHOOL_HOLIDAYS')): return '--','--' else: config_list = get_polls_for_keyword(indicator) function_to_invoke = config_list[0].get('func') absent_by_location, absent_by_time, school_percent = function_to_invoke(locations, config_list[0], date_weeks) try: this_week_absent = absent_by_time[0] except IndexError: this_week_absent = 0 try: past_week_absent = absent_by_time[1] except IndexError: past_week_absent = 0 return this_week_absent, past_week_absent def p3_absent_boys(locations, get_time=datetime.datetime.now): """ Attendance of P3 Pupils; this gets the absenteeism """ boysp3, boysp3_past = compute_absenteeism_summary('P3Boys',locations,get_time=get_time) return {'boysp3' : boysp3, 'boysp3_past' : boysp3_past,} def p6_boys_absent(locations, get_time=datetime.datetime.now): boysp6, boysp6_past = compute_absenteeism_summary('P6Boys',locations,get_time=get_time) return {'boysp6' : boysp6, 'boysp6_past' : boysp6_past} def p3_absent_girls(locations, get_time=datetime.datetime.now): girlsp3 ,girlsp3_past = compute_absenteeism_summary('P3Girls',locations,get_time=get_time) return {'girlsp3' : girlsp3, 'girlsp3_past' : girlsp3_past} def p6_girls_absent(locations,get_time=datetime.datetime.now): girlsp6,girlsp6_past = compute_absenteeism_summary('P6Girls',locations,get_time=get_time) return {'girlsp6' : girlsp6, 'girlsp6_past' : girlsp6_past} def f_teachers_absent(locations, get_time=datetime.datetime.now): female_teachers ,female_teachers_past = compute_absenteeism_summary('FemaleTeachers',locations,get_time=get_time) return {'female_teachers' :female_teachers,'female_teachers_past' : female_teachers_past,} def m_teachers_absent(locations, get_time=datetime.datetime.now): male_teachers,male_teachers_past = compute_absenteeism_summary('MaleTeachers',locations, get_time=get_time) return {'male_teachers' : male_teachers, 'male_teachers_past' : male_teachers_past} def get_target_week(): for week in get_weeks_in_term(): if week[0] < datetime.datetime.today() < week[1]: return week def progress(stages, stage): numerator = stages.index(stage) + 1 denominator = len(stages) return 100 * numerator / denominator def p3_curriculum(locations): target_week = get_week_date() poll = Poll.objects.get(name='edtrac_p3curriculum_progress') mode = NumericResponsesFor(poll) \ .forDateRange(target_week) \ .forLocations(locations) \ .forValues(themes.keys()) \ .mode() if mode: return {'mode_progress' : progress(sorted(themes.keys()), mode), 'c_mode' : [[mode]]} else: return {'mode_progress' : 0, 'c_mode' : "Progress undetermined this week"} def meals_missed(locations, get_time): poll = Poll.objects.get(name = "edtrac_headteachers_meals") this_month = get_month_day_range(get_time()) schools_without_meals = NumericResponsesFor(poll) \ .forLocations(locations) \ .forDateRange(this_month) \ .excludeGreaterThan(0) \ .groupBySchools() return {'meals_missed' : len(schools_without_meals)} def head_teachers_female(locations, get_time=datetime.datetime.now): female_d1,female_d2 = get_two_weeks_absenteeism('FemaleHeadTeachers',locations,get_time) try: f_head_diff = female_d2 - female_d1 if f_head_diff < 0: f_head_t_class = "decrease" f_head_t_data = 'data-red' elif f_head_diff > 0: f_head_t_class = "increase" f_head_t_data = 'data-green' else: f_head_t_class = "zero" f_head_t_data = 'data-white' except: f_head_diff = '--' f_head_t_class = "zero" f_head_t_data = 'data-white' return {'f_head_t_week' : female_d1, 'f_head_t_week_before' : female_d2, 'f_head_diff' : f_head_diff, 'f_head_t_class' : f_head_t_class, 'f_head_t_data':f_head_t_data} def head_teachers_male(locations, get_time=datetime.datetime.now): male_d1, male_d2 = get_two_weeks_absenteeism('MaleHeadTeachers',locations,get_time=get_time) try: m_head_diff = male_d2 - male_d1 if m_head_diff < 0: m_head_t_class = "decrease" m_head_t_data = 'data-red' elif m_head_diff > 0: m_head_t_class = "increase" m_head_t_data = 'data-green' else: m_head_t_class = "zero" m_head_t_data = 'data-white' except: m_head_diff = '--' m_head_t_class = "zero" m_head_t_data = 'data-white' return {'m_head_t_week' : male_d1, 'm_head_t_data':m_head_t_data, 'm_head_t_week_before' : male_d2, 'm_head_diff' : m_head_diff, 'm_head_t_class' : m_head_t_class} def schools_valid(locations, group_names, blacklisted): school_valid = EmisReporter.objects.filter( groups__name__in=group_names, reporting_location__in=locations ).exclude(connection__in=blacklisted).exclude(schools=None) \ .values('schools__id').distinct().count() return {'total_schools_valid': school_valid} def schools_active(locations): try: count_reps = EmisReporter.objects.filter(groups__name__in=['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'], reporting_location__in = locations).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None).count() count = 0 for p in Poll.objects.filter(name__icontains = 'attendance').select_related(): if len(locations) == 1: count += p.responses.filter( contact__reporting_location__in = locations, date__range = get_week_date(depth = 2)[0] ).distinct().select_related().count() else: count += p.responses.filter(date__range = get_week_date(depth=2)[0]).distinct().select_related().count() school_active = (100 * count) / count_reps except ZeroDivisionError: school_active = 0 return {'school_active': school_active} def smc_meetings(locations): # SMC meetings are count based school_to_date = School.objects.filter(pk__in=EmisReporter.objects.\ filter(reporting_location__name__in = [loc.name for loc in locations]).select_related().\ values_list('schools__pk', flat=True)).count() smc_meeting_poll = Poll.objects.get(name = 'edtrac_smc_meetings') meetings = NumericResponsesFor(smc_meeting_poll) \ .excludeZeros() \ .forDateRange([getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END')]) \ .forLocations(locations) \ .total() try: total_meetings = 100 * meetings / school_to_date except ZeroDivisionError: total_meetings = 0 return {'smc_meetings': total_meetings, 'schools_to_date': school_to_date} def total_reporters(locations, group_names, blacklisted): total_reporters = EmisReporter.objects.filter( groups__name__in=group_names, reporting_location__in=locations ).exclude( connection__in=blacklisted ).exclude( schools=None ).count() return {'total_reporters': total_reporters} # generate context vars def generate_dashboard_vars(location): """ An overly ambitious function that generates context variables for a location if provided This gets populated in the dashboard. """ context_vars = {} if location.name == "Uganda": # get locations from active districts only locations = Location.objects.filter(pk__in=EmisReporter.objects.\ values_list('reporting_location__pk', flat=True)).distinct() else: locations = [location] group_names = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] blacklisted = Blacklist.objects.all().values_list('connection', flat=True) # violence girls context_vars.update(violence_numbers_girls(locations)) #violence boys context_vars.update(violence_numbers_boys(locations)) #violence_reported context_vars.update(violence_numbers_reported(locations)) # capitations grants context_vars.update(capitation_grants(locations)) #active schools context_vars.update(schools_active(locations)) #valid schools context_vars.update(schools_valid(locations, group_names, blacklisted)) #SMC meetings context_vars.update(smc_meetings(locations)) #female head teachers that missed school context_vars.update(head_teachers_female(locations)) #male head teachers that missed school context_vars.update(head_teachers_male(locations)) # time stamps context_vars.update({'month':datetime.datetime.now()}) # progress context_vars.update(p3_curriculum(locations)) # Female teachers context_vars.update(f_teachers_absent(locations)) # P3 teachers male context_vars.update(m_teachers_absent(locations)) # P3 boys context_vars.update(p3_absent_boys(locations)) # P3 Girls context_vars.update(p3_absent_girls(locations)) # P6 Girls context_vars.update(p6_girls_absent(locations)) # P6 Boys context_vars.update(p6_boys_absent(locations)) #Meals context_vars.update(meals_missed(locations, get_time = datetime.datetime.now)) #Total Reporters context_vars.update(total_reporters(locations, group_names, blacklisted)) return context_vars # view generator def view_generator(req, enrol_deploy_poll=None, attendance_poll=None, title=None, url_name_district=None, url_name_school = 'school-detail', template_name='education/timeslider_base.html'): """ A generic function to create views based on time ranges. """ time_range_form = ResultForm() profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): # high level officials will access all districts locations = Location.objects.filter(type='district').filter(pk__in =\ EnrolledDeployedQuestionsAnswered.objects.values_list('school__location__pk',flat=True)) else: # other officials will access individual districts locations = [profile.location] if req.method == 'POST': time_range_form = ResultForm(data=req.POST) to_ret = [] if time_range_form.is_valid(): from_date = time_range_form.cleaned_data['from_date'] to_date = time_range_form.cleaned_data['to_date'] month_delta = abs(from_date.month - to_date.month) date_weeks = [] month_flag = None if month_delta <= 2: # same month get days in between month_flag = False # don't split data in months while from_date <= to_date: if from_date.weekday() == 3: #is to_day a Thursday? date_weeks.append(previous_calendar_week(t = from_date)) # get range from Wed to Thur. from_date += datetime.timedelta(days = 1) else: month_flag = True # split data in months while from_date <= to_date: date_weeks.append([dateutils.month_start(from_date),dateutils.month_end(dateutils.increment(from_date, months=1))]) next_date = dateutils.increment(from_date, months = 1) delta = next_date - from_date from_date += datetime.timedelta(days = abs(delta.days)) if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): schools_temp = School.objects.filter(pk__in = \ EnrolledDeployedQuestionsAnswered.objects.select_related().values_list('school__pk', flat=True)) for location in locations: temp = [] # get schools in this location location_schools = schools_temp.select_related().filter(location = location) # store in memory for d in date_weeks: total_attendance = 0 # per school total_enrollment = 0 # per school for school in location_schools: enrolled = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) if enrolled > 0: if month_flag: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'avg') # use averages else: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_enrollment += enrolled try: percentage = (total_enrollment - total_attendance) * 100 / total_enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) return render_to_response(template_name, {'form':time_range_form, 'dataset':to_ret, 'title': title,'month_flag': month_flag, 'url_name':url_name_district, 'date_batch':date_weeks}, RequestContext(req)) else: location_schools = School.objects.filter(pk__in = EnrolledDeployedQuestionsAnswered.objects.select_related().\ filter(school__location=locations[0]).values_list('school__pk', flat=True)).select_related() #Non admin types# for school in location_schools: for d in date_weeks: temp = [] enrollment = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) if month_flag: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'avg') else: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') try: percentage = (enrollment - attendance) * 100 / enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([school, temp]) return render_to_response(template_name, {'form':time_range_form, 'dataset_school':to_ret, 'title': title,'month_flag':month_flag, 'url_name': url_name_school, 'date_batch':date_weeks}, RequestContext(req)) else: return render_to_response(template_name, {'form':time_range_form, 'url_name':url_name_district, 'title':title}, RequestContext(req)) # NO POST data sent! else: date_weeks = [] date_weeks.append(previous_calendar_week(t = datetime.datetime.now())) sw = date_weeks[0][0] date_weeks.append(previous_calendar_week(t = dateutils.increment(datetime.datetime(sw.year, sw.month, sw.day, 10), weeks = -1))) location_data = [] schools_temp = School.objects.select_related().\ filter(pk__in =\ EnrolledDeployedQuestionsAnswered.objects.select_related().filter(school__location__in=locations).values_list('school__pk',flat=True)) context_vars = {} if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins')\ or profile.is_member_of('UNICEF Officials'): for location in locations: temp = [] # get schools in this location location_schools = schools_temp.select_related().filter(location = location) for d in date_weeks: total_attendance = 0 # per school total_enrollment = 0 # per school for school in location_schools: enrolled = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_enrollment += enrolled try: percentage = (total_enrollment - total_attendance) * 100 / total_enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) try: diff = temp[0] - temp[1] except TypeError: diff = '--' location_data.append([location, temp[0], temp[1], diff]) context_vars.update({'location_data':location_data}) else: location_schools = School.objects.select_related().filter(pk__in = EnrolledDeployedQuestionsAnswered.objects.select_related().\ filter(school__location=locations[0]).values_list('school__pk', flat=True)) #Non admin types to_ret = [] for school in location_schools: enrollment = poll_responses_term(enrol_deploy_poll, belongs_to='schools', school = school ) temp = [] for d in date_weeks: attendance = get_numeric_report_data(attendance_poll, school = school, time_range=list(d), to_ret = 'sum') try: percentage = (enrollment - attendance) * 100 / enrollment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([school, temp]) context_vars = {'form':time_range_form, 'dataset_school':to_ret, 'title': title, 'url_name': url_name_school, 'date_batch':date_weeks} if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): x = {'url_name':url_name_district, 'headings':['District', 'Current week', 'Previous week', 'Percentage difference']} else: x = {'url_name':url_name_school, 'headings':['School', 'Current week', 'Previous week', 'Percentage difference']} if context_vars.has_key('form') ==False and context_vars.has_key('title') == False: context_vars.update({'form':time_range_form,'title':title}) # add the keys to context_vars dict context_vars.update(x) return render_to_response(template_name, context_vars, RequestContext(req)) @login_required def admin_dashboard(request): if request.user.get_profile().is_member_of('Ministry Officials') or request.user.get_profile().is_member_of('Admins')\ or request.user.get_profile().is_member_of('UNICEF Officials'): location = Location.objects.get(name="Uganda") else: location = request.user.get_profile().location key = "context-vars-for-location-" + str(location.id) context_vars = cache.get(key) if not context_vars: context_vars = generate_dashboard_vars(location=location) cache.set(key, context_vars, 60 * 60) return render_to_response("education/admin/admin_dashboard.html", context_vars, RequestContext(request)) class NationalStatistics(TemplateView): template_name = "education/admin/national_statistics.html" groups = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] def compute_percent(self, reps, groups = groups): all_reporters = EmisReporter.objects.filter(groups__name__in=groups).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None) try: reps.count() / all_reporters.count() except ZeroDivisionError: return 0 def get_context_data(self, **kwargs): context = super(NationalStatistics, self).get_context_data(**kwargs) groups = ['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters', 'DEO', 'MEO'] all_reporters = EmisReporter.objects.filter(groups__name__in=groups).exclude(connection__in=Blacklist.objects.all()).exclude(schools=None) profile = self.request.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): districts = Location.objects.filter(type="district").\ filter(name__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in=Blacklist.objects.values_list('connection',flat=True)).values_list('reporting_location__name', flat=True)) reps = EmisReporter.objects.select_related().filter(groups__name__in=['Teachers', 'Head Teachers', 'SMC', 'GEM', 'Other Reporters'], connection__in=Message.objects.\ filter(date__range = get_week_date(depth = 2)[1]).values_list('connection', flat = True)).exclude(schools = None).exclude(connection__in = Blacklist.objects.values_list('connection', flat=True)) district_schools = [ (district, School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).\ filter(reporting_location__name = district.name).distinct().values_list('schools__pk',flat=True)).count()) for district in districts ] context['total_districts'] = districts.count() context['district_schools'] = district_schools schools= School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).\ exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).distinct().values_list('schools__pk',flat=True)) context['school_count'] = schools.count() total_schools = 0 for district in districts: s_count = School.objects.filter(pk__in=EmisReporter.objects.exclude(schools=None).exclude(connection__in = Blacklist.objects.values_list('connection',flat=True)).\ filter(reporting_location__name = district.name).distinct().values_list('schools__pk',flat=True)).count() total_schools += s_count context['total_schools'] = total_schools district_active = [ ( district, self.compute_percent(reps.filter(reporting_location__pk=district.pk), groups=['Head Teachers']) ) for district in districts ] district_active.sort(key=operator.itemgetter(1), reverse=True) context['district_active'] = district_active[:3] context['district_less_active'] = district_active[-3:] head_teacher_count = all_reporters.filter(groups__name='Head Teachers').count() smc_count = all_reporters.filter(groups__name = "SMC").count() p6_teacher_count = all_reporters.filter(groups__name = "Teachers", grade = "P6").count() p3_teacher_count = all_reporters.filter(groups__name = "Teachers", grade = "P3").count() total_teacher_count = all_reporters.filter(groups__name="Teachers").count() deo_count = all_reporters.filter(groups__name="DEO").count() gem_count = all_reporters.filter(groups__name="GEM").count() teacher_data_unclean = total_teacher_count - p3_teacher_count - p6_teacher_count context['head_teacher_count'] = head_teacher_count context['smc_count'] = smc_count context['p6_teacher_count'] = p6_teacher_count context['p3_teacher_count'] = p3_teacher_count context['total_teacher_count'] = total_teacher_count context['teacher_data_unclean'] = teacher_data_unclean context['deo_count'] = deo_count context['gem_count'] = gem_count context['all_reporters'] = all_reporters.count() context['expected_reporters'] = schools.count() * 4 # reporters that used EduTrac the past week active_school_reporters = all_reporters.filter(connection__in=Message.objects.exclude(application='script').\ filter(date__range = get_week_date(depth = 2)[1]).values_list('connection', flat = True)) school_active = [ (school, self.compute_percent(active_school_reporters.filter(schools__pk=school.pk), groups=['Head Teachers', 'Teachers', 'GEM', 'SMC','Other Reporters'])) for school in schools ] school_active.sort(key=operator.itemgetter(1), reverse=True) context['school_active_count'] = School.objects.filter(pk__in = active_school_reporters.values_list('schools__pk', flat=True)).count() context['school_active'] = school_active[:3] context['school_less_active'] = school_active[-3:] return context else: return self.render_to_response(dashboard(self.request)) def get_term_range(term): if term == 'first': return [getattr(settings,'FIRST_TERM_BEGINS'),dateutils.increment(getattr(settings,'FIRST_TERM_BEGINS'),weeks=12)] if term == 'second': return [getattr(settings,'SECOND_TERM_BEGINS'),dateutils.increment(getattr(settings,'SECOND_TERM_BEGINS'),weeks=12)] if term == 'third': return [getattr(settings,'THIRD_TERM_BEGINS'),dateutils.increment(getattr(settings,'THIRD_TERM_BEGINS'),weeks=12)] if term == '' or term =='current' or term is None: return [getattr(settings,'SCHOOL_TERM_START'),getattr(settings,'SCHOOL_TERM_END')] class CapitationGrants(TemplateView): poll_name ='' restrict_group='' def compute_percent(self, x, y): try: return (100 * x) / y except ZeroDivisionError: return 0 def _extract_info(self, list): to_ret = [] for item in list: to_ret.append( [item.get('category__name'), item.get('value')] ) final_ret = {} for li in to_ret: final_ret[li[0]] = li[1] total = sum(filter(None, final_ret.values())) for key in final_ret.keys(): final_ret[key] = self.compute_percent(final_ret.get(key), total) return final_ret def _get_per_category_responses_for_school(self, responses_by_category, school): info = [stat for stat in responses_by_category if stat['response__contact__emisreporter__schools__name'] == school.name] return school, self._extract_info(info).items() def _get_schools_info(self, responses_at_location,location): responses_by_category = responses_at_location.values( 'response__contact__emisreporter__schools__name', 'category__name').annotate(value=Count('pk')) schools = location.schools.all() return [self._get_per_category_responses_for_school(responses_by_category, school) for school in schools] def get_context_data(self, **kwargs): term = self.kwargs.get('term') term_range = get_term_range(term) context = super(CapitationGrants, self).get_context_data(**kwargs) cg = Poll.objects.select_related().get(name=self.poll_name) authorized_users = ['Admins', 'Ministry Officials', 'UNICEF Officials'] authorized_user = False for auth_user in authorized_users: if self.request.user.get_profile().is_member_of(auth_user): authorized_user = True break context['authorized_user'] = authorized_user er = EmisReporter.objects.select_related() unknown_unknowns = cg.responses.filter(~Q(message__text__iregex="i don('?)t know"), categories__category__name="unknown") if authorized_user: reporter_count = er.filter(groups__name=self.restrict_group).exclude(schools=None).count() all_responses = cg.responses_by_category().exclude(response__in=unknown_unknowns).filter(response__date__range=term_range) locs = Location.objects.filter( type="district", pk__in= \ er.exclude(connection__in=Blacklist.objects. \ values_list('connection', flat=True), schools=None).filter(groups__name=self.restrict_group). \ values_list('reporting_location__pk', flat=True)) districts_to_ret = [] for location in locs: info = self._extract_info(all_responses.filter(response__contact__reporting_location=location)) districts_to_ret.append((location, info.items())) total_responses = all_responses.values_list('response__contact').distinct().count() context['responses'] = self._extract_info(all_responses).items() context['location'] = Location.tree.root_nodes()[0] context['sub_locations'] = districts_to_ret context['sub_location_type'] = "district" else: location = self.request.user.get_profile().location all_responses = cg.responses_by_category().exclude(response__in=unknown_unknowns).filter(response__date__range=term_range) responses_at_location = all_responses.filter(response__contact__reporting_location=location) total_responses = responses_at_location.values_list('response__contact').distinct().count() reporter_count = er.exclude(schools=None, connection__in= \ Blacklist.objects.values_list('connection', flat=True)).filter(groups__name=self.restrict_group, \ reporting_location=location).count() context['responses'] = self._extract_info(responses_at_location).items() context['location'] = location context['sub_locations'] = self._get_schools_info(responses_at_location, location) context['sub_location_type'] = "school" context['reporter_count'] = self.compute_percent(total_responses, reporter_count) context['group'] = self.restrict_group return context # Details views... specified by ROLES def set_logged_in_users_location(profile): if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of( 'Admins'): location = Location.objects.get(name='Uganda') else: location = profile.location return location def violence_details_dash(req): profile = req.user.get_profile() context_vars = {} location = set_logged_in_users_location(profile) violence_cases_girls = poll_response_sum("edtrac_violence_girls", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_boys = poll_response_sum("edtrac_violence_boys", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_reported = poll_response_sum("edtrac_violence_reported", location=location, month_filter='monthly', months=2, ret_type=list) violence_cases_gem = poll_response_sum('edtrac_gem_abuse', location=location, month_filter='monthly', months=2, ret_type=list) girls_total = [] for name, list_val in violence_cases_girls: girls_total.append((list_val[0], list_val[1])) context_vars['violence_cases_girls'] = violence_cases_girls girls_first_col, girls_second_col = [],[] for first, second in girls_total: girls_first_col.append(first), girls_second_col.append(second) girls_first_col = [i for i in girls_first_col if i != '--'] girls_second_col = [i for i in girls_second_col if i != '--'] context_vars['girls_totals'] = [sum(girls_first_col), sum(girls_second_col)] boys_total = [] for name, list_val in violence_cases_boys: boys_total.append((list_val[0], list_val[1])) context_vars['violence_cases_boys'] = violence_cases_boys boys_first_col, boys_second_col = [],[] for first, second in boys_total: boys_first_col.append(first), boys_second_col.append(second) boys_first_col = [i for i in boys_first_col if i != '--'] boys_second_col = [i for i in boys_second_col if i != '--'] context_vars['boys_totals'] = [sum(boys_first_col), sum(boys_second_col)] reported_total = [] for name, list_val in violence_cases_reported: reported_total.append((list_val[0], list_val[1])) context_vars['violence_cases_reported'] = violence_cases_reported reported_first_col, reported_second_col = [],[] for first, second in reported_total: reported_first_col.append(first), reported_second_col.append(second) reported_first_col = [i for i in reported_first_col if i != '--'] reported_second_col = [i for i in reported_second_col if i != '--'] context_vars['reported_totals'] = [sum(reported_first_col), sum(reported_second_col)] gem_total = [] # total violence cases reported by school for name, list_val in violence_cases_gem: gem_total.append((list_val[0], list_val[1])) context_vars['violence_cases_reported_by_gem'] = violence_cases_gem first_col, second_col = [],[] for first, second in gem_total: first_col.append(first), second_col.append(second) first_col = [i for i in first_col if i != '--'] second_col = [i for i in second_col if i != '--'] context_vars['gem_totals'] = [sum(first_col), sum(second_col)] context_vars['report_dates'] = [start for start, end in get_month_day_range(datetime.datetime.now(), depth=2)] school_report_count = 0 gem_report_count = 0 for dr in get_month_day_range(datetime.datetime.now(), depth=2): if profile.location.type.name == 'country': contacts = Contact.objects.select_related().filter(reporting_location__in=profile.\ location.get_descendants().filter(type="district")) else: contacts = Contact.objects.select_related().filter(reporting_location=profile.location) school_resp_count = Poll.objects.select_related().get(name="edtrac_violence_girls").responses.filter( contact__in = contacts, date__range = dr).count() gem_resp_count = Poll.objects.select_related().get(name="edtrac_gem_abuse").responses.filter( contact__in = contacts, date__range = dr).count() school_report_count += school_resp_count gem_report_count += gem_resp_count try: context_vars['sch_reporting_percentage'] = 100 * ( school_report_count / (float(len(get_month_day_range(datetime.datetime.now(), depth=2))) * school_report_count)) except ZeroDivisionError: context_vars['sch_reporting_percentage'] = 0 try: context_vars['gem_reporting_percentage'] = 100 * ( gem_report_count / (float(len(get_month_day_range(datetime.datetime.now(), depth=2))) * gem_report_count)) except ZeroDivisionError: context_vars['gem_reporting_percentage'] = 0 now = datetime.datetime.now() month_ranges = get_month_day_range(now, depth=now.month) month_ranges.sort() h_teach_month = [] girls_violence_month = [] boys_violence_month =[] reported_violence_month = [] h_teach_data = [] gem_data = [] girls_violence_data = [] boys_violence_data = [] reported_violence_data = [] if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Admins'): for month_range in month_ranges: h_teach_month.append(month_range[0].strftime('%B')) h_teach_data.append(get_numeric_report_data('edtrac_violence_girls',time_range=month_range, to_ret = 'sum')) gem_data.append(get_numeric_report_data('edtrac_gem_abuse',time_range=month_range, to_ret = 'sum')) girls_violence_month.append(month_range[0].strftime('%B')) girls_violence_data.append(get_numeric_report_data('edtrac_violence_girls', time_range=month_range, to_ret='sum')) boys_violence_month.append(month_range[0].strftime('%B')) boys_violence_data.append(get_numeric_report_data('edtrac_violence_boys', time_range=month_range, to_ret='sum')) reported_violence_month.append(month_range[0].strftime('%B')) reported_violence_data.append(get_numeric_report_data('edtrac_violence_reported', time_range=month_range, to_ret='sum')) else: for month_range in month_ranges: h_teach_month.append(month_range[0].strftime('%B')) h_teach_data.append(get_numeric_report_data('edtrac_girls_violence',time_range=month_range, to_ret = 'sum', location=profile.location)) gem_data.append(get_numeric_report_data('edtrac_gem_abuse',time_range=month_range, to_ret = 'sum', location=profile.location)) girls_violence_month.append(month_range[0].strftime('%B')) girls_violence_data.append(get_numeric_report_data('edtrac_violence_girls', time_range=month_range, to_ret='sum', location=profile.location)) boys_violence_month.append(month_range[0].strftime('%B')) boys_violence_data.append(get_numeric_report_data('edtrac_violence_boys', time_range=month_range, to_ret='sum', location=profile.location)) reported_violence_month.append(month_range[0].strftime('%B')) reported_violence_data.append(get_numeric_report_data('edtrac_violence_reported', time_range=month_range, to_ret='sum', location=profile.location)) monthly_data_h_teachers = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(h_teach_month, h_teach_data)]) monthly_violence_data_girls = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(girls_violence_month, girls_violence_data)]) monthly_violence_data_boys = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(boys_violence_month, boys_violence_data)]) monthly_violence_data_reported = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(reported_violence_month, reported_violence_data)]) gem_month = copy.deepcopy(h_teach_month) monthly_data_gem = ';'.join([str(item[0])+'-'+str(item[1]) for item in zip(gem_month, gem_data)]) context_vars['monthly_data_gem'] = monthly_data_gem context_vars['monthly_violence_data_girls'] = monthly_violence_data_girls context_vars['monthly_violence_data_boys'] = monthly_violence_data_boys context_vars['monthly_violence_data_reported'] = monthly_violence_data_reported context_vars['monthly_data_h_teach'] = monthly_data_h_teachers context_vars['schools_responding_to_all_questions'] = total_number_of_schools_that_responded_to_all_violence_questions() if profile.is_member_of('Minstry Officials') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Admins'): return render_to_response('education/admin/admin_violence_details.html', context_vars, RequestContext(req)) elif profile.is_member_of('DEO'): context_vars['location_name'] = profile.location return render_to_response('education/deo/deo2_violence_details.html', context_vars, RequestContext(req)) def total_number_of_schools_that_responded_to_all_violence_questions(): schools_responding_to_boys_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_boys")] schools_responding_to_girls_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_girls")] schools_that_referred_violence = [__get_school_name_from(response) for response in __get_responses_for("edtrac_violence_reported")] schools_that_answered_all_questions = list(set(schools_responding_to_boys_violence).intersection(schools_responding_to_girls_violence).intersection(schools_that_referred_violence)) valid_school_names = [school for school in schools_that_answered_all_questions if school is not None] return len(valid_school_names) def __get_school_name_from(response): try: school_name = response.contact.emisreporter.schools.all()[0].name except IndexError: school_name = None return school_name def __get_responses_for(poll_name): responses_for_all_questions = Response.objects.filter(poll__name__in =["edtrac_violence_girls","edtrac_violence_boys","edtrac_violence_reported"]) return responses_for_all_questions.filter(poll__name = poll_name) class DistrictViolenceDetails(TemplateView): template_name = "education/dashboard/district_violence_detail.html" def get_context_data(self, **kwargs): context = super(DistrictViolenceDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) or self.request.user.get_profile().location schools = School.objects.filter( pk__in = EmisReporter.objects.filter(reporting_location=location).values_list('schools__pk', flat=True)) school_case = [] month_now, month_before = get_month_day_range(datetime.datetime.now(), depth=2) totalViolence = 0 nowViolence = 0 beforeViolence = 0 for school in schools: # optimize with value queries now_data = get_numeric_report_data( 'edtrac_headteachers_abuse', time_range = month_now, school = school, to_ret = 'sum', belongs_to = 'schools') before_data = get_numeric_report_data('edtrac_headteachers_abuse', time_range = month_before, school = school,\ to_ret = 'sum', belongs_to = 'schools') data = int(now_data + before_data) totalViolence += data nowViolence += now_data beforeViolence += before_data if now_data > 0 or before_data > 0: school_case.append((school, now_data, before_data, data)) context['totalViolence'] = totalViolence context['nowViolence'] = nowViolence context['beforeViolence'] = beforeViolence context['location'] = location context['school_vals'] = school_case context['month_now'] = month_now[0] context['month_before'] = month_before[0] return context class AttendanceAdminDetails(TemplateView): template_name = "education/admin/attendance_details.html" def get_context_data(self, **kwargs): context = super(AttendanceAdminDetails, self).get_context_data(**kwargs) #TODO: proper drilldown of attendance by school # National level ideally "admin" and can be superclassed to suit other roles profile = self.request.user.get_profile() context['role_name'] = profile.role.name if profile.is_member_of("Admins") or profile.is_member_of("Ministry Officials") or profile.is_member_of('UNICEF Officials'): names = list(set(EmisReporter.objects.exclude(reporting_location=None).filter(reporting_location__type="district").\ values_list('reporting_location__name',flat=True))) locations = Location.objects.filter(name__in=names).order_by("name") context['total_disticts'] = locations.count() headings = [ 'Location', 'Boys P3', 'Boys P6', 'Girls P3', 'Girls P6', 'Female Teachers', "Male Teachers"] context['headings'] = headings context['week'] = datetime.datetime.now() context['location'] = profile.location return context # search functionality def search_form(req): searchform = SearchForm() if req.method == 'POST': searchform = SearchForm(req.POST) if searchform.is_valid(): searchform.save() return render_to_response( 'education/partials/search-form.html', {'form': searchform}, RequestContext(req) ) class ProgressAdminDetails(TemplateView): template_name = "education/progress/admin_progress_details.html" def get_context_data(self, **kwargs): context = super(ProgressAdminDetails, self).get_context_data(**kwargs) context['progress'] = list_poll_responses(Poll.objects.get(name="edtrac_p3curriculum_progress")) getcontext().prec = 1 context['progress_figures'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_p3curriculum_progress"),\ location=self.request.user.get_profile().location, choices = [Decimal(str(key)) for key in themes.keys()]) return context CHOICES = [0, 25, 50, 75, 100] class MealsAdminDetails(TemplateView): template_name = "education/admin/admin_meals_details.html" def get_context_data(self, **kwargs): choices = CHOICES context = super(MealsAdminDetails, self).get_context_data(**kwargs) context['school_meals_reports'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_headteachers_meals"),\ month_filter=True, choices=choices) context['community_meals_reports'] = get_count_response_to_polls(Poll.objects.get(name="edtrac_smc_meals"), month_filter=True, choices=choices, with_percent=True) districts = Location.objects.filter(type="district", id__in =\ EmisReporter.objects.exclude(reporting_location = None).\ values_list('reporting_location__id', flat=True)).order_by('name').\ values_list('name', flat=True) # basic filtering for CSS districts = [[d, False] for d in districts] districts[0][1] = True context['districts'] = districts return context # Meals being had at a district class DistrictMealsDetails(DetailView): template_name = "education/admin/district_meal.html" context_object_name = "district_meals" model = Location def get_object(self): return self.model.objects.filter(type="district").get(name = self.kwargs.get('name')) def get_context_data(self, **kwargs): context = super(DistrictMealsDetails, self).get_context_data(**kwargs) location = self.get_object() choices = CHOICES school_meal_reports = get_count_response_to_polls( Poll.objects.get(name="edtrac_headteachers_meals"), location_name = location.name, month_filter=True, choices=choices, with_range = True, with_percent = True ) context['school_meals_reports'] = school_meal_reports context['location'] = location now = datetime.datetime.now() ranges = get_month_day_range(now, depth = now.month) ranges.reverse() context['date_ranges'] = ranges return context @login_required def deo_dashboard(req): location = req.user.get_profile().location return render_to_response("education/deo/deo_dashboard.html", generate_dashboard_vars(location=location), RequestContext(req)) @login_required def quitters(req): quitters = EmisReporter.objects.filter(connection__identity__in=Blacklist.objects.values_list('connection__identity',flat=True)) return render_to_response('education/partials/reporters/quitters.html',{'quitters':quitters}, RequestContext(req)) class ViolenceDeoDetails(TemplateView): template_name = "education/deo/deo_violence_details.html" def get_context_data(self, **kwargs): context = super(ViolenceDeoDetails, self).get_context_data(**kwargs) #context['violence_cases'] = list_poll_responses(Poll.objects.get(name="emis_headteachers_abuse")) context['violence_cases'] = poll_response_sum(Poll.objects.get(name="edtrac_headteachers_abuse"), location=self.request.user.get_profile().location, month_filter=True) return context @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ViolenceDeoDetails, self).dispatch(*args, **kwargs) class ProgressDeoDetails(TemplateView): template_name = "education/deo/deo_progress_details.html" def get_context_data(self, **kwargs): context = super(ProgressDeoDetails, self).get_context_data(**kwargs) #TODO mixins and filters context['progress'] = list_poll_responses(Poll.objects.get(name="edtrac_p3curriculum_progress")) return context ########################################################################################################## ########################################################################################################## ############################ More Generic Views ########################################################## ########################################################################################################## ########################################################################################################## ## management control panel @login_required def control_panel(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials') or profile.is_member_of('Ministry Officials'): return render_to_response('education/partials/control_panel.html', {}, RequestContext(req)) else: return render_to_response('education/partials/control_panel_dist.html',{}, RequestContext(req)) @login_required def audit_trail(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): # aparently the only places where comments are made is functions that involve editing users, reporters, etc. revisions = Revision.objects.exclude(comment='').order_by('-date_created').values_list('user__username','comment','date_created') else: revisions = Revision.objects.exclude(user__username = 'admin', comment='').\ order_by('-date_created').values_list('user__username','comment','date_created') return render_to_response('education/admin/audit_trail.html',{'revisions':revisions}, RequestContext(req)) class DistrictViolenceCommunityDetails(DetailView): context_object_name = "district_violence" model = Location def get_context_data(self, **kwargs): context = super(DistrictViolenceCommunityDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) or self.request.user.get_profile().location emis_reporters = EmisReporter.objects.filter(groups__name="GEM", connection__in =\ Poll.objects.get(name="edtrac_gem_abuse").responses.values_list('contact__connection',flat=True)) context['location'] = location context['reporters'] = emis_reporters context['month'] = datetime.datetime.now() return context # Progress happening in a district class DistrictProgressDetails(DetailView): context_object_name = "district_progress" model = Location #TODO provide filters def get_context_data(self, **kwargs): context = super(DistrictProgressDetails, self).get_context_data(**kwargs) location = Location.objects.filter(type="district").get(pk=int(self.kwargs.get('pk'))) context['location'] = location return context ########################################################################################################## ########################################################################################################## ################################ Other handy views for EduTrac ############################################ ########################################################################################################## ########################################################################################################## HEADINGS = ['District', 'Absent (%) This week', 'Absent (%) Last week'] #define location and school for p3 and p6 students locale = Location.objects.exclude(type="country").filter(type="district") @login_required def boysp3_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_boysp3_enrollment','edtrac_boysp3_attendance') return render_to_response("education/boysp3_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data', 'Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def boysp6_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_boysp6_enrollment','edtrac_boysp6_attendance') return render_to_response("education/boysp6_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def girlsp3_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_girlsp3_enrollment','edtrac_girlsp3_attendance') return render_to_response("education/girlsp3_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def girlsp6_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_girlsp6_enrollment','edtrac_girlsp6_attendance') return render_to_response("education/girlsp6_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def female_t_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_f_teachers_deployment','edtrac_f_teachers_attendance') return render_to_response("education/female_t_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) @login_required def male_t_district_attd_detail(req, location_id): """ This gets the details about schools in a district, the people in attedance, etc. """ select_location = Location.objects.get(id=location_id) school_data, existing_data = view_stats_by_school(location_id,'edtrac_m_teachers_deployment','edtrac_m_teachers_attendance') return render_to_response("education/male_t_district_attd_detail.html", { 'location':select_location,\ 'location_data':school_data, 'week':datetime.datetime.now(), 'headings' : ['School','Data','Current Week (%)', 'Week before (%)']}, RequestContext(req)) def boys_p3_attendance(req, **kwargs): profile = req.user.get_profile() location = profile.location if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): """ This view shows data by district """ locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.select_related().distinct().values_list('reporting_location__name', flat=True)).order_by("name") # return view that will give school-based views # --> ref function just below this <--- return boys_p3_attd_admin(req, locations=locations) else: #DEO dates = kwargs.get('dates') schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] for d in dates: temp.extend(return_absent('edtrac_boysp3_attendance', 'edtrac_boysp3_enrollment', school = school, date_week=d)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location':location } def boys_p3_attd_admin(req, **kwargs): """ Helper function to get differences in absenteeism across districts. """ # P3 attendance /// what to show an admin or Ministry official locations = kwargs.get('locations') to_ret = return_absent('edtrac_boysp3_attendance', 'edtrac_boysp3_enrollment', locations) return {'location_data':to_ret, 'headings': HEADINGS, 'week':datetime.datetime.now()} def boys_p6_attendance(req): profile = req.user.get_profile() location = profile.location if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return boys_p6_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_boysp6_attendance', 'edtrac_boysp6_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def boys_p6_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P6 boys. """ # P6 attendance /// what to show an admin or Ministry official to_ret = return_absent('edtrac_boysp6_attendance', 'edtrac_boysp6_enrollment', locations=locations) return {'location_data':to_ret,'headings':HEADINGS,'week':datetime.datetime.now()} def girls_p3_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return girls_p3_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_girlsp3_attendance', 'edtrac_girlsp3_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def girls_p3_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P3 girls """ to_ret = return_absent('edtrac_girlsp3_attendance', 'edtrac_girlsp3_enrollment', locations=locations) return {'location_data':to_ret,'headings':HEADINGS,'week':datetime.datetime.now()} def girls_p6_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.values_list('reporting_location__name', flat=True)).distinct().order_by("name") return girls_p6_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_girlsp6_attendance', 'edtrac_girlsp6_enrollment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def girls_p6_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for P6 girls """ to_ret = return_absent('edtrac_girlsp6_attendance', 'edtrac_girlsp6_enrollment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def female_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.distinct().values_list('reporting_location__name',flat=True)).order_by("name") return female_teacher_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_f_teachers_attendance', 'edtrac_f_teachers_deployment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def female_teacher_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for all female teachers """ to_ret = return_absent('edtrac_f_teachers_attendance', 'edtrac_f_teachers_deployment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def male_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): locations = Location.objects.exclude(type="country").filter(type="district", name__in=\ EmisReporter.objects.distinct().values_list('reporting_location__name',flat=True)).order_by("name") return male_teacher_attd_admin(req, locations=locations) else: #DEO schools = School.objects.filter(location=location) to_ret = [] for school in schools: temp = [school] temp.extend(return_absent('edtrac_m_teachers_attendance', 'edtrac_m_teachers_deployment', school = school)) to_ret.append(temp) to_ret.sort(key = operator.itemgetter(1)) # sort by current month data return { 'week':datetime.datetime.now(), 'headings':['School', "Current Week (%)", "Week before (%)", "Percentage change"], 'location_data': to_ret, 'location' : location } def male_teacher_attd_admin(req, locations=None): """ Helper function to get differences in absenteeism across districts for all female teachers """ to_ret = return_absent('edtrac_m_teachers_attendance', 'edtrac_m_teachers_deployment', locations=locations) return {'location_data':to_ret, 'headings':HEADINGS, 'week':datetime.datetime.now()} def male_head_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): schools = School.objects.filter(location__name__in=EmisReporter.objects.distinct().\ filter(reporting_location__type = 'district').values_list('reporting_location__name', flat=True)) else: #DEO schools = School.objects.filter(location=location) data_to_render = [] for school in schools: #TODO separate male and female head teachers data = poll_response_sum(Poll.objects.get(name="edtrac_head_teachers_attendance"),month_filter='weekly',location=school.location) data_to_render.append( [ school, school.location, data ] ) return render_to_response( 'education/partials/male_head_teacher_attendance.html', { 'week':datetime.datetime.now(), 'headings':['School', 'District', 'Number'], 'location_data': data_to_render }, RequestContext(req) ) def female_head_teacher_attendance(req): location = req.user.get_profile().location profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): schools = School.objects.filter(location__name__in= EmisReporter.objects.distinct().\ select_related().filter(reporting_location__type = 'district').values_list('reporting_location__name', flat=True)) else: #DEO schools = School.objects.select_related().filter(location=location).order_by("name", "location__name") data_to_render = [] for school in schools: #TODO separate male and female head teachers data = poll_response_sum(Poll.objects.get(name="edtrac_head_teachers_attendance"),month_filter='weekly',location=school.location) data_to_render.append( [ school, school.location, data ] ) return render_to_response( 'education/partials/female_head_teacher_attendance.html', { 'week':datetime.datetime.now(), 'headings':['School', 'District', 'Number'], 'location_data': data_to_render }, RequestContext(req) ) @login_required def time_range_boysp3(req): return view_stats(req, enrol_deploy_poll='edtrac_boysp3_enrollment', attendance_poll='edtrac_boysp3_attendance', title='P3 Boys Absenteeism', url_name_district = "boysp3-district-attd-detail" ) @login_required def time_range_boysp6(req): return view_stats(req, enrol_deploy_poll='edtrac_boysp6_enrollment', attendance_poll='edtrac_boysp6_attendance', title='P6 Boys Absenteeism', url_name_district = "boysp6-district-attd-detail" ) @login_required def time_range_girlsp3(req): return view_stats(req, enrol_deploy_poll='edtrac_girlsp3_enrollment', attendance_poll='edtrac_girlsp3_attendance', title='P3 Girls Absenteeism', url_name_district = "girlsp3-district-attd-detail" ) @login_required def time_range_girlsp6(req): return view_stats(req, enrol_deploy_poll='edtrac_girlsp6_enrollment', attendance_poll='edtrac_girlsp6_attendance', title='P6 Girls Absenteeism', url_name_district = "girlsp6-district-attd-detail" ) @login_required def time_range_teachers_m(req): return view_stats(req, enrol_deploy_poll='edtrac_m_teachers_deployment', attendance_poll='edtrac_m_teachers_attendance', title='Male teachers absenteeism', url_name_district = "male-teacher-district-attd-detail" ) @login_required def time_range_teachers_f(req): return view_stats(req, enrol_deploy_poll='edtrac_f_teachers_deployment', attendance_poll='edtrac_f_teachers_attendance', title='Female teachers absenteeism', url_name_district = "female-teacher-district-attd-detail" ) @login_required def time_range_head_teachers(req): """ Get a date-ranged page for Head teachers """ """ A function that compute time-ranged data for female teachers. This function is split in two: handling of POST data and GET data. It also makes a difference between User groups so you different role players like DEO, Admins, UNICEF Officials """ time_range_form = ResultForm() locations = Location.objects.filter(type='district').filter(pk__in = EmisReporter.objects.values_list('reporting_location__pk',flat=True)) if req.method == 'POST': # handling of POST data time_range_form = ResultForm(data=req.POST) to_ret = [] if time_range_form.is_valid(): from_date = time_range_form.cleaned_data['from_date'] to_date = time_range_form.cleaned_data['to_date'] month_delta = abs(from_date.month - to_date.month) date_weeks = [] if month_delta <= 2: # same month get days in between while from_date <= to_date: if from_date.weekday() == 3: #is to_day a Thursday? date_weeks.append(previous_calendar_week(t = from_date)) # get range from Wed to Thur. from_date += datetime.timedelta(days = 1) else: # case for when more than 2 months is selected while from_date <= to_date: #TODO refine data points date_weeks.append([dateutils.month_start(from_date),dateutils.month_end(from_date)]) from_date = dateutils.increment(from_date, months = 1) # splitting the results by analysing membership of Officials accessing EduTrac if req.user.get_profile().is_member_of('Ministry Officials') or\ req.user.get_profile().is_member_of('Admins') or req.user.get_profile().is_member_of('UNICEF Officials'): schools_temp = School.objects.select_related().\ filter(pk__in = EmisReporter.objects.select_related().\ filter(groups__name = "Head Teachers").values_list('schools__pk',flat=True)) for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True).select_related() location_schools = School.objects.filter(pk__in = schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) else: #Non admin types date_weeks, to_ret = [], [] date_weeks.append(previous_calendar_week(t = datetime.datetime.now())) for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True) location_schools = School.objects.filter(pk__in=schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) to_ret.append([location, temp]) return render_to_response('education/timeslider_base.html', {'form':time_range_form, 'dataset':to_ret, 'title':'Female Teacher Absenteeism', 'url_name':"female-teacher-district-attd-detail", 'date_batch':date_weeks}, RequestContext(req)) else: return render_to_response('education/timeslider_base.html', {'form':time_range_form, 'url_name':"female-teacher-district-attd-detail", 'title':'Male Teacher Absenteeism'}, RequestContext(req)) else: # initial GET view is displays difference between 2 weeks of the attendance of female teachers as reported by the Head Teacher date_weeks = [] location_data = [] # get current week date_weeks.append(previous_calendar_week()) temp_date = datetime.datetime(date_weeks[0][0].year, date_weeks[0][0].month, date_weeks[0][0].day) - datetime.timedelta(days = 1) # add previous week to date_weeks list date_weeks.append(previous_calendar_week(t = temp_date)) # cache schools query in memory (these are Schools that have enrollment data) schools_temp = Poll.objects.select_related().get(name = 'edtrac_f_teachers_deployment').responses.\ exclude(contact__emisreporter__schools__name = None).select_related() context_vars = {} for location in locations: temp = [] # get schools in this location schools = schools_temp.filter(contact__reporting_location__name = location.name).\ values_list('contact__emisreporter__schools__pk', flat=True) location_schools = School.objects.filter(pk__in = schools).select_related() for d in date_weeks: total_attendance = 0 # per school total_deployment = 0 # per school for school in location_schools: deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to='schools', school = school ) attendance = get_numeric_report_data('edtrac_f_teachers_attendance', school = school, time_range=list(d), to_ret = 'sum') total_attendance += attendance total_deployment += deployed try: percentage = (total_deployment - total_attendance) * 100 / total_deployment except ZeroDivisionError: percentage = '--' temp.append(percentage) try: diff = temp[0] - temp[1] except TypeError: diff = '--' location_data.append([location, temp[0], temp[1], diff]) context_vars.update({'location_data':location_data}) profile = req.user.get_profile() if profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): x = {'url_name':"female-teacher-district-attd-detail", "headings":["District", "Current Week", "Previous Week", "Percentage Change"]} else: x = {'url_name':"school-detail", "headings":["School", "Current Week", "Previous Week", "Percentage Change"]} context_vars.update({'form':time_range_form,'title':'Female Teachers Absenteeism'}) context_vars.update(x) return render_to_response('education/timeslider_base.html', context_vars, RequestContext(req)) def whitelist(request): numbers = [] for c in Connection.objects.exclude(backend__name='yo6200'): if not c.identity.strip() in numbers: numbers.append(c.identity.strip()) return render_to_response( "education/whitelist.txt", {'connections': Connection.objects.exclude(backend__name='yo6200').filter(identity__in=numbers)}, mimetype="text/plain", context_instance=RequestContext(request)) def _reload_whitelists(): refresh_urls = getattr(settings, 'REFRESH_WHITELIST_URL', None) if refresh_urls is not None: if not type(refresh_urls) == list: refresh_urls = [refresh_urls, ] for refresh_url in refresh_urls: try: status_code = urlopen(refresh_url).getcode() if int(status_code / 100) == 2: continue else: return False except Exception as e: return False return True return False def _addto_autoreg(connections): for connection in connections: if not connection.contact and\ not ScriptProgress.objects.filter(script__slug='emis_autoreg', connection=connection).count(): ScriptProgress.objects.create(script=Script.objects.get(slug="edtrac_autoreg"),\ connection=connection) @login_required def add_connection(request): form = NewConnectionForm() if request.method == 'POST': form = NewConnectionForm(request.POST) connections = [] if form.is_valid(): identity = form.cleaned_data['identity'] identity, backend = assign_backend(str(identity.strip())) # create connection, created = Connection.objects.get_or_create(identity=identity, backend=backend) # in case a duplicate process does exist, delete it ScriptProgress.objects.filter(connection=connection).delete() connections.append(connection) other_numbers = request.POST.getlist('other_nums') if len(other_numbers) > 0: for number in other_numbers: identity, backend = assign_backend(str(number.strip())) connection, created = Connection.objects.get_or_create(identity=identity, backend=backend) connections.append(connection) _addto_autoreg(connections) _reload_whitelists() # time.sleep(2) return render_to_response('education/partials/addnumbers_row.html', {'object':connections, 'selectable':False}, RequestContext(request)) return render_to_response("education/partials/new_connection.html", {'form':form}, RequestContext(request)) @login_required def delete_connection(request, connection_id): connection = get_object_or_404(Connection, pk=connection_id) connection.delete() _reload_whitelists() return render_to_response("education/partials/connection_view.html", {'object':connection.contact }, context_instance=RequestContext(request)) @login_required def comments(req): profile = req.user.get_profile() if profile.is_member_of('Admins') or profile.is_member_of('Ministry Officials') or profile.is_member_of('UNICEF Officials'): comments = [(r.get_commentable_display(), r.comment, r.user, r.get_reporting_period_display(), get_range_on_date(r.reporting_period, r) ) for r in ReportComment.objects.order_by('-report_date')] else: # DFO/DEO should get only information on their districts comments = [(r.get_commentable_display(), r.comment, r.user, r.get_reporting_period_display(), get_range_on_date(r.reporting_period, r)) for r in ReportComment.objects.filter(user__profile__location=profile.location).order_by('-report_date')] return render_to_response('education/partials/comments.html', {'data_set':comments}, RequestContext(req)) @login_required def new_comment(req): report_comment_form = ReportCommentForm(initial = {'user':req.user.pk}) if req.method == 'POST': report_comment_form = ReportCommentForm(req.POST) if report_comment_form.is_valid(): with reversion.create_revision(): report_comment_form.save() reversion.set_comment('wrote a comment') return HttpResponseRedirect(reverse('comments')) else: return render_to_response('education/partials/new_comment.html', {'form':report_comment_form}, RequestContext(req)) else: return render_to_response('education/partials/new_comment.html',{'form':report_comment_form}, RequestContext(req)) @login_required def edit_comment(req, report_comment_pk): report_comment = get_object_or_404(ReportComment, pk=report_comment_pk) report_comment_form = ReportCommentForm(instance=report_comment) if req.method == 'POST': report_comment_form = ReportCommentForm(instance=report_comment, data=req.POST) if report_comment_form.is_valid(): with reversion.create_revision(): report_comment_form.save() reversion.set_comment('edited comment') return HttpResponseRedirect(reverse('comments')) else: return render_to_response('education/partials/edit_comment.html', {'form':report_comment_form}, RequestContext(req)) else: return render_to_response('education/partials/edit_comment.html', {'form':report_comment_form}, RequestContext(req)) @login_required def delete_comment(req, report_comment_pk): report_comment = get_object_or_404(ReportComment, pk=report_comment_pk) if req.method == 'POST': with reversion.create_revision(): report_comment.delete() reversion.set_comment('deleted comment') return HttpResponse(status=200) @login_required def delete_reporter(request, reporter_pk): reporter = get_object_or_404(EmisReporter, pk=reporter_pk) reporter_name = reporter.name if request.method == 'POST': with reversion.create_revision(): reversion.set_comment('deleted %s'%reporter_name) reporter.delete() return HttpResponse(status=200) @login_required def edit_reporter(request, reporter_pk): reporter = get_object_or_404(EmisReporter, pk=reporter_pk) reporter_group_name = reporter.groups.all()[0].name if request.method == 'POST': reporter_form = EditReporterForm(instance=reporter,data=request.POST) if reporter_form.is_valid(): with reversion.create_revision(): reporter_form.save() reversion.set_comment('edited %s details' % reporter.name) saved_reporter_grp = EmisReporter.objects.get(pk=reporter_pk).groups.all()[0].name if reporter.default_connection and reporter.groups.count() > 0: # remove from other scripts # if reporter's groups remain the same. if reporter_group_name == saved_reporter_grp: pass else: ScriptProgress.objects.exclude(script__slug="edtrac_autoreg").filter(connection=reporter.default_connection).delete() _schedule_teacher_weekly_scripts(reporter.groups.all()[0], reporter.default_connection, ['Teachers']) _schedule_weekly_scripts(reporter.groups.all()[0], reporter.default_connection, ['Head Teachers', 'SMC']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_head_teachers_monthly', 'last', ['Head Teachers']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_gem_monthly', 20, ['GEM']) _schedule_monthly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_smc_monthly', 5, ['SMC']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_smc_termly', ['SMC']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_p3_enrollment_headteacher_termly', ['Head Teachers']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_p6_enrollment_headteacher_termly', ['Head Teachers']) _schedule_termly_script(reporter.groups.all()[0], reporter.default_connection, 'edtrac_teacher_deployment_headteacher_termly', ['Head Teachers']) return redirect("reporter-detail", pk=reporter.pk) else: if reporter.schools.exists(): reporter_form = EditReporterForm(instance=reporter, initial={'schools':reporter.schools.all()[0]}) else: reporter_form = EditReporterForm(instance=reporter) return render_to_response('education/edit_reporter.html', {'reporter_form': reporter_form, 'reporter': reporter}, context_instance=RequestContext(request)) @login_required def add_schools(request): if request.method == 'POST': form = SchoolForm(request.POST) schools = [] if form.is_valid(): names = filter(None, request.POST.getlist('name')) locations = request.POST.getlist('location') if len(names) > 0: for i, name in enumerate(names): location = Location.objects.get(pk=int(locations[i])) name, created = School.objects.get_or_create(name=name, location=location) schools.append(name) return render_to_response('education/partials/addschools_row.html', {'object':schools, 'selectable':False}, RequestContext(request)) else: form = SchoolForm() return render_to_response('education/deo/add_schools.html', {'form': form, }, context_instance=RequestContext(request)) @login_required def delete_school(request, school_pk): school = get_object_or_404(School, pk=school_pk) school_name = school.name if request.method == 'POST': with reversion.create_revision(): school.delete() reversion.set_comment("%s deleted %s"%(request.user.username, school_name)) return HttpResponse(status=200) @login_required def edit_school(request, school_pk): school = get_object_or_404(School, pk=school_pk) school_form = SchoolForm(instance=school) school_name = school.name if request.method == 'POST': school_form = SchoolForm(instance=school, data=request.POST) if school_form.is_valid(): with reversion.create_revision(): school_form.save() reversion.set_comment('edited %s' % school_name) else: return render_to_response('education/partials/edit_school.html' , {'school_form': school_form, 'school' : school}, context_instance=RequestContext(request)) return render_to_response('/education/partials/school_row.html', {'object':School.objects.get(pk=school_pk), 'selectable':True}, context_instance=RequestContext(request)) else: return render_to_response('education/partials/edit_school.html', {'school_form': school_form, 'school': school}, context_instance=RequestContext(request)) @login_required def school_detail(request, school_id): school = School.objects.get(id=school_id) today = date.today() month_ranges = get_month_day_range(today, depth=today.month) month_ranges.reverse() slug_list = ['girlsp3', 'boysp3', 'girlsp6', 'boysp6'] slug_list_tr = ['f_teachers', 'm_teachers'] monthly_data = [] monthly_data_teachers = [] monthly_data_head_teachers = [] monthly_data_violence = [] monthly_data_meals = [] for month_range in month_ranges: monthly_data.append( [return_absent_month( 'edtrac_'+ '%s'%slug + '_attendance', 'edtrac_'+ '%s'%slug + '_enrollment', month_range = month_range, school = school) for slug in slug_list]) monthly_data_teachers.append( [return_absent_month( 'edtrac_'+'%s'%slug + '_attendance', 'edtrac_'+'%s'%slug + '_deployment', month_range = month_range, school=school) for slug in slug_list_tr]) reporters = [] reps = school.emisreporter_set.values() for rep in reps: r = EmisReporter.objects.get(id=rep['id']) reporters.append(r) boys_p3_enrolled = poll_responses_term('edtrac_boysp3_enrollment', belongs_to='schools', school = school) boys_p6_enrolled = poll_responses_term('edtrac_boysp6_enrollment', belongs_to='schools', school = school) girls_p3_enrolled = poll_responses_term('edtrac_girlsp3_enrollment', belongs_to='schools', school = school) girls_p6_enrolled = poll_responses_term('edtrac_girlsp6_enrollment', belongs_to='schools', school = school) m_teachers_deployed = poll_responses_term('edtrac_m_teachers_deployment', belongs_to = 'schools', school = school) f_teachers_deployed = poll_responses_term('edtrac_f_teachers_deployment', belongs_to = 'schools', school = school) return render_to_response("education/school_detail.html", {\ 'school_name': school.name, 'months' : [d_start for d_start, d_end in month_ranges], 'monthly_data' : monthly_data, 'monthly_data_teachers' : monthly_data_teachers, 'monthly_data_head_teachers': monthly_data_head_teachers, 'monthly_data_violence' : monthly_data_violence, 'monthly_data_meals' : monthly_data_meals, 'reporters' : reporters, 'boys_p3_enrolled': boys_p3_enrolled, 'boys_p6_enrolled': boys_p6_enrolled, 'girls_p3_enrolled' : girls_p3_enrolled, 'girls_p6_enrolled' : girls_p6_enrolled, 'm_teachers_deployed': m_teachers_deployed, 'f_teachers_deployed': f_teachers_deployed }, RequestContext(request)) # analytics specific for emis {copy, but adjust to suit your needs} @login_required def to_excel(request, start_date=None, end_date=None, district_id=None): return create_excel_dataset(request, start_date, end_date, district_id) @login_required def school_reporters_to_excel(req): book = xlwt.Workbook() all_schools = School.objects.all() sheet = book.add_sheet('School Reporters') headings = ['School', 'Reporters'] rowx = 0 for colx, value in enumerate(headings): sheet.write(rowx, colx, value) sheet.set_panes_frozen(True) sheet.set_horz_split_pos(rowx+1) sheet.set_remove_splits(True) for row in all_schools: rowx += 1 for colx, value in enumerate([row.name, ', '.join([reporter.name for reporter in row.emisreporter_set.all()])]): sheet.write(rowx, colx, value) response = HttpResponse(mimetype="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment; filename=school_reporters_data.xls' book.save(response) return response @login_required def system_report(req=None): book = xlwt.Workbook() school_dates = [ getattr(settings, 'SCHOOL_TERM_START'), getattr(settings, 'SCHOOL_TERM_END'), ] first_date = school_dates[0] last_date = school_dates[1] date_bunches = [] while first_date <= last_date: tmp = get_day_range(first_date) first_date = tmp[0] date_bunches.append(get_day_range(first_date)) first_date = dateutils.increment(first_date, weeks=1) profile = req.user.get_profile() enrolled_answered = \ EnrolledDeployedQuestionsAnswered.objects.select_related() headings = ['School'] + [d.strftime("%d/%m/%Y") for d, _ in date_bunches] if profile.is_member_of('Admins') or profile.is_member_of('UNICEF Officials'): district_names = enrolled_answered.values_list( 'school__location__name', flat=True ).distinct() else: location = profile.location district_names = [location.name] district_schools = {} for dn in district_names: district_schools[dn] = School.objects.select_related().filter( pk__in=enrolled_answered.filter( school__location__name=dn ).values_list('school__pk', flat=True)).order_by('name') polls = Poll.objects.select_related().filter( Q(name__icontains="boys") | Q(name__icontains="girls") | Q(name='edtrac_f_teachers_attendance') | Q(name='edtrac_m_teachers_attendance') ) for district_name in district_schools.keys(): container = [] sheet = book.add_sheet(district_name, cell_overwrite_ok=True) rowx = 0 for colx, val_headings in enumerate(headings): sheet.write(rowx, colx, val_headings) sheet.set_panes_frozen(True) # in general, freeze after last heading row sheet.set_horz_split_pos(rowx + 1) # if user does unfreeze, don't leave a split there sheet.set_remove_splits(True) for school in district_schools[district_name]: school_vals = [school.name] for d_bunch in date_bunches: submission_count = 0 for poll in polls: submission_count += poll.responses.filter( contact__in=school.emisreporter_set.values_list( 'connection__contact'), date__range = d_bunch ).count() school_vals.extend([submission_count]) container.append(school_vals) for row in container: rowx += 1 for colx, value in enumerate(row): sheet.write(rowx, colx, value) response = HttpResponse(mimetype="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment; filename=SystemReport.xls' book.save(response) return response @login_required def excel_reports(req): return render_to_response('education/excelreports/excel_dashboard.html',{},RequestContext(req)) @login_required def edit_user(request, user_pk=None): title="" user=User() if request.method == 'POST' and request.user.get_profile().role_id == Role.objects.get(name = 'Admins').id: if user_pk: user = get_object_or_404(User, pk=user_pk) user_form = UserForm(request.POST,instance=user,edit=True) if user_form.is_valid(): with reversion.create_revision(): user = user_form.save() if user.groups.count() == 0: group = Group.objects.get(pk=user_form.cleaned_data['groups'][0].pk) user.groups.add(group) try: profile=UserProfile.objects.get(user=user) profile.location=user_form.cleaned_data['location'] profile.role=Role.objects.get(name=user_form.cleaned_data['groups'][0].name) profile.save() except UserProfile.DoesNotExist: UserProfile.objects.create(name=user.first_name,user=user,role=Role.objects.get(pk=user_form.cleaned_data['groups'][0].pk),location=user_form.cleaned_data['location']) reversion.set_comment("edited %s's profile" % user.username) return HttpResponseRedirect(reverse("emis-users")) elif user_pk: user = get_object_or_404(User, pk=user_pk) user_form = UserForm(instance=user,edit=True) title="Editing "+user.username else: user_form = UserForm(instance=user) return render_to_response('education/partials/edit_user.html', {'user_form': user_form,'title':title}, context_instance=RequestContext(request)) def htattendance(request, start_date=None, end_date=None, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) smc_htpresent = Poll.objects.get(name='emis_absence').responses.exclude(has_errors=True)\ .filter(date__range=(dates.get('start'), dates.get('end')))\ .filter(message__connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all())\ .order_by('message__date') return generic(request, model = Poll, queryset = smc_htpresent, objects_per_page = 50, results_title = 'Head Teacher Presence as Reported by SMCs', columns = [ ('school', False, 'school', None), ('present', False, 'present', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/ht_attendance_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timeslider_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) def gem_htattendance(request, start_date=None, end_date=None, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) gem_htpresent = XFormSubmission.objects.filter(xform__keyword='gemteachers').exclude(has_errors=True)\ .filter(created__range=(dates.get('start'), dates.get('end')))\ .filter(connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all())\ .order_by('created') return generic(request, model = XFormSubmission, queryset = gem_htpresent, objects_per_page = 50, results_title = 'Head Teacher Presence as Reported by GEM', columns = [ ('school', False, 'school', None), ('present', False, 'present', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/gemht_attendance_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timesli`der_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) def meals(request, district_id=None): user_location = get_location(request, district_id) dates = get_xform_dates(request) meals = Poll.objects.get(name='emis_meals').responses.exclude(has_errors=True)\ .filter(date__range=(dates.get('start'), dates.get('end')))\ .filter(message__connection__contact__emisreporter__reporting_location__in=user_location.get_descendants(include_self=True).all()) return generic(request, model = Poll, queryset = meals, objects_per_page = 50, results_title = 'Pupils who had Meals at School', columns = [ ('school', False, 'school', None), ('estimated number', False, 'number', None), ('reporting date', False, 'date', None), ], partial_row = 'education/partials/meals_row.html', partial_header = 'education/partials/partial_header.html', base_template = 'education/timeslider_base.html', needs_date = True, selectable = False, dates = get_xform_dates, ) @super_user_required def edit_scripts(request): forms = [] for script in Script.objects.exclude(name='Special Script').order_by('slug'): forms.append((script, ScriptsForm(instance=script))) if request.method == 'POST': script_form = ScriptsForm(request.POST,instance=Script.objects.get(slug=request.POST.get('slug'))) if script_form.is_valid(): script_form.save() return render_to_response('education/partials/edit_script.html', {'forms': forms, 'management_for': 'scripts'}, context_instance=RequestContext(request)) def emis_scripts_special(req): scripts = Script.objects.exclude(slug__icontains='weekly').exclude(name='Special Script').exclude(slug='edtrac_autoreg').order_by('slug') if req.method == 'POST': checked_numbers = req.POST.getlist('checked_numbers') checked_numbers = [n for n in checked_numbers if re.match(r'\d+', n)] poll_questions = req.POST.getlist('poll_questions') poll_scripts = [pq.split('-') for pq in poll_questions] #(poll_id, script_slug) d = datetime.datetime.now() _script = Script.objects.create(slug=\ "edtrac_%s %s %s %s:%s:%s"%(d.year,d.month,d.day,d.hour, d.minute, d.second), name="Special Script") _poll_scripts = [] # make sure that the poll/script to sent to just one group not a mixture of groups. reporter_group_name = EmisReporter.objects.get(id=checked_numbers[0]).groups.all()[0].name.lower().replace(' ', '_') for id, script_slug in poll_scripts: if re.search(reporter_group_name, script_slug): _poll_scripts.append((id, script_slug)) for i, li in enumerate(_poll_scripts): poll_id, script_slug = li _script.steps.add(ScriptStep.objects.create( script = _script, poll = Poll.objects.get(id = poll_id), order = i, # using index for different order??? rule = ScriptStep.RESEND_MOVEON, num_tries = 1, start_offset = 60, retry_offset = 86400, giveup_offset = 86400, )) _script.save() if len(checked_numbers) < 25 and len(checked_numbers) > 0: # assuming that "all" is not checked for reporter in EmisReporter.objects.filter(id__in=checked_numbers).exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() else: # what if the reporting location is different? Would you instead want to poll the different districts? single_reporter_location = True # flag reporter_location = EmisReporter.objects.filter(id__in=checked_numbers).\ exclude(reporting_location=None).values_list('reporting_location__name', flat=True) if reporter_location.count() > 0 and len(set(reporter_location)) > 1: single_reporter_location = False reporter_location = EmisReporter.objects.filter(reporting_location__type = 'district').\ values_list('reporting_location__name',flat=True) else: reporter_location = EmisReporter.objects.filter(reporting_location__type='district').\ filter(reporting_location__name = reporter_location[0]).values_list('reporting_location__name',flat=True) single_school = True reporter_schools = EmisReporter.objects.filter(id__in=checked_numbers).\ exclude(schools=None).values_list('schools__name', flat=True) if reporter_schools.count() > 0 and len(set(reporter_schools)) > 1: single_school = False reporter_schools = EmisReporter.objects.values_list('schools__name',flat=True) else: reporter_schools = EmisReporter.objects.filter(schools__name=reporter_schools[0]).values_list( 'schools__name', flat=True ) if single_reporter_location or single_school: for reporter in EmisReporter.objects.filter(schools__name__in=reporter_schools, reporting_location__name__in = reporter_location, groups__name =\ ' '.join([i.capitalize() for i in reporter_group_name.replace('_',' ').split()])).\ exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() else: for reporter in EmisReporter.objects.filter(groups__name =\ ' '.join([i.capitalize() for i in reporter_group_name.replace('_',' ').split()])).exclude(connection=None): sp = ScriptProgress.objects.create(connection=reporter.default_connection, script=_script) sp.set_time(datetime.datetime.now()+datetime.timedelta(seconds=90)) # 30s after default cron wait time sp.save() return HttpResponseRedirect(reverse('emis-contact')) else: return render_to_response('education/partials/reporters/special_scripts.html',{'scripts':scripts}, RequestContext(req)) def reschedule_scripts(request, script_slug): grp = get_script_grp(script_slug) if script_slug.endswith('_weekly'): reschedule_weekly_polls(grp) elif script_slug.endswith('_monthly'): reschedule_monthly_polls(grp) else: if request.POST.has_key('date'): date = request.POST.get('date') else: date = None reschedule_termly_polls(grp, date) new_scripts = ScriptProgress.objects.filter(script__slug=script_slug) if new_scripts: new_script_date = new_scripts[0].time response = HttpResponse("This Script has been rescheduled to: %s " % new_script_date.strftime("%d-%m-%Y %H:%M")) return response else: return HttpResponse("This script can't be rescheduled. Try again") class EdtracReporter(ListView): model = EmisReporter template_name = "education/emisreporter_list.html" context_object_name = "reporter_list" ########## Maps ################# def attendance_visualization(req): return render_to_response( 'education/partials/map_attendance.html', { 'geoserver_url':getattr(settings, 'GEOSERVER_URL', 'http://localhost/geoserver') }, context_instance = RequestContext(req)) class AbsenteeismForm(forms.Form): error_css_class = 'error' select_choices = [('all', '--'), ('P3Boys', 'P3 Boys'), ('P3Girls', 'P3 Girls'), ('P3Pupils', 'P3 Pupils'), ('P6Boys', 'P6 Boys'), ('P6Girls', 'P6 Girls'), ('P6Pupils', 'P6 Pupils'), ('MaleTeachers', 'Male Teachers'), ('FemaleTeachers', 'Female Teachers'), ('Teachers', 'Teachers'), ('MaleHeadTeachers', 'Male Head Teachers'), ('FemaleHeadTeachers', 'Female Head Teachers'), ('HeadTeachers', 'Head Teachers'), ] from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) indicator = forms.ChoiceField(choices=select_choices, required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: if is_empty(data.get('indicator')): raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data @login_required def detail_attd(request, district=None): locations = get_location_for_absenteeism_view(district, request) time_range_depth = 4 if request.method == 'POST': absenteeism_form = AbsenteeismForm(data=request.POST) if absenteeism_form.is_valid(): indicator = absenteeism_form.cleaned_data['indicator'] week_range = get_date_range(absenteeism_form.cleaned_data['from_date'], absenteeism_form.cleaned_data['to_date'], time_range_depth) else: return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form}, RequestContext(request)) else: absenteeism_form = AbsenteeismForm(initial={'indicator': 'all'}) week_range = get_week_date(time_range_depth) indicator = "all" week_range.reverse() config_list = get_polls_for_keyword(indicator) collective_result, time_data, reporting_school_percent = get_aggregated_report(locations, config_list, week_range) weeks = ["%s - %s" % (i[0].strftime("%m/%d/%Y"), i[1].strftime("%m/%d/%Y")) for i in week_range] return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form, 'collective_result_keys': [config['collective_dict_key'] for config in config_list], 'collective_result': collective_result, 'time_data': mark_safe(json.dumps(time_data)), 'school_percent' : reporting_school_percent, 'weeks': mark_safe(json.dumps(weeks)), "locations": locations}, RequestContext(request)) @login_required def detail_dashboard(request, district=None): locations = get_location_for_absenteeism_view(district, request) time_range_depth = 4 if request.method == 'POST': absenteeism_form = AbsenteeismForm(data=request.POST) if absenteeism_form.is_valid(): indicator = absenteeism_form.cleaned_data['indicator'] week_range = get_date_range(absenteeism_form.cleaned_data['from_date'], absenteeism_form.cleaned_data['to_date'], time_range_depth) else: return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form}, RequestContext(request)) else: absenteeism_form = AbsenteeismForm(initial={'indicator': 'all'}) week_range = get_week_date(time_range_depth) indicator = "all" week_range.reverse() config_list = get_polls_for_keyword(indicator) collective_result, time_data, reporting_school_percent = get_aggregated_report(locations, config_list, week_range) weeks = ["%s - %s" % (i[0].strftime("%m/%d/%Y"), i[1].strftime("%m/%d/%Y")) for i in week_range] return render_to_response('education/admin/detail_attd.html', {'form': absenteeism_form, 'collective_result_keys': [config['collective_dict_key'] for config in config_list], 'collective_result': collective_result, 'time_data': mark_safe(json.dumps(time_data)), 'school_percent' : reporting_school_percent, 'weeks': mark_safe(json.dumps(weeks)), "locations": locations}, RequestContext(request)) @login_required def detail_attd_school(request, location): name = request.GET['school'] school_id = School.objects.get(name=name, location__name=location).id return redirect(reverse('school-detail',args=(school_id,))) class ExportPollForm(forms.Form): error_css_class = 'error' select_choices = list(Poll.objects.values_list(*['pk','name'])) from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) poll_name = forms.ChoiceField(choices=select_choices, required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: if is_empty(data.get('poll_name')): raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data def get_district_parent(reporting_location): parent_locations = reporting_location.get_ancestors() district_parent = [parent for parent in parent_locations if parent.type.name == 'district'] return district_parent[0].name def _format_responses(responses): a = [] for response in responses: if response.contact: contact = response.contact sender = contact location_type = contact.reporting_location.type reporting_location = contact.reporting_location.name if not location_type.name == 'district' and not location_type.name == 'country': reporting_location = get_district_parent(contact.reporting_location) location_type = 'district' school = ", ".join(contact.emisreporter.schools.values_list('name', flat=True)) else: sender = response.message.connection.identity location_type = "--" reporting_location = "--" school = "--" date = response.message.date if response.poll.type == "t": value = response.eav.poll_text_value elif response.poll.type == "n": if hasattr(response.eav, 'poll_number_value'): value = response.eav.poll_number_value else: value = 0 elif response.poll.type == 'l': value = response.eav.poll_location_value.name category = response.categories.values_list('category__name',flat=True) if len(category) == 0: category = "--" else: category = ", ".join(category) a.append((sender,location_type,reporting_location,school,date,value,category)) return a def _get_identity(r): return r.default_connection.identity if r.default_connection else "--" def _format_reporters(reporters): return [[r.id,r.name, _get_identity(r),r.reporting_location.type.name, r.reporting_location.name, ", ".join(r.schools.values_list('name', flat=True))] for r in reporters] @login_required def edtrac_export_poll_responses(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': form = ExportPollForm() else: form = ExportPollForm(data=request.POST) if form.is_valid(): poll = get_object_or_404(Poll, pk=form.cleaned_data['poll_name']) responses = poll.responses.all().order_by('-pk') to_date = form.cleaned_data['to_date'] from_date = form.cleaned_data['from_date'] if from_date and to_date: responses = responses.filter(date__range=[from_date, to_date]) resp = render_to_response( 'education/admin/export_poll_responses.csv', { 'responses': _format_responses(responses) }, mimetype='text/csv', context_instance=RequestContext(request) ) resp['Content-Disposition'] = 'attachment;filename="%s.csv"' \ % poll.name return resp return render_to_response('education/admin/export_poll_responses.html', {'form': form}, RequestContext(request), ) @login_required def edit_sub_county_reporters(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': sub_county_reporters = EmisReporter.objects.filter(reporting_location__type = 'sub_county') return render_to_response('education/admin/edit_sub_county_reporters.html', {'reporters':sub_county_reporters},RequestContext(request)) @login_required def export_sub_county_reporters(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': sub_county_reporters = EmisReporter.objects.filter(reporting_location__type='sub_county') resp = render_to_response('education/admin/export_sub_county_reporters.csv', {'responses': _format_reporters(sub_county_reporters)}, mimetype='text/csv', context_instance=RequestContext(request)) resp['Content-Disposition'] = 'attachment;filename="sub_county_reporters.csv"' return resp class ExportMessageForm(forms.Form): error_css_class = 'error' from_date = forms.DateTimeField(required=False) to_date = forms.DateTimeField(required=False) def clean(self): data = self.cleaned_data if data.get('from_date') is None or data.get('to_date') is None: raise forms.ValidationError("Fields blank") if data.get('from_date') > data.get('to_date'): raise forms.ValidationError("To date less than from date") return data def _get_school(m): if m.connection.contact.emisreporter.schools.all().exists(): return m.connection.contact.emisreporter.schools.all()[0] return None def _format_messages(messages): return[ [m ,m.connection.contact.reporting_location,_get_school(m),m.connection.contact,m.connection,m.date ] for m in messages] @login_required def edtrac_export_error_messages(request): profile = request.user.get_profile() if not (profile.is_member_of('Ministry Officials') or profile.is_member_of('Admins') or profile.is_member_of( 'UNICEF Officials')): return redirect('/') if request.method == 'GET': form = ExportMessageForm() else: form = ExportMessageForm(data=request.POST) if form.is_valid(): messages = Message.objects.exclude( connection__identity__in = getattr(settings, 'MODEM_NUMBERS') ).filter(direction='I', connection__contact__emisreporter__reporting_location__in =\ locations.get(name__iexact="Uganda").get_descendants(include_self=True).all() ) messages= messages.filter(poll_responses=None) | messages.filter(poll_responses__has_errors=True) to_date = form.cleaned_data['to_date'] from_date = form.cleaned_data['from_date'] if from_date and to_date: messages = messages.filter(date__range=[from_date, to_date]) resp = render_to_response('education/admin/export_error_messages.csv', {'messages' : _format_messages(messages)}, mimetype='text/csv', context_instance=RequestContext(request)) resp['Content-Disposition'] = 'attachment;filename="error_messages.csv"'\ return resp return render_to_response('education/admin/export_error_messages.html', {'form':form},RequestContext(request)) def get_schools(request): location = request.GET['location'] list_of_schools = [{'text':'--------------','value':''}] if not is_empty(location): filtered_schools = School.objects.filter(location=Location.objects.get(pk=location,type__slug='district')) location_schools = [{'text':school.name,'value':school.pk} for school in filtered_schools] list_of_schools.extend(location_schools) return HttpResponse(json.dumps(list_of_schools))
""" inputpy.param This module exports two classes: - Param - ParamStore The Design and DesignSpace classes will probably be moved (probably merged with the existing classes in inputpy.design). :copyright: (c) 2013 by Christoffer Fink. :license: MIT. See LICENSE for details. """ from inputpy.util import Evaluator from inputpy.util import initOrder import inputpy.generators as generator import inputpy.util as util class Identifiable: """ This class is a mixin. It provides all subclasses with a getId() method. An instance can be initialized using an id argument. If none is provided, then a unique id will be constructed automatically. """ def __init__(self, objId=None): self.__id = objId or str(id(self)) def getId(self): return self.__id class Param(Identifiable): """ The parameter class is pretty dumb. It represents the definition of a parameter as opposed to an actual parameter. This means that it knows only the information that was used to define it. It will never have a value (with the exception of fixed values), and does not know how to generate appropriate values or even which ones would be valid. """ def __init__(self, paramId, paramType, fixed=None, inclMin=None, exclMin=None, inclMax=None, exclMax=None): # Check arguments. if paramType is None: raise ValueError('The parameter type was None') if inclMin is not None and exclMin is not None: raise ValueError('Defined both inclusive and exclusive limits') if inclMax is not None and exclMax is not None: raise ValueError('Defined both inclusive and exclusive limits') if inclMin is None: minTmp = exclMin else: minTmp = inclMin if inclMax is None: maxTmp = exclMax else: maxTmp = inclMax minTmp = self.__transformLimit(minTmp) maxTmp = self.__transformLimit(maxTmp) # Are max/min exclusive? minIsExcl = exclMin is not None maxIsExcl = exclMax is not None # Initialize fields. Identifiable.__init__(self, paramId) self.type = paramType self.exclMin = minIsExcl self.exclMax = maxIsExcl self.minDependees = [] # Referenced parameters in min expression. self.maxDependees = [] # Referenced parameters in max expression. self.min = [] self.max = [] for minLimit in minTmp: self.__initMinMax(self.min, self.minDependees, minLimit) for maxLimit in maxTmp: self.__initMinMax(self.max, self.maxDependees, maxLimit) self.__padLimits(self.min, self.max) self.min = tuple(self.min) self.max = tuple(self.max) self.minDependees = tuple(self.minDependees) self.maxDependees = tuple(self.maxDependees) # Set fixed value, if any. self.setFixed(fixed) @staticmethod def __padLimits(minLimits, maxLimits): minLen = len(minLimits) maxLen = len(maxLimits) if minLen < maxLen: limits = minLimits else: limits = maxLimits for i in range(abs(minLen - maxLen)): limits.append(None) # Is this the best way to check whether limit is already a sequence? @staticmethod def __transformLimit(limit): if limit is None: return (None,) # A string is also a sequence, but it always represents a single limit. if isinstance(limit, str): return (limit,) try: iter(limit) except TypeError: return (limit,) else: return limit @staticmethod def __initMinMax(limits, dependees, limit): # If min/max are expressions, these will be parsed to find # dependencies. If the expression does not contain references to any # other parameters, then the expression is evaluated immediately. # Any dependencies are recorded. if type(limit) is str: dependees.extend(Evaluator.parseDependencies(limit)) if len(dependees) == 0: limit = Evaluator.evaluate(limit) limits.append(limit) def isFixed(self): """ Return whether this parameter has been set to a fixed value. """ return self.fixed is not None def setFixed(self, value): """ Sets this parameter to a fixed value. A parameter can also be un-fixed by passing None as the value. Note that setting the fixed value bypasses range checks, meaning that whatever min/max limits have been set are completely ignored. Currently, expressions are allowed for numeric parameters as long as they do not reference other parameters. (InPUT4j supports neither) Boolean parameters do not evaluate expressions. When set to a string value, only 'true' (ignoring case) is True. Any other string is interpreted as False. """ if type(value) is str: if self.type == 'boolean': self.fixed = value.lower() == 'true' return self.fixed = Evaluator.evaluate(value) else: self.fixed = value def getFixedValue(self): """ Return the value this parameter was fixed to, if any. """ return self.fixed def isDependent(self): """ Return whether this parameter depends on any others. """ return self.isMinDependent() or self.isMaxDependent() def isMinDependent(self): """ Return whether this parameter depends on any others for defining its minimum value. """ return len(self.minDependees) > 0 def isMaxDependent(self): """ Return whether this parameter depends on any others for defining its maximum value. """ return len(self.maxDependees) > 0 def getType(self): """ Return a string containing the type this parameter was defined with. For example, for an integer parameter (defined with type='integer') the return value will be 'integer'. """ return self.type def getMin(self): """ Return a sequence of values and/or expressions that define the lower limits. For any limit that depends on other parameters, the value will be an expression. Otherwise it will be a concrete value. The sequence is guaranteed to always contain at least one item. If the parameter does not define any lower limits at all, then the one and only item will be None. The sequence of min and max limits are guaranteed to be the same length. In other words, min and max are always paired up. """ return self.min def getMax(self): """ Return a sequence of values and/or expressions that define the upper limits. For any limit that depends on other parameters, the value will be an expression. Otherwise it will be a concrete value. The sequence is guaranteed to always contain at least one item. If the parameter does not define any upper limits at all, then the one and only item will be None. The sequence of min and max limits are guaranteed to be the same length. In other words, min and max are always paired up. """ return self.max def isMinExclusive(self): """ Return whether the lower limit is exclusive. """ return self.exclMin def isMaxExclusive(self): """ Return whether the upper limit is exclusive. """ return self.exclMax def getDependees(self): """ Return a tuple containing the IDs of any parameters that this parameter depends on. """ return tuple(self.minDependees + self.maxDependees) def __eq__(self, other): if self.getId() != other.getId(): return False if self.getType() != other.getType(): return False if self.min != other.min: return False if self.max != other.max: return False if self.minDependees != other.minDependees: return False if self.maxDependees != other.maxDependees: return False return True # Factory. def getParameter(id, type, **kwargs): # This is not an array parameter. if type.find('[') == -1: return Param(id, type, **kwargs) # 'integer[2][3]' should become size: 2, paramType: 'integer[3]' startIndex = type.index('[') endIndex = type.index(']') size = int(type[startIndex+1:endIndex] or 0) type = type[:startIndex] + type[endIndex+1:] return ParamArray(id, type, size, **kwargs) class ParamArray(): """ This is a special kind of parameter. It is a kind of wrapper that adds the quality of being an array to any parameter. Multidimensional arrays are handled by wrapping multiple parameters recursively. Almost all method calls end up at the actual parameter. This class only adds two new methods: - getSize - getParameter And overrides one method: - getType """ def __init__(self, paramId, paramType, size, **kwargs): self.__param = getParameter(paramId, paramType, **kwargs) self.__size = size assert self.__param is not None def __getattr__(self, attr): return getattr(self.__param, attr) def getType(self): """ Always returns 'array'. """ return 'array' def getSize(self): """ Return the size of this array. A size of 0 means that the size is unspecified. """ return self.__size def getParameter(self): """ Return the parameter that this array should have elements of. """ return self.__param def __eq__(self, other): if self.getSize() != other.getSize(): return False return self.getParameter() == other.getParameter() class ParamStore: def __init__(self, params=None): """ The params argument is optional. It can be a single parameter or a sequence of multiple parameters. Parameters can be added until the ParamStore is finalized. """ self.__params = {} # ID-to-Param mapping. self.__dep = {} # ID-to-IDs mapping. self.__finalized = False if params is not None: self.addParam(params) # Assumes that params is a sequence of parameters. If it turns out to be # a single parameter it is placed in a sequence before processing. def addParam(self, param): """ Add one or more parameters to this ParamStore. The params argument can be a sequence of parameters or just a single parameter. Raises NotImplementedError if this ParamStore has been finalized. """ if self.__finalized: msg = 'Cannot add parameters to store once finalized.' raise NotImplementedError(msg) try: for p in param: self.addParam(p) except TypeError: paramId = param.getId() self.__params[paramId] = param # Update dependencies as new parameters are added. self.__dep[paramId] = param.getDependees() def getParam(self, paramId): """ Returns the parameter with the given ID. """ return self.__params[paramId] def setFixed(self, paramId, value): self.__params[paramId].setFixed(value) def finalize(self): """ Do any final processing and make the parameter store effectively read-only. No more parameters can be added later. Multiple calls will have no effect. Raises ValueError if: - There are unmet dependencies. (A referenced parameter is missing.) - There are circular dependencies. - Any independent parameters have invalid ranges. """ if self.__finalized: return # The order of these two calls (__validateParamters and initOrder) # is significant. self.__validateParameters() self.initOrder = initOrder(self.__dep) self.__finalized = True def getInitializationOrder(self): """ Return a dictionary that maps the initialization order to the matching parameter IDs. Example: A return value of {0: ['A', 'B'], 1: ['C']} means that A and B must be initialized before C (because C depends on one or more of (A,B)). The method requires that this parameter store is finalized. Calling this method will force finalization if not already done. """ if not self.__finalized: self.finalize() return self.initOrder def getParameters(self): """ Return a dictionary mapping parameter IDs to Param objects. """ return self.__params def getSupportedParamIds(self): """ Return the parameter IDs for all parameters stored here. """ return self.__params.keys() def __validateParameters(self): """ Check that all parameters are valid. - All independent ranges are valid. - All dependencies can be met (referenced parameters exist). """ # Check ranges. for (paramId, param) in self.__params.items(): if not self.__validRange(param): raise ValueError('Empty value range') # Check for unmet dependencies. for (paramId, param) in self.__params.items(): if not param.isDependent(): continue d = self.__missingDep(param) if d: msg = '%s referencing nonexistent parameter %s' % (paramId, d) raise ValueError(msg) # This test isn't as thorough as it could be. It only checks completely # independent parameters. def __validRange(self, param): if param.isDependent(): return True # Don't know that it's invalid at least. return generator.isValid(param) def __missingDep(self, param): """ Return any unmet dependency. That is, any referenced parameter that doesn't exist. """ dependees = param.getDependees() for d in dependees: if not d in self.__params: return d return False class DesignSpace(Identifiable): """ The design space contains a set of parameters and is capable of generating designs by initializing these parameters. A design space is mostly immutable(*): - No parameters can be added to an existing design space. - Parameters cannot be removed from the design space. - Parameters cannot be modified(*). - No internal state exists, apart from the set of parameters. This means that, initializing parameters (whether single parameters, using next(), or the full set, using nextDesign()), does not have side effects. * Parameters can be set to a fixed value though. That's the only mutability exception. """ def __init__(self, paramStore, spaceId=None): Identifiable.__init__(self, spaceId) self.params = paramStore or ParamStore() self.params.finalize() def getSupportedParamIds(self): return self.params.getSupportedParamIds() def next(self, paramId): """ Return a freshly generated value for the parameter ID. Any referenced parameters will be initialized as well, and nothing will be cached. However, each parameter is guaranteed to only be initialized once for each call to next. This method isn't used while generating a design. It exists mostly for API compatibility with InPUT4j. """ return self.__initParam(paramId, {})[paramId] def nextDesign(self, designId=None): """ Return a new design with freshly initialized parameters. """ params = {} initOrder = self.params.getInitializationOrder() # Initialize all the top-level parameters. Their dependencies will # be resolved recursively by __initParam. top = sorted(initOrder.keys())[-1] top = initOrder[top] for paramId in top: params = self.__initParam(paramId, params) return Design(params, designId) def __initParam(self, paramId, init): """ Return a dictionary mapping parameter ID to initialized value for the specified parameter and any parameters it depends on. The init argument is a dictionary containing a subset of the result. """ if paramId in init: return init param = self.params.getParam(paramId) if param.isDependent(): for d in param.getDependees(): init = self.__initParam(d, init) init[paramId] = generator.nextValue(param, init) return init def setFixed(self, paramId, value): """ Set the parameter to a fixed value. The value may be any expression that does not reference other parameters. """ self.params.setFixed(paramId, value) class Design(Identifiable): def __init__(self, params, designId=None): Identifiable.__init__(self, designId) self.params = params def getValue(self, paramId): return util.getValue(paramId, self.params) def setValue(self, paramId, value): util.setValue(paramId, self.params, value) Started merging the old and new DesignSpace """ inputpy.param This module exports two classes: - Param - ParamStore The Design and DesignSpace classes will probably be moved (probably merged with the existing classes in inputpy.design). :copyright: (c) 2013 by Christoffer Fink. :license: MIT. See LICENSE for details. """ from inputpy.util import Evaluator from inputpy.util import initOrder import inputpy.generators as generator import inputpy.util as util class Identifiable: """ This class is a mixin. It provides all subclasses with a getId() method. An instance can be initialized using an id argument. If none is provided, then a unique id will be constructed automatically. """ def __init__(self, objId=None): self.__id = objId or str(id(self)) def getId(self): return self.__id class Param(Identifiable): """ The parameter class is pretty dumb. It represents the definition of a parameter as opposed to an actual parameter. This means that it knows only the information that was used to define it. It will never have a value (with the exception of fixed values), and does not know how to generate appropriate values or even which ones would be valid. """ def __init__(self, paramId, paramType, fixed=None, inclMin=None, exclMin=None, inclMax=None, exclMax=None): # Check arguments. if paramType is None: raise ValueError('The parameter type was None') if inclMin is not None and exclMin is not None: raise ValueError('Defined both inclusive and exclusive limits') if inclMax is not None and exclMax is not None: raise ValueError('Defined both inclusive and exclusive limits') if inclMin is None: minTmp = exclMin else: minTmp = inclMin if inclMax is None: maxTmp = exclMax else: maxTmp = inclMax minTmp = self.__transformLimit(minTmp) maxTmp = self.__transformLimit(maxTmp) # Are max/min exclusive? minIsExcl = exclMin is not None maxIsExcl = exclMax is not None # Initialize fields. Identifiable.__init__(self, paramId) self.type = paramType self.exclMin = minIsExcl self.exclMax = maxIsExcl self.minDependees = [] # Referenced parameters in min expression. self.maxDependees = [] # Referenced parameters in max expression. self.min = [] self.max = [] for minLimit in minTmp: self.__initMinMax(self.min, self.minDependees, minLimit) for maxLimit in maxTmp: self.__initMinMax(self.max, self.maxDependees, maxLimit) self.__padLimits(self.min, self.max) self.min = tuple(self.min) self.max = tuple(self.max) self.minDependees = tuple(self.minDependees) self.maxDependees = tuple(self.maxDependees) # Set fixed value, if any. self.setFixed(fixed) @staticmethod def __padLimits(minLimits, maxLimits): minLen = len(minLimits) maxLen = len(maxLimits) if minLen < maxLen: limits = minLimits else: limits = maxLimits for i in range(abs(minLen - maxLen)): limits.append(None) # Is this the best way to check whether limit is already a sequence? @staticmethod def __transformLimit(limit): if limit is None: return (None,) # A string is also a sequence, but it always represents a single limit. if isinstance(limit, str): return (limit,) try: iter(limit) except TypeError: return (limit,) else: return limit @staticmethod def __initMinMax(limits, dependees, limit): # If min/max are expressions, these will be parsed to find # dependencies. If the expression does not contain references to any # other parameters, then the expression is evaluated immediately. # Any dependencies are recorded. if type(limit) is str: dependees.extend(Evaluator.parseDependencies(limit)) if len(dependees) == 0: limit = Evaluator.evaluate(limit) limits.append(limit) def isFixed(self): """ Return whether this parameter has been set to a fixed value. """ return self.fixed is not None def setFixed(self, value): """ Sets this parameter to a fixed value. A parameter can also be un-fixed by passing None as the value. Note that setting the fixed value bypasses range checks, meaning that whatever min/max limits have been set are completely ignored. Currently, expressions are allowed for numeric parameters as long as they do not reference other parameters. (InPUT4j supports neither) Boolean parameters do not evaluate expressions. When set to a string value, only 'true' (ignoring case) is True. Any other string is interpreted as False. """ if type(value) is str: if self.type == 'boolean': self.fixed = value.lower() == 'true' return self.fixed = Evaluator.evaluate(value) else: self.fixed = value def getFixedValue(self): """ Return the value this parameter was fixed to, if any. """ return self.fixed def isDependent(self): """ Return whether this parameter depends on any others. """ return self.isMinDependent() or self.isMaxDependent() def isMinDependent(self): """ Return whether this parameter depends on any others for defining its minimum value. """ return len(self.minDependees) > 0 def isMaxDependent(self): """ Return whether this parameter depends on any others for defining its maximum value. """ return len(self.maxDependees) > 0 def getType(self): """ Return a string containing the type this parameter was defined with. For example, for an integer parameter (defined with type='integer') the return value will be 'integer'. """ return self.type def getMin(self): """ Return a sequence of values and/or expressions that define the lower limits. For any limit that depends on other parameters, the value will be an expression. Otherwise it will be a concrete value. The sequence is guaranteed to always contain at least one item. If the parameter does not define any lower limits at all, then the one and only item will be None. The sequence of min and max limits are guaranteed to be the same length. In other words, min and max are always paired up. """ return self.min def getMax(self): """ Return a sequence of values and/or expressions that define the upper limits. For any limit that depends on other parameters, the value will be an expression. Otherwise it will be a concrete value. The sequence is guaranteed to always contain at least one item. If the parameter does not define any upper limits at all, then the one and only item will be None. The sequence of min and max limits are guaranteed to be the same length. In other words, min and max are always paired up. """ return self.max def isMinExclusive(self): """ Return whether the lower limit is exclusive. """ return self.exclMin def isMaxExclusive(self): """ Return whether the upper limit is exclusive. """ return self.exclMax def getDependees(self): """ Return a tuple containing the IDs of any parameters that this parameter depends on. """ return tuple(self.minDependees + self.maxDependees) def __eq__(self, other): if self.getId() != other.getId(): return False if self.getType() != other.getType(): return False if self.min != other.min: return False if self.max != other.max: return False if self.minDependees != other.minDependees: return False if self.maxDependees != other.maxDependees: return False return True # Factory. def getParameter(id, type, **kwargs): # This is not an array parameter. if type.find('[') == -1: return Param(id, type, **kwargs) # 'integer[2][3]' should become size: 2, paramType: 'integer[3]' startIndex = type.index('[') endIndex = type.index(']') size = int(type[startIndex+1:endIndex] or 0) type = type[:startIndex] + type[endIndex+1:] return ParamArray(id, type, size, **kwargs) class ParamArray(): """ This is a special kind of parameter. It is a kind of wrapper that adds the quality of being an array to any parameter. Multidimensional arrays are handled by wrapping multiple parameters recursively. Almost all method calls end up at the actual parameter. This class only adds two new methods: - getSize - getParameter And overrides one method: - getType """ def __init__(self, paramId, paramType, size, **kwargs): self.__param = getParameter(paramId, paramType, **kwargs) self.__size = size assert self.__param is not None def __getattr__(self, attr): return getattr(self.__param, attr) def getType(self): """ Always returns 'array'. """ return 'array' def getSize(self): """ Return the size of this array. A size of 0 means that the size is unspecified. """ return self.__size def getParameter(self): """ Return the parameter that this array should have elements of. """ return self.__param def __eq__(self, other): if self.getSize() != other.getSize(): return False return self.getParameter() == other.getParameter() class ParamStore: def __init__(self, params=None): """ The params argument is optional. It can be a single parameter or a sequence of multiple parameters. Parameters can be added until the ParamStore is finalized. """ self.__params = {} # ID-to-Param mapping. self.__dep = {} # ID-to-IDs mapping. self.__finalized = False if params is not None: self.addParam(params) # Assumes that params is a sequence of parameters. If it turns out to be # a single parameter it is placed in a sequence before processing. def addParam(self, param): """ Add one or more parameters to this ParamStore. The params argument can be a sequence of parameters or just a single parameter. Raises NotImplementedError if this ParamStore has been finalized. """ if self.__finalized: msg = 'Cannot add parameters to store once finalized.' raise NotImplementedError(msg) try: for p in param: self.addParam(p) except TypeError: paramId = param.getId() self.__params[paramId] = param # Update dependencies as new parameters are added. self.__dep[paramId] = param.getDependees() def getParam(self, paramId): """ Returns the parameter with the given ID. """ return self.__params[paramId] def setFixed(self, paramId, value): self.__params[paramId].setFixed(value) def finalize(self): """ Do any final processing and make the parameter store effectively read-only. No more parameters can be added later. Multiple calls will have no effect. Raises ValueError if: - There are unmet dependencies. (A referenced parameter is missing.) - There are circular dependencies. - Any independent parameters have invalid ranges. """ if self.__finalized: return # The order of these two calls (__validateParamters and initOrder) # is significant. self.__validateParameters() self.initOrder = initOrder(self.__dep) self.__finalized = True def getInitializationOrder(self): """ Return a dictionary that maps the initialization order to the matching parameter IDs. Example: A return value of {0: ['A', 'B'], 1: ['C']} means that A and B must be initialized before C (because C depends on one or more of (A,B)). The method requires that this parameter store is finalized. Calling this method will force finalization if not already done. """ if not self.__finalized: self.finalize() return self.initOrder def getParameters(self): """ Return a dictionary mapping parameter IDs to Param objects. """ return self.__params def getSupportedParamIds(self): """ Return the parameter IDs for all parameters stored here. """ return self.__params.keys() def __validateParameters(self): """ Check that all parameters are valid. - All independent ranges are valid. - All dependencies can be met (referenced parameters exist). """ # Check ranges. for (paramId, param) in self.__params.items(): if not self.__validRange(param): raise ValueError('Empty value range') # Check for unmet dependencies. for (paramId, param) in self.__params.items(): if not param.isDependent(): continue d = self.__missingDep(param) if d: msg = '%s referencing nonexistent parameter %s' % (paramId, d) raise ValueError(msg) # This test isn't as thorough as it could be. It only checks completely # independent parameters. def __validRange(self, param): if param.isDependent(): return True # Don't know that it's invalid at least. return generator.isValid(param) def __missingDep(self, param): """ Return any unmet dependency. That is, any referenced parameter that doesn't exist. """ dependees = param.getDependees() for d in dependees: if not d in self.__params: return d return False class DesignSpace(Identifiable): """ The design space contains a set of parameters and is capable of generating designs by initializing these parameters. A design space is mostly immutable(*): - No parameters can be added to an existing design space. - Parameters cannot be removed from the design space. - Parameters cannot be modified(*). - No internal state exists, apart from the set of parameters. This means that, initializing parameters (whether single parameters, using next(), or the full set, using nextDesign()), does not have side effects. * Parameters can be set to a fixed value though. That's the only mutability exception. """ # fileName is currently ignored. def __init__(self, paramStore, spaceId=None, fileName=None): """ An instance is always created using a ParamStore. A file name (if specified) only indicates which file the DesignSpace is based on. It will not be processed in any way. To import a DesignSpace from a file, use the getDesignSpace function. """ Identifiable.__init__(self, spaceId) self.params = paramStore or ParamStore() self.params.finalize() def getSupportedParamIds(self): return self.params.getSupportedParamIds() # All three keyword arguments are currently ignored. def next(self, paramId, dimensions=None, subParams=None, actualParams=None): """ Return a freshly generated value for the parameter ID. Any referenced parameters will be initialized as well, and nothing will be cached. However, each parameter is guaranteed to only be initialized once for each call to next. This method isn't used while generating a design. It exists mostly for API compatibility with InPUT4j. """ return self.__initParam(paramId, {})[paramId] # readOnly is currently ignored. def nextDesign(self, designId=None, readOnly=False): """ Return a new design with freshly initialized parameters. """ params = {} initOrder = self.params.getInitializationOrder() # Initialize all the top-level parameters. Their dependencies will # be resolved recursively by __initParam. top = sorted(initOrder.keys())[-1] top = initOrder[top] for paramId in top: params = self.__initParam(paramId, params) return Design(params, designId) def __initParam(self, paramId, init): """ Return a dictionary mapping parameter ID to initialized value for the specified parameter and any parameters it depends on. The init argument is a dictionary containing a subset of the result. """ if paramId in init: return init param = self.params.getParam(paramId) if param.isDependent(): for d in param.getDependees(): init = self.__initParam(d, init) init[paramId] = generator.nextValue(param, init) return init def setFixed(self, paramId, value): """ Set the parameter to a fixed value. The value may be any expression that does not reference other parameters. """ self.params.setFixed(paramId, value) # ------------------------------------------------------------------------- # These are dummy implementations, taken from the first version of # DesignSpace. # ------------------------------------------------------------------------- def impOrt(self, importer): return Design({}) def isFile(self): return self.fileName is not None def getFileName(self): return self.fileName def nextEmptyDesign(self, designId): return Design({}, designId) # ------------------------------------------------------------------------- class Design(Identifiable): def __init__(self, params, designId=None): Identifiable.__init__(self, designId) self.params = params def getValue(self, paramId): return util.getValue(paramId, self.params) def setValue(self, paramId, value): util.setValue(paramId, self.params, value)
# Copyright (c) 2018 Fortinet, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # FortiAuthenticator API request format templates. # About api request message naming regulations: # Prefix HTTP method # ADD_XXX --> POST # SET_XXX --> PUT # DELETE_XXX --> DELETE # GET_XXX --> GET # MODIFY_XXX --> PATCH # Version GET_VERSION = """ { {% if sn is defined %} "path": "/version?sn={{ sn }}", {% else %} "path": "/version/", {% endif %} "method": "GET" } """ # Namespace # query GET_REALM = """ { {% if id is defined %} {% if sn is defined %} "path": "/api/v1/realm/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/realm/{{ id }}/, {% endif %} {% else %} {% set _options = { "sn": sn, "is_default": is_default, "name": name, "customer_id": customer_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/realm?{{ _query }}", {% else %} "path": "/api/v1/realm/", {% endif %} {% endif %} "method": "GET" } """ # add ADD_REALM = """ { "path": "/api/v1/realm", "method": "POST", "body": { {% if description is defined %} "description": "{{ description }}", {% endif %} {% if sn is defined %} "sn": "{{ sn }}", {% endif %} "name": "{{ name }}" } } """ # delete DELETE_REALM = """ { {% if sn is defined %} "path": "/api/v1/realm/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/realm/{{ id }}/, {% endif %} "method": "DELETE" } """ # authenticated api client # query GET_CLIENT = """ { {% if id is defined %} {% if sn is defined %} "path": "/api/v1/client/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/client/{{ id }}/, {% endif %} {% else %} {% set _options = { "sn": sn, "vdom": vdom, "realm_id": realm_id, "customer_id": customer_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/client?{{ _query }}", {% else %} "path": "/api/v1/client/", {% endif %} {% endif %} "method": "GET" } """ # delete DELETE_CLIENT = """ { {% if sn is defined %} "path": "/api/v1/client/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/client/{{ id }}/, {% endif %} "method": "DELETE" } """ # User # query GET_USER = """ { {% if id is defined %} {% if sn is defined %} "path": "/api/v1/user/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/user/{{ id }}/, {% endif %} {% else %} {% set _options = { "sn": sn, "username": username, "email": email, "mobile_number": mobile_number, "realm_id": realm_id, "realm": realm, "vdom": vdom, "active": active, "customer_id": customer_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/user?{{ _query }}", {% else %} "path": "/api/v1/user/", {% endif %} {% endif %} "method": "GET" } """ # add ADD_USER = """ { "path": "/api/v1/user/", "method": "POST", "body": { "sn": "{{ sn }}", "vdom": "{{ vdom }}", "email": "{{ email }}", {% if realm_id is defined %} "realm_id": "{{ realm_id }}", {% elif realm is defined %} "realm": "{{ realm }}", {% endif %} {% if mobile_number is defined %} "mobile_number": "{{ mobile_number }}", {% endif %} {% if cluster_members is defined %} "cluster_members": [ {% for member in cluster_members %} "{{ member }}"{{ "," if not loop.last }} {% endfor %} ], {% endif %} "username": "{{ username }}" } } """ # delete DELETE_USER = """ { {% if sn is defined %} "path": "/api/v1/user/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/user/{{ id }}/, {% endif %} "method": "DELETE" } """ # put MODIFY_USER = """ { "path": "/api/v1/user/{{ id }}/", "method": "PUT", "body": { {% set _options = { "sn": sn, "email": email, "mobile_number": mobile_number, "active": active, "change_token": change_token } %} {% for k, v in _options.iteritems() if v is defined %} "{{ k }}": "{{ v }}", {% endfor %} "id": "{{ id }}" } } """ # count GET_COUNT = """ { {% set _options = { "sn": sn, "resource": resource, "realm_id": realm_id, "active": active, "customer_id": customer_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/count?{{ _query }}", {% else %} "path": "/api/v1/count/", {% endif %} "method": "GET" } """ # authentication ADD_AUTH = """ { "path": "/api/v1/auth/", "method": "POST", "body": { {% if token is defined %} "token": "{{ token }}", {% endif %} "sn": "{{ sn }}", "realm_id": "{{ realm_id }}", "username": "{{ username }}" } } """ # statement GET_STATEMENT = """ { {% set _options = { "sn": sn, "start": start, "end": end, "realm_id": realm_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/statement?{{ _query }}", {% else %} "path": "/api/v1/statement/", {% endif %} "method": "GET" } """ # token activation ADD_TOKEN_ACTIVATION = """ { "path": "/api/v1/token/activation", "method": "POST", "body": { {% if token is defined %} "token": "{{ token }}", {% endif %} } } """ TOKEN_TRANSFER_START = """ { "path": "/api/v1/token/transfer/start", "method": "POST", "body": { "sn": "{{ sn }}", "tokens": "{{ tokens }}", "reg_id": "{{ reg_id }}", "hmac": "{{ hmac }}", "transfer_code": "{{ transfer_code }}", "msg_sn": "FortiToken Cloud" } } """ update get_user template # Copyright (c) 2018 Fortinet, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # FortiAuthenticator API request format templates. # About api request message naming regulations: # Prefix HTTP method # ADD_XXX --> POST # SET_XXX --> PUT # DELETE_XXX --> DELETE # GET_XXX --> GET # MODIFY_XXX --> PATCH # Version GET_VERSION = """ { {% if sn is defined %} "path": "/version?sn={{ sn }}", {% else %} "path": "/version/", {% endif %} "method": "GET" } """ # Namespace # query GET_REALM = """ { {% if id is defined %} {% if sn is defined %} "path": "/api/v1/realm/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/realm/{{ id }}/, {% endif %} {% else %} {% set _options = { "sn": sn, "is_default": is_default, "name": name, "customer_id": customer_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/realm?{{ _query }}", {% else %} "path": "/api/v1/realm/", {% endif %} {% endif %} "method": "GET" } """ # add ADD_REALM = """ { "path": "/api/v1/realm", "method": "POST", "body": { {% if description is defined %} "description": "{{ description }}", {% endif %} {% if sn is defined %} "sn": "{{ sn }}", {% endif %} "name": "{{ name }}" } } """ # delete DELETE_REALM = """ { {% if sn is defined %} "path": "/api/v1/realm/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/realm/{{ id }}/, {% endif %} "method": "DELETE" } """ # authenticated api client # query GET_CLIENT = """ { {% if id is defined %} {% if sn is defined %} "path": "/api/v1/client/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/client/{{ id }}/, {% endif %} {% else %} {% set _options = { "sn": sn, "vdom": vdom, "realm_id": realm_id, "customer_id": customer_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/client?{{ _query }}", {% else %} "path": "/api/v1/client/", {% endif %} {% endif %} "method": "GET" } """ # delete DELETE_CLIENT = """ { {% if sn is defined %} "path": "/api/v1/client/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/client/{{ id }}/, {% endif %} "method": "DELETE" } """ # User # query GET_USER = """ { {% if id is defined %} {% if sn is defined %} "path": "/api/v1/user/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/user/{{ id }}/, {% endif %} {% else %} {% set _options = { "sn": sn, "username": username, "email": email, "mobile_number": mobile_number, "realm_id": realm_id, "realm": realm, "vdom": vdom, "active": active, "customer_id": customer_id } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if cluster_members is defined %} {% for member in cluster_members %} _query.append('cluster_members[]=' + member) {% endfor %} {% endif %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/user?{{ _query }}", {% else %} "path": "/api/v1/user/", {% endif %} {% endif %} "method": "GET" } """ # add ADD_USER = """ { "path": "/api/v1/user/", "method": "POST", "body": { "sn": "{{ sn }}", "vdom": "{{ vdom }}", "email": "{{ email }}", {% if realm_id is defined %} "realm_id": "{{ realm_id }}", {% elif realm is defined %} "realm": "{{ realm }}", {% endif %} {% if mobile_number is defined %} "mobile_number": "{{ mobile_number }}", {% endif %} {% if cluster_members is defined %} "cluster_members": [ {% for member in cluster_members %} "{{ member }}"{{ "," if not loop.last }} {% endfor %} ], {% endif %} "username": "{{ username }}" } } """ # delete DELETE_USER = """ { {% if sn is defined %} "path": "/api/v1/user/{{ id }}?sn={{ sn }}", {% else %} "path": "/api/v1/user/{{ id }}/, {% endif %} "method": "DELETE" } """ # put MODIFY_USER = """ { "path": "/api/v1/user/{{ id }}/", "method": "PUT", "body": { {% set _options = { "sn": sn, "email": email, "mobile_number": mobile_number, "active": active, "change_token": change_token } %} {% for k, v in _options.iteritems() if v is defined %} "{{ k }}": "{{ v }}", {% endfor %} "id": "{{ id }}" } } """ # count GET_COUNT = """ { {% set _options = { "sn": sn, "resource": resource, "realm_id": realm_id, "active": active, "customer_id": customer_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/count?{{ _query }}", {% else %} "path": "/api/v1/count/", {% endif %} "method": "GET" } """ # authentication ADD_AUTH = """ { "path": "/api/v1/auth/", "method": "POST", "body": { {% if token is defined %} "token": "{{ token }}", {% endif %} "sn": "{{ sn }}", "realm_id": "{{ realm_id }}", "username": "{{ username }}" } } """ # statement GET_STATEMENT = """ { {% set _options = { "sn": sn, "start": start, "end": end, "realm_id": realm_id, "cluster_members": cluster_members } %} {% set _query = [] %} {% for k, v in _options.iteritems() if v is defined %} {% if _query.append(k+'='+v) %} {% endif %} {% endfor %} {% if _query %} {% set _query = '&'.join(_query) %} "path": "/api/v1/statement?{{ _query }}", {% else %} "path": "/api/v1/statement/", {% endif %} "method": "GET" } """ # token activation ADD_TOKEN_ACTIVATION = """ { "path": "/api/v1/token/activation", "method": "POST", "body": { {% if token is defined %} "token": "{{ token }}", {% endif %} } } """ TOKEN_TRANSFER_START = """ { "path": "/api/v1/token/transfer/start", "method": "POST", "body": { "sn": "{{ sn }}", "tokens": "{{ tokens }}", "reg_id": "{{ reg_id }}", "hmac": "{{ hmac }}", "transfer_code": "{{ transfer_code }}", "msg_sn": "FortiToken Cloud" } } """
# -*- coding: utf-8 -*- # https://man.recast.ai/ from api import ApiManager import requests class RecastManager(ApiManager): def __init__(self, user_slug, bot_slug, token, language, fallback_name, strictness=50): ApiManager.__init__(self, fallback_name) self._base_url = 'https://api.recast.ai/v1' self._user_slug = user_slug self._bot_slug = bot_slug self.strictness = strictness self._url = '{0}/users/{1}/bots/{2}'.format(self._base_url, user_slug, bot_slug) self._token = token self._headers = { 'Authorization': 'Token {}'.format(self._token) } self._language = language self._update_bot() def __repr__(self): return 'recast' def predict(self, sentences): predictions = [] for sentence in sentences: predictions.append(self._predict_one(sentence)) return predictions def fit(self, df_train): self._clear() X_train = df_train['sentence'] y_train = df_train['intent'] intents = set(y_train) for intent in intents: utterances = list(X_train[y_train == intent]) self._create_intent(intent, utterances, self._language) @classmethod def get_parametors(cls): return ['strictness'] def _update_bot(self): response = requests.put( url='{}'.format(self._url), json={ 'name': self._bot_slug, 'strictness': self.strictness }, headers=self._headers ) return response def _create_intent(self, name, expressions, language, description='', n_try=0): array = [] for expression in expressions: array.append( { 'source': expression, 'language': {'isocode': language} } ) response = requests.post( url='{}/intents'.format(self._url), json={ 'name': name, 'description': description, 'expressions': array }, headers=self._headers ) try: return response.json() except: if n_try < 3: return self._create_intent(name, expressions, language, '', n_try=n_try + 1) raise Exception('no json could be decoded') def _clear(self): intent_slugs = self._get_intents_slug() for slug in intent_slugs: self._delete_intent_by_slug(slug) def _delete_intent_by_slug(self, intent_slug): response = requests.delete( url='{}/intents/{}'.format(self._url, intent_slug), headers=self._headers ) return response.json() def _get_intents_slug(self): response = requests.get( url='{}/intents'.format(self._url), # url = 'https://api.recast.ai/v1/users/pytha/bots/test/intents', headers=self._headers ) response = response.json() intents = response['results'] intent_slugs = [] for intent in intents: intent_slugs.append(intent['slug']) return intent_slugs def _predict_one(self, sentence): response = requests.post( url='{}/request'.format(self._base_url), data={ 'text': sentence, 'language': self._language }, headers=self._headers ) response = response.json() if len(response['results']['intents']) > 0: return response['results']['intents'][0] return self._fallback_name fix(recast): use API v2 # -*- coding: utf-8 -*- # https://man.recast.ai/ from api import ApiManager import requests class RecastManager(ApiManager): def __init__(self, user_slug, bot_slug, token, language, fallback_name, strictness=50): ApiManager.__init__(self, fallback_name) self._base_url = 'https://api.recast.ai/v2' self._user_slug = user_slug self._bot_slug = bot_slug self.strictness = strictness self._url = '{0}/users/{1}/bots/{2}'.format(self._base_url, user_slug, bot_slug) self._token = token self._headers = { 'Authorization': 'Token {}'.format(self._token) } self._language = language self._update_bot() def __repr__(self): return 'recast' def predict(self, sentences): predictions = [] for sentence in sentences: predictions.append(self._predict_one(sentence)) return predictions def fit(self, df_train): self._clear() X_train = df_train['sentence'] y_train = df_train['intent'] intents = set(y_train) for intent in intents: utterances = list(X_train[y_train == intent]) self._create_intent(intent, utterances, self._language) @classmethod def get_parametors(cls): return ['strictness'] def _update_bot(self): response = requests.put( url='{}'.format(self._url), json={ 'name': self._bot_slug, 'strictness': self.strictness }, headers=self._headers ) return response def _create_intent(self, name, expressions, language, description='', n_try=0): array = [] for expression in expressions: array.append( { 'source': expression, 'language': {'isocode': language} } ) response = requests.post( url='{}/intents'.format(self._url), json={ 'name': name, 'description': description, 'expressions': array }, headers=self._headers ) try: return response.json() except: if n_try < 3: return self._create_intent(name, expressions, language, '', n_try=n_try + 1) raise Exception('no json could be decoded') def _clear(self): intent_slugs = self._get_intents_slug() for slug in intent_slugs: self._delete_intent_by_slug(slug) def _delete_intent_by_slug(self, intent_slug): response = requests.delete( url='{}/intents/{}'.format(self._url, intent_slug), headers=self._headers ) return response.json() def _get_intents_slug(self): response = requests.get( url='{}/intents'.format(self._url), # url = 'https://api.recast.ai/v1/users/pytha/bots/test/intents', headers=self._headers ) response = response.json() intents = response['results'] intent_slugs = [] for intent in intents: intent_slugs.append(intent['slug']) return intent_slugs def _predict_one(self, sentence): response = requests.post( url='{}/request'.format(self._base_url), data={ 'text': sentence, 'language': self._language }, headers=self._headers ) response = response.json() if len(response['results']['intents']) > 0: return response['results']['intents'][0]['slug'] return self._fallback_name
""" ================================= Handwritten digits decompositions ================================= This example compares different unsupervised matrix decomposition (dimension reduction) methods on the digits dataset. """ print __doc__ # Authors: Vlad Niculae, Alexandre Gramfort # License: BSD from time import time import numpy as np import pylab as pl from scikits.learn.decomposition import RandomizedPCA, NMF, SparsePCA, FastICA from scikits.learn.cluster import KMeans from scikits.learn.datasets import load_digits n_row, n_col = 4, 4 n_components = n_row * n_col ############################################################################### # Load digits data digits = load_digits() threes = digits.data[digits.target == 3] threes_centered = threes - threes.mean(axis=0) print "Dataset consists of %d images" % len(threes) ###################################################################### # Compute a PCA (eigendigits) on the digit dataset print "Extracting the top %d eigendigits..." % n_components, t0 = time() pca = RandomizedPCA(n_components=n_components, whiten=True) pca.fit(threes_centered) print "done in %0.3fs" % (time() - t0) eigendigits = pca.components_ ###################################################################### # Compute a NMF on the digit dataset print "Extracting %d non-negative features..." % n_components, t0 = time() nmf = NMF(n_components=n_components, init='nndsvd', beta=5, tol=1e-2, sparseness="components") nmf.fit(threes) print "done in %0.3fs" % (time() - t0) nmfdigits = nmf.components_ ###################################################################### # Compute a ICA on the digit dataset print "Extracting the top %d independent components..." % n_components, t0 = time() ica = FastICA(n_components=n_components, whiten=True) ica.fit(threes_centered.T) print "done in %0.3fs" % (time() - t0) icadigits = ica.components_.T ##################################################################### # Compute Sparse PCA on the digits print "Extracting %d sparse components..." % n_components, t0 = time() spca = SparsePCA(n_components=n_components, alpha=5, tol=1e-4) spca.fit(threes_centered) print "done in %0.3fs" % (time() - t0) spcadigits = spca.components_ spcaspan = np.max(np.abs(spcadigits)) ###################################################################### # Compute a K-Means (cluster centers) on the digit dataset print "Extracting %d cluster centers..." % n_components, t0 = time() km = KMeans(k=n_components) km.fit(threes_centered) print "done in %0.3fs" % (time() - t0) kmeansdigits = km.cluster_centers_ ###################################################################### # Plot the results def plot_digit_gallery(title, images): pl.figure(figsize=(1. * n_col, 1.13 * n_row)) pl.suptitle(title, size=16) for i, comp in enumerate(images): pl.subplot(n_row, n_col, i + 1) pl.imshow(comp.reshape((8, 8)), cmap=pl.cm.gray_r, interpolation='nearest') pl.xticks(()) pl.yticks(()) pl.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.) plot_digit_gallery('Principal components', eigendigits) plot_digit_gallery('Independent components', icadigits) plot_digit_gallery('Non-negative components', nmfdigits) plot_digit_gallery('K-Means cluter centers', kmeansdigits) ############################################################################### # Plot sparse components (it's a little bit different) fig = pl.figure(figsize=(1. * n_col, 1.3 * n_row)) for i, comp in enumerate(spcadigits): pl.subplot(n_row, n_col, i + 1) pl.imshow(np.reshape(comp, (8, 8)), interpolation='nearest', vmin=-spcaspan, vmax=spcaspan, cmap=pl.cm.PuOr) pl.xticks(()) pl.yticks(()) pl.subplots_adjust(0.01, 0.15, 0.99, 0.92, 0.04, 0.) cax = fig.add_axes([0.1, 0.06, 0.8, 0.04]) pl.colorbar(cax=cax, orientation='horizontal') pl.suptitle('Sparse components', size=16) pl.show() MISC: Restructure compound decomposition example """ ================================= Handwritten digits decompositions ================================= This example compares different unsupervised matrix decomposition (dimension reduction) methods on the digits dataset. """ print __doc__ # Authors: Vlad Niculae, Alexandre Gramfort # License: BSD from time import time import pylab as pl from scikits.learn.decomposition import RandomizedPCA, NMF, SparsePCA, FastICA from scikits.learn.cluster import KMeans from scikits.learn.datasets import load_digits n_row, n_col = 4, 4 n_components = n_row * n_col ############################################################################### # Load digits data digits = load_digits() threes = digits.data[digits.target == 3] threes_centered = threes - threes.mean(axis=0) print "Dataset consists of %d images" % len(threes) ############################################################################### def plot_digit_gallery(title, images): pl.figure(figsize=(1. * n_col, 1.13 * n_row)) pl.suptitle(title, size=16) vmax = max(images.max(), -images.min()) for i, comp in enumerate(images): pl.subplot(n_row, n_col, i + 1) pl.imshow(comp.reshape((8, 8)), cmap=pl.cm.BrBG, interpolation='nearest', vmin=-vmax, vmax=vmax) pl.xticks(()) pl.yticks(()) pl.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.) ############################################################################### # Dictionary of the different estimators, and whether to center and # transpose the problem estimators = { 'eigendigits (PCA)': (RandomizedPCA(n_components=n_components, whiten=True), True, False), 'non-negative components (NMF)': (NMF(n_components=n_components, init='nndsvd', beta=5, tol=1e-2, sparseness='components'), False, False), 'independent components (ICA)': (FastICA(n_components=n_components, whiten=True), True, True), 'sparse components (SparsePCA)': (SparsePCA(n_components=n_components, alpha=5, tol=1e-4), True, False), } ############################################################################### # Do the estimation and plot it for name, (estimator, center, transpose) in estimators.iteritems(): print "Extracting the top %d %s..." % (n_components, name) t0 = time() data = threes if center: data = threes_centered if transpose: data = data.T estimator.fit(data) print "done in %0.3fs" % (time() - t0) components_ = estimator.components_ if transpose: components_ = components_.T plot_digit_gallery(name, components_) ###################################################################### # Compute a K-Means (cluster centers) on the digit dataset print "Extracting %d cluster centers..." % n_components, t0 = time() km = KMeans(k=n_components) km.fit(threes_centered) print "done in %0.3fs" % (time() - t0) kmeans_digits = km.cluster_centers_ plot_digit_gallery('K-Means cluter centers', kmeans_digits) pl.show()
import aiohttp import asyncio import json import logging from uuid import uuid4 from asyncio.base_events import BaseEventLoop logger = logging.getLogger(__name__) class KurentoTransportException(Exception): def __init__(self, message, response=None): print(message, response) super(KurentoTransportException, self).__init__(message) self.response = response if response is None: self.response = {} self.message = message def __str__(self): return "%s - %s" % (str(self.message), json.dumps(self.response)) # create_future is new in version 3.5.2 if hasattr(BaseEventLoop, 'create_future'): def create_future(loop): return loop.create_future() else: def create_future(loop): return asyncio.Future(loop=loop) def _set_result(fut, result): if fut.done(): logger.debug("Waiter future is already done %r", fut) assert fut.cancelled(), ( "waiting future is in wrong state", fut, result) else: fut.set_result(result) def _set_exception(fut, exception): if fut.done(): logger.debug("Waiter future is already done %r", fut) assert fut.cancelled(), ( "waiting future is in wrong state", fut, exception) else: fut.set_exception(exception) class KurentoTransport(object): _ws = None # _waiters = deque() _waiters = {} def __init__(self, url, loop=None): logging.debug("KURENTO Creating new Transport with url: %s" % url) self.url = url self.session = aiohttp.ClientSession() self.current_id = 0 self.session_id = None self.subscriptions = {} self.stopped = False if loop is None: loop = asyncio.get_event_loop() self._loop = loop self._reader_task = asyncio.ensure_future(self._reader(), loop=self._loop) # def __del__(self): # logger.debug("Destroying KurentoTransport with url: %s" % self.url) # self.stopped = True # self._ws.close() async def _reader(self): while not self.stopped: logging.debug("KURENTO connected %s" % self.url) try: self._ws = await self.session.ws_connect(self.url) msg = await self._ws.receive() if msg.tp == aiohttp.MsgType.text: if msg.data == 'close': await self._ws.close() break else: self._on_message(msg.data) elif msg.tp == aiohttp.MsgType.closed: break elif msg.tp == aiohttp.MsgType.error: break except aiohttp.errors.ServerDisconnectedError: logging.debug("KURENTO drop conection %s" % self.url) return None def _next_id(self): self.current_id = uuid4().hex return str(self.current_id) def _on_message(self, message): resp = json.loads(message) logger.debug("KURENTO received message: %s" % message) msg_id = str(resp.get('id')) if 'method' in resp: if resp['method'] == 'onEvent': print("SUBSCRIPTIONS", self.subscriptions) if (resp['method'] == 'onEvent' and 'params' in resp and 'value' in resp['params'] and 'type' in resp['params']['value'] and resp['params']['value']['object'] in self.subscriptions): sub_id = str(resp['params']['value']['object']) logging.warning("sub_id %s" % sub_id) fn = self.subscriptions[sub_id] self.session_id = resp['params'].get('sessionId', self.session_id) fn(resp["params"]["value"]) return None if resp['method'] == 'onEvent': print("SUB NOT FOUND!!!!11111") print(resp) elif 'error' in resp: waiter = self._waiters.get(msg_id) error = resp['error'].get('message', 'Unknown Error') _set_exception(waiter, KurentoTransportException(error, resp)) elif 'result' in resp and 'value' in resp['result']: waiter = self._waiters.get(msg_id) _set_result(waiter, resp['result']['value']) else: if 'result' in resp and 'sessionId' in resp['result']: self.session_id = resp['result']['sessionId'] def _rpc(self, rpc_type, **args): if self.session_id: args["sessionId"] = self.session_id request = { "jsonrpc": "2.0", "id": self._next_id(), "method": rpc_type, "params": args } logger.debug("KURENTO sending message: %s" % json.dumps(request)) # print(request) fut = create_future(loop=self._loop) self._ws.send_str(json.dumps(request)) self._waiters[request['id']] = fut return fut def create(self, obj_type, **args): return self._rpc("create", type=obj_type, constructorParams=args) def invoke(self, object_id, operation, **args): return self._rpc("invoke", object=object_id, operation=operation, operationParams=args) async def subscribe(self, object_id, event_type, fn): logging.debug('+-==================================================_=') subscription_id = await self._rpc("subscribe", object=object_id, type=event_type) self.subscriptions[str(object_id)] = fn return subscription_id def unsubscribe(self, subscription_id): del self.subscriptions[subscription_id] return self._rpc("unsubscribe", subscription=subscription_id) def release(self, object_id): return self._rpc("release", object=object_id) async def stop(self): logger.debug("Destroying KurentoTransport with url: %s" % self.url) self.stopped = True await self._ws.close() await self.session.close() fix kurento connect import aiohttp import asyncio import json import logging from uuid import uuid4 from asyncio.base_events import BaseEventLoop logger = logging.getLogger(__name__) class KurentoTransportException(Exception): def __init__(self, message, response=None): print(message, response) super(KurentoTransportException, self).__init__(message) self.response = response if response is None: self.response = {} self.message = message def __str__(self): return "%s - %s" % (str(self.message), json.dumps(self.response)) # create_future is new in version 3.5.2 if hasattr(BaseEventLoop, 'create_future'): def create_future(loop): return loop.create_future() else: def create_future(loop): return asyncio.Future(loop=loop) def _set_result(fut, result): if fut.done(): logger.debug("Waiter future is already done %r", fut) assert fut.cancelled(), ( "waiting future is in wrong state", fut, result) else: fut.set_result(result) def _set_exception(fut, exception): if fut.done(): logger.debug("Waiter future is already done %r", fut) assert fut.cancelled(), ( "waiting future is in wrong state", fut, exception) else: fut.set_exception(exception) class KurentoTransport(object): _ws = None # _waiters = deque() _waiters = {} def __init__(self, url, loop=None): logging.debug("KURENTO Creating new Transport with url: %s" % url) self.url = url self.session = aiohttp.ClientSession() self.current_id = 0 self.session_id = None self.subscriptions = {} self.stopped = False if loop is None: loop = asyncio.get_event_loop() self._loop = loop self._reader_task = asyncio.ensure_future(self._reader(), loop=self._loop) # def __del__(self): # logger.debug("Destroying KurentoTransport with url: %s" % self.url) # self.stopped = True # self._ws.close() async def _reader(self): logging.debug("KURENTO connected %s" % self.url) self._ws = await self.session.ws_connect(self.url) while not self.stopped: msg = await self._ws.receive() if msg.tp == aiohttp.MsgType.text: if msg.data == 'close': await self._ws.close() break else: self._on_message(msg.data) elif msg.tp == aiohttp.MsgType.closed: break elif msg.tp == aiohttp.MsgType.error: break # except aiohttp.errors.ServerDisconnectedError: # logging.debug("KURENTO drop conection %s" % self.url) # return None def _next_id(self): self.current_id = uuid4().hex return str(self.current_id) def _on_message(self, message): resp = json.loads(message) logger.debug("KURENTO received message: %s" % message) msg_id = str(resp.get('id')) if 'method' in resp: if resp['method'] == 'onEvent': print("SUBSCRIPTIONS", self.subscriptions) if (resp['method'] == 'onEvent' and 'params' in resp and 'value' in resp['params'] and 'type' in resp['params']['value'] and resp['params']['value']['object'] in self.subscriptions): sub_id = str(resp['params']['value']['object']) logging.warning("sub_id %s" % sub_id) fn = self.subscriptions[sub_id] self.session_id = resp['params'].get('sessionId', self.session_id) fn(resp["params"]["value"]) return None if resp['method'] == 'onEvent': print("SUB NOT FOUND!!!!11111") print(resp) elif 'error' in resp: waiter = self._waiters.get(msg_id) error = resp['error'].get('message', 'Unknown Error') _set_exception(waiter, KurentoTransportException(error, resp)) elif 'result' in resp and 'value' in resp['result']: waiter = self._waiters.get(msg_id) _set_result(waiter, resp['result']['value']) else: if 'result' in resp and 'sessionId' in resp['result']: self.session_id = resp['result']['sessionId'] def _rpc(self, rpc_type, **args): if self.session_id: args["sessionId"] = self.session_id request = { "jsonrpc": "2.0", "id": self._next_id(), "method": rpc_type, "params": args } logger.debug("KURENTO sending message: %s" % json.dumps(request)) # print(request) fut = create_future(loop=self._loop) self._ws.send_str(json.dumps(request)) self._waiters[request['id']] = fut return fut def create(self, obj_type, **args): return self._rpc("create", type=obj_type, constructorParams=args) def invoke(self, object_id, operation, **args): return self._rpc("invoke", object=object_id, operation=operation, operationParams=args) async def subscribe(self, object_id, event_type, fn): logging.debug('+-==================================================_=') subscription_id = await self._rpc("subscribe", object=object_id, type=event_type) self.subscriptions[str(object_id)] = fn return subscription_id def unsubscribe(self, subscription_id): del self.subscriptions[subscription_id] return self._rpc("unsubscribe", subscription=subscription_id) def release(self, object_id): return self._rpc("release", object=object_id) async def stop(self): logger.debug("Destroying KurentoTransport with url: %s" % self.url) self.stopped = True await self._ws.close() await self.session.close()
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import os_client_config import flask import jsonschema import netaddr from neutronclient.common import exceptions as n_exceptions from neutronclient.neutron import client from oslo_concurrency import processutils from oslo_config import cfg from oslo_utils import excutils from kuryr import app from kuryr import binding from kuryr.common import config from kuryr.common import constants from kuryr.common import exceptions from kuryr import schemata from kuryr import utils MANDATORY_NEUTRON_EXTENSION = "subnet_allocation" def _get_cloud_config(cloud='devstack-admin'): return os_client_config.OpenStackConfig().get_one_cloud(cloud=cloud) def _credentials(cloud='devstack-admin'): """Retrieves credentials to run functional tests Credentials are either read via os-client-config from the environment or from a config file ('clouds.yaml'). Environment variables override those from the config file. devstack produces a clouds.yaml with two named clouds - one named 'devstack' which has user privs and one named 'devstack-admin' which has admin privs. This function will default to getting the devstack-admin cloud as that is the current expected behavior. """ return _get_cloud_config(cloud=cloud).get_auth_args() def _get_neutron_client_from_creds(): creds = _credentials() username = creds['username'] tenant_name = creds['project_name'] password = creds['password'] auth_url = creds['auth_url'] + "/v2.0" neutron_client = client.Client('2.0', username=username, tenant_name=tenant_name, password=password, auth_url=auth_url) return neutron_client def get_neutron_client(): """Creates the Neutron client for communicating with Neutron.""" try: # First try to retrieve neutron client from a working OS deployment # This is used for gate testing. # Since this always use admin credentials, next patch will introduce # a config parameter that disable this for production environments neutron_client = _get_neutron_client_from_creds() return neutron_client except Exception: pass cfg.CONF.import_group('neutron_client', 'kuryr.common.config') cfg.CONF.import_group('keystone_client', 'kuryr.common.config') keystone_conf = cfg.CONF.keystone_client username = keystone_conf.admin_user tenant_name = keystone_conf.admin_tenant_name password = keystone_conf.admin_password auth_token = keystone_conf.admin_token auth_uri = keystone_conf.auth_uri.rstrip('/') neutron_uri = cfg.CONF.neutron_client.neutron_uri if username and password: # Authenticate with password crentials neutron_client = utils.get_neutron_client( url=neutron_uri, username=username, tenant_name=tenant_name, password=password, auth_url=auth_uri) else: neutron_client = utils.get_neutron_client_simple( url=neutron_uri, auth_url=auth_uri, token=auth_token) return neutron_client def neutron_client(): if not hasattr(app, 'neutron'): app.neutron = get_neutron_client() app.enable_dhcp = cfg.CONF.neutron_client.enable_dhcp app.neutron.format = 'json' def check_for_neutron_ext_support(): """Validates for mandatory extension support availability in neutron.""" try: app.neutron.show_extension(MANDATORY_NEUTRON_EXTENSION) except n_exceptions.NeutronClientException as e: if e.status_code == n_exceptions.NotFound.status_code: raise exceptions.MandatoryApiMissing( "Neutron extension with alias '{0}' not found" .format(MANDATORY_NEUTRON_EXTENSION)) # TODO(tfukushima): Retrieve the following subnet names from the config file. SUBNET_POOLS_V4 = [ p.strip() for p in os.environ.get('SUBNET_POOLS_V4', 'kuryr').split(',')] SUBNET_POOLS_V6 = [ p.strip() for p in os.environ.get('SUBNET_POOLS_V6', 'kuryr6').split(',')] def _cache_default_subnetpool_ids(app): """Caches IDs of the default subnetpools as app.DEFAULT_POOL_IDS.""" if not hasattr(app, 'DEFAULT_POOL_IDS'): default_subnetpool_id_set = set() try: subnetpool_names = SUBNET_POOLS_V4 + SUBNET_POOLS_V6 for subnetpool_name in subnetpool_names: subnetpools = app.neutron.list_subnetpools( name=subnetpool_name) for subnetpool in subnetpools['subnetpools']: default_subnetpool_id_set.add(subnetpool['id']) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happened during retrieving the default " "subnet pools.".format(ex)) app.DEFAULT_POOL_IDS = frozenset(default_subnetpool_id_set) def _get_networks_by_attrs(**attrs): networks = app.neutron.list_networks(**attrs) if len(networks.get('networks', [])) > 1: raise exceptions.DuplicatedResourceException( "Multiple Neutron networks exist for the params {0}" .format(', '.join(['{0}={1}'.format(k, v) for k, v in attrs.items()]))) return networks['networks'] def _get_subnets_by_attrs(**attrs): subnets = app.neutron.list_subnets(**attrs) if len(subnets.get('subnets', [])) > 2: # subnets for IPv4 and/or IPv6 raise exceptions.DuplicatedResourceException( "Multiple Neutron subnets exist for the params {0} " .format(', '.join(['{0}={1}'.format(k, v) for k, v in attrs.items()]))) return subnets['subnets'] def _get_ports_by_attrs(**attrs): ports = app.neutron.list_ports(**attrs) if len(ports.get('ports', [])) > 1: raise exceptions.DuplicatedResourceException( "Multiple Neutron ports exist for the params {0} " .format(', '.join(['{0}={1}'.format(k, v) for k, v in attrs.items()]))) return ports['ports'] def _get_subnetpools_by_attrs(**attrs): subnetpools = app.neutron.list_subnetpools(**attrs) if len(subnetpools.get('subnetpools', [])) > 1: raise exceptions.DuplicatedResourceException( "Multiple Neutron subnetspool exist for the params {0} " .format(', '.join(['{0}={1}'.format(k, v) for k, v in attrs.items()]))) return subnetpools['subnetpools'] def _get_subnet_cidr_using_cidr(cidr): subnet_network = str(cidr.network) subnet_cidr = '/'.join([subnet_network, str(cidr.prefixlen)]) return subnet_cidr def _get_subnets_by_interface_cidr(neutron_network_id, interface_cidr): cidr = netaddr.IPNetwork(interface_cidr) subnet_network = cidr.network subnet_cidr = '/'.join([str(subnet_network), str(cidr.prefixlen)]) subnets = _get_subnets_by_attrs( network_id=neutron_network_id, cidr=subnet_cidr) return subnets def _process_interface_address(port_dict, subnets_dict_by_id, response_interface): assigned_address = port_dict['ip_address'] subnet_id = port_dict['subnet_id'] subnet = subnets_dict_by_id[subnet_id] cidr = netaddr.IPNetwork(subnet['cidr']) assigned_address += '/' + str(cidr.prefixlen) if cidr.version == 4: response_interface['Address'] = assigned_address else: response_interface['AddressIPv6'] = assigned_address def _create_port(endpoint_id, neutron_network_id, interface_mac, fixed_ips): port = { 'name': utils.get_neutron_port_name(endpoint_id), 'admin_state_up': True, 'network_id': neutron_network_id, 'device_owner': constants.DEVICE_OWNER, 'device_id': endpoint_id, 'binding:host_id': utils.get_hostname(), 'fixed_ips': fixed_ips } if interface_mac: port['mac_address'] = interface_mac try: rcvd_port = app.neutron.create_port({'port': port}) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend during creating a " "Neutron port: {0}".format(ex)) raise return rcvd_port['port'] def _update_port(port, endpoint_id): port['name'] = '-'.join([endpoint_id, 'port']) try: response_port = app.neutron.update_port({'port': port}) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend during creating a " "Neutron port: {0}".format(ex)) raise return response_port def _get_fixed_ips_by_interface_cidr(subnets, interface_cidrv4, interface_cidrv6, fixed_ips): for subnet in subnets: fixed_ip = {'subnet_id': subnet['id']} if interface_cidrv4 or interface_cidrv6: if subnet['ip_version'] == 4 and interface_cidrv4: cidr = netaddr.IPNetwork(interface_cidrv4) elif subnet['ip_version'] == 6 and interface_cidrv6: cidr = netaddr.IPNetwork(interface_cidrv6) subnet_cidr = '/'.join([str(cidr.network), str(cidr.prefixlen)]) if subnet['cidr'] != subnet_cidr: continue fixed_ip['ip_address'] = str(cidr.ip) fixed_ips.append(fixed_ip) def _create_or_update_port(neutron_network_id, endpoint_id, interface_cidrv4, interface_cidrv6, interface_mac): response_interface = {} subnets = [] fixed_ips = [] subnetsv4 = subnetsv6 = [] if interface_cidrv4: subnetsv4 = _get_subnets_by_interface_cidr( neutron_network_id, interface_cidrv4) if interface_cidrv6: subnetsv6 = _get_subnets_by_interface_cidr( neutron_network_id, interface_cidrv6) subnets = subnetsv4 + subnetsv6 if not len(subnets): raise exceptions.NoResourceException( "No subnet exist for the cidrs {0} and {1} " .format(interface_cidrv4, interface_cidrv6)) if len(subnets) > 2: raise exceptions.DuplicatedResourceException( "Multiple subnets exist for the cidrs {0} and {1}" .format(interface_cidrv4, interface_cidrv6)) _get_fixed_ips_by_interface_cidr(subnets, interface_cidrv4, interface_cidrv6, fixed_ips) filtered_ports = app.neutron.list_ports(fixed_ips=fixed_ips) num_port = len(filtered_ports.get('ports', [])) if not num_port: response_port = _create_port(endpoint_id, neutron_network_id, interface_mac, fixed_ips) elif num_port == 1: port = filtered_ports['ports'][0] response_port = _update_port(port, endpoint_id) else: raise n_exceptions.DuplicatedResourceException( "Multiple ports exist for the cidrs {0} and {1}" .format(interface_cidrv4, interface_cidrv6)) created_fixed_ips = response_port['fixed_ips'] subnets_dict_by_id = {subnet['id']: subnet for subnet in subnets} if not interface_mac: response_interface['MacAddress'] = response_port['mac_address'] if not (interface_cidrv4 or interface_cidrv6): if 'ip_address' in response_port: _process_interface_address( response_port, subnets_dict_by_id, response_interface) for fixed_ip in created_fixed_ips: _process_interface_address( fixed_ip, subnets_dict_by_id, response_interface) return response_interface @app.route('/Plugin.Activate', methods=['POST']) def plugin_activate(): """Returns the list of the implemented drivers. This function returns the list of the implemented drivers defaults to ``[NetworkDriver, IpamDriver]`` in the handshake of the remote driver, which happens right before the first request against Kuryr. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#handshake # noqa """ return flask.jsonify(constants.SCHEMA['PLUGIN_ACTIVATE']) @app.route('/NetworkDriver.GetCapabilities', methods=['POST']) def plugin_scope(): """Returns the capability as the remote network driver. This function returns the capability of the remote network driver, which is ``global`` or ``local`` and defaults to ``global``. With ``global`` capability, the network information is shared among multipe Docker daemons if the distributed store is appropriately configured. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#set-capability # noqa """ capabilities = {'Scope': cfg.CONF.capability_scope} return flask.jsonify(capabilities) @app.route('/NetworkDriver.DiscoverNew', methods=['POST']) def network_driver_discover_new(): """The callback function for the DiscoverNew notification. The DiscoverNew notification includes the type of the resource that has been newly discovered and possibly other information associated with the resource. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#discovernew-notification # noqa """ return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.DiscoverDelete', methods=['POST']) def network_driver_discover_delete(): """The callback function for the DiscoverDelete notification. The DiscoverDelete notification includes the type of the resource that has been deleted and possibly other information associated with the resource. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#discoverdelete-notification # noqa """ return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.CreateNetwork', methods=['POST']) def network_driver_create_network(): """Creates a new Neutron Network which name is the given NetworkID. This function takes the following JSON data and delegates the actual network creation to the Neutron client. libnetwork's NetworkID is used as the name of Network in Neutron. :: { "NetworkID": string, "IPv4Data" : [{ "AddressSpace": string, "Pool": ipv4-cidr-string, "Gateway" : ipv4-address, "AuxAddresses": { "<identifier1>" : "<ipv4-address1>", "<identifier2>" : "<ipv4-address2>", ... } }, ...], "IPv6Data" : [{ "AddressSpace": string, "Pool": ipv6-cidr-string, "Gateway" : ipv6-address, "AuxAddresses": { "<identifier1>" : "<ipv6-address1>", "<identifier2>" : "<ipv6-address2>", ... } }, ...], "Options": { ... } } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#create-network # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.CreateNetwork" .format(json_data)) jsonschema.validate(json_data, schemata.NETWORK_CREATE_SCHEMA) neutron_network_name = json_data['NetworkID'] pool_cidr = json_data['IPv4Data'][0]['Pool'] network = app.neutron.create_network( {'network': {'name': neutron_network_name, "admin_state_up": True}}) app.logger.info("Created a new network with name {0} successfully: {1}" .format(neutron_network_name, network)) cidr = netaddr.IPNetwork(pool_cidr) subnet_network = str(cidr.network) subnet_cidr = '/'.join([subnet_network, str(cidr.prefixlen)]) subnets = _get_subnets_by_attrs( network_id=network['network']['id'], cidr=subnet_cidr) if not subnets: new_subnets = [{ 'name': pool_cidr, 'network_id': network['network']['id'], 'ip_version': cidr.version, 'cidr': subnet_cidr, }] app.neutron.create_subnet({'subnets': new_subnets}) return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.DeleteNetwork', methods=['POST']) def network_driver_delete_network(): """Deletes the Neutron Network which name is the given NetworkID. This function takes the following JSON data and delegates the actual network deletion to the Neutron client. :: { "NetworkID": string } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#delete-network # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.DeleteNetwork" .format(json_data)) jsonschema.validate(json_data, schemata.NETWORK_DELETE_SCHEMA) neutron_network_name = json_data['NetworkID'] try: filtered_networks = _get_networks_by_attrs(name=neutron_network_name) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happened during listing " "Neutron networks: {0}".format(ex)) raise # We assume Neutron's Network names are not conflicted in Kuryr because # they are Docker IDs, 256 bits hashed values, which are rarely conflicted. # However, if there're multiple networks associated with the single # NetworkID, it raises DuplicatedResourceException and stops processes. # See the following doc for more details about Docker's IDs: # https://github.com/docker/docker/blob/master/docs/terms/container.md#container-ids # noqa neutron_network_id = filtered_networks[0]['id'] filtered_subnets = _get_subnets_by_attrs( network_id=neutron_network_id) for subnet in filtered_subnets: try: subnetpool_id = subnet.get('subnetpool_id', None) _cache_default_subnetpool_ids(app) if subnetpool_id not in app.DEFAULT_POOL_IDS: # If the subnet to be deleted has any port, when some ports # are referring to the subnets in other words, # delete_subnet throws an exception, SubnetInUse that # extends Conflict. This can happen when the multiple # Docker endpoints are created with the same subnet CIDR # and it's totally the normal case. So we'd just log that # and continue to proceed. app.neutron.delete_subnet(subnet['id']) except n_exceptions.Conflict as ex: app.logger.error("Subnet, {0}, is in use. " "Network cant be deleted.".format(subnet['id'])) raise except n_exceptions.NeutronClientException as ex: app.logger.error("Error happened during deleting a " "Neutron subnets: {0}".format(ex)) raise try: app.neutron.delete_network(neutron_network_id) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happened during deleting a " "Neutron network: {0}".format(ex)) raise app.logger.info("Deleted the network with ID {0} successfully" .format(neutron_network_id)) return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.CreateEndpoint', methods=['POST']) def network_driver_create_endpoint(): """Creates new Neutron Subnets and a Port with the given EndpointID. This function takes the following JSON data and delegates the actual endpoint creation to the Neutron client mapping it into Subnet and Port. :: { "NetworkID": string, "EndpointID": string, "Options": { ... }, "Interface": { "Address": string, "AddressIPv6": string, "MacAddress": string } } Then the following JSON response is returned. :: { "Interface": { "Address": string, "AddressIPv6": string, "MacAddress": string } } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#create-endpoint # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.CreateEndpoint" .format(json_data)) jsonschema.validate(json_data, schemata.ENDPOINT_CREATE_SCHEMA) neutron_network_name = json_data['NetworkID'] endpoint_id = json_data['EndpointID'] filtered_networks = _get_networks_by_attrs(name=neutron_network_name) if not filtered_networks: return flask.jsonify({ 'Err': "Neutron network associated with ID {0} doesn't exist." .format(neutron_network_name) }) else: neutron_network_id = filtered_networks[0]['id'] interface = json_data['Interface'] or {} # Workaround for null interface_cidrv4 = interface.get('Address', '') interface_cidrv6 = interface.get('AddressIPv6', '') interface_mac = interface.get('MacAddress', '') if not filtered_networks: return flask.jsonify({ 'Err': "Interface address not provided." }) response_interface = _create_or_update_port( neutron_network_id, endpoint_id, interface_cidrv4, interface_cidrv6, interface_mac) return flask.jsonify({'Interface': response_interface}) @app.route('/NetworkDriver.EndpointOperInfo', methods=['POST']) def network_driver_endpoint_operational_info(): return flask.jsonify(constants.SCHEMA['ENDPOINT_OPER_INFO']) @app.route('/NetworkDriver.DeleteEndpoint', methods=['POST']) def network_driver_delete_endpoint(): """Deletes Neutron Subnets and a Port with the given EndpointID. This function takes the following JSON data and delegates the actual endpoint deletion to the Neutron client mapping it into Subnet and Port. :: { "NetworkID": string, "EndpointID": string } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#delete-endpoint # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.DeleteEndpoint" .format(json_data)) jsonschema.validate(json_data, schemata.ENDPOINT_DELETE_SCHEMA) return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.Join', methods=['POST']) def network_driver_join(): """Binds a Neutron Port to a network interface attached to a container. This function takes the following JSON data, creates a veth pair, put one end inside of the container and binds another end to the Neutron Port specified in the request. :: { "NetworkID": string, "EndpointID": string, "SandboxKey": string, "Options": { ... } } If the binding is succeeded, the following JSON response is returned.:: { "InterfaceName": { SrcName: string, DstPrefix: string }, "Gateway": string, "GatewayIPv6": string, "StaticRoutes": [{ "Destination": string, "RouteType": int, "NextHop": string, }, ...] } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#join # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.Join" .format(json_data)) jsonschema.validate(json_data, schemata.JOIN_SCHEMA) neutron_network_name = json_data['NetworkID'] endpoint_id = json_data['EndpointID'] filtered_networks = _get_networks_by_attrs(name=neutron_network_name) if not filtered_networks: return flask.jsonify({ 'Err': "Neutron network associated with ID {0} doesn't exit." .format(neutron_network_name) }) else: neutron_network_id = filtered_networks[0]['id'] neutron_port_name = utils.get_neutron_port_name(endpoint_id) filtered_ports = _get_ports_by_attrs(name=neutron_port_name) if not filtered_ports: raise exceptions.NoResourceException( "The port doesn't exist for the name {0}" .format(neutron_port_name)) neutron_port = filtered_ports[0] all_subnets = _get_subnets_by_attrs(network_id=neutron_network_id) try: ifname, peer_name, (stdout, stderr) = binding.port_bind( endpoint_id, neutron_port, all_subnets) app.logger.debug(stdout) if stderr: app.logger.error(stderr) except exceptions.VethCreationFailure as ex: with excutils.save_and_reraise_exception(): app.logger.error('Preparing the veth pair was failed: {0}.' .format(ex)) except processutils.ProcessExecutionError: with excutils.save_and_reraise_exception(): app.logger.error( 'Could not bind the Neutron port to the veth endpoint.') join_response = { "InterfaceName": { "SrcName": peer_name, "DstPrefix": config.CONF.binding.veth_dst_prefix }, "StaticRoutes": [] } for subnet in all_subnets: if subnet['ip_version'] == 4: join_response['Gateway'] = subnet.get('gateway_ip', '') else: join_response['GatewayIPv6'] = subnet.get('gateway_ip', '') host_routes = subnet.get('host_routes', []) for host_route in host_routes: static_route = { 'Destination': host_route['destination'] } if host_route.get('nexthop', None): static_route['RouteType'] = constants.TYPES['NEXTHOP'] static_route['NextHop'] = host_route['nexthop'] else: static_route['RouteType'] = constants.TYPES['CONNECTED'] join_response['StaticRoutes'].append(static_route) return flask.jsonify(join_response) @app.route('/NetworkDriver.Leave', methods=['POST']) def network_driver_leave(): """Unbinds a Neutron Port to a network interface attached to a container. This function takes the following JSON data and delete the veth pair corresponding to the given info. :: { "NetworkID": string, "EndpointID": string } """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.DeleteEndpoint" .format(json_data)) jsonschema.validate(json_data, schemata.LEAVE_SCHEMA) neutron_network_name = json_data['NetworkID'] endpoint_id = json_data['EndpointID'] filtered_networks = _get_networks_by_attrs(name=neutron_network_name) if not filtered_networks: return flask.jsonify({ 'Err': "Neutron network associated with ID {0} doesn't exit." .format(neutron_network_name) }) else: neutron_port_name = utils.get_neutron_port_name(endpoint_id) filtered_ports = _get_ports_by_attrs(name=neutron_port_name) if not filtered_ports: raise exceptions.NoResourceException( "The port doesn't exist for the name {0}" .format(neutron_port_name)) neutron_port = filtered_ports[0] try: stdout, stderr = binding.port_unbind(endpoint_id, neutron_port) app.logger.debug(stdout) if stderr: app.logger.error(stderr) except processutils.ProcessExecutionError: with excutils.save_and_reraise_exception(): app.logger.error( 'Could not unbind the Neutron port from the veth ' 'endpoint.') except exceptions.VethDeletionFailure: with excutils.save_and_reraise_exception(): app.logger.error('Cleaning the veth pair up was failed.') return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/IpamDriver.GetDefaultAddressSpaces', methods=['POST']) def ipam_get_default_address_spaces(): """Provides the default address spaces for the IPAM. This function is called after the registration of the IPAM driver and the plugin set the returned values as the default address spaces for the IPAM. The address spaces can be configured in the config file. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#getdefaultaddressspaces # noqa """ app.logger.debug("Received /IpamDriver.GetDefaultAddressSpaces") address_spaces = { 'LocalDefaultAddressSpace': cfg.CONF.local_default_address_space, 'GlobalDefaultAddressSpace': cfg.CONF.global_default_address_space} return flask.jsonify(address_spaces) @app.route('/IpamDriver.RequestPool', methods=['POST']) def ipam_request_pool(): """Creates a new Neutron subnetpool from the given request. This funciton takes the following JSON data and delegates the subnetpool creation to the Neutron client. :: { "AddressSpace": string "Pool": string "SubPool": string "Options": map[string]string "V6": bool } Then the following JSON response is returned. :: { "PoolID": string "Pool": string "Data": map[string]string } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#requestpool # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /IpamDriver.RequestPool" .format(json_data)) jsonschema.validate(json_data, schemata.REQUEST_POOL_SCHEMA) requested_pool = json_data['Pool'] requested_subpool = json_data['SubPool'] v6 = json_data['V6'] pool_id = '' subnet_cidr = '' if requested_pool: app.logger.info("Creating subnetpool with the given pool CIDR") if requested_subpool: cidr = netaddr.IPNetwork(requested_subpool) else: cidr = netaddr.IPNetwork(requested_pool) subnet_cidr = _get_subnet_cidr_using_cidr(cidr) pool_name = utils.get_neutron_subnetpool_name(subnet_cidr) # Check if requested pool already exist pools = _get_subnetpools_by_attrs(name=pool_name) if pools: pool_id = pools[0]['id'] if not pools: new_subnetpool = { 'name': pool_name, 'default_prefixlen': cidr.prefixlen, 'prefixes': [subnet_cidr]} created_subnetpool_response = app.neutron.create_subnetpool( {'subnetpool': new_subnetpool}) pool = created_subnetpool_response['subnetpool'] pool_id = pool['id'] else: if v6: default_pool_list = SUBNET_POOLS_V6 else: default_pool_list = SUBNET_POOLS_V4 pool_name = default_pool_list[0] pools = _get_subnetpools_by_attrs(name=pool_name) if pools: pool = pools[0] pool_id = pool['id'] prefixes = pool['prefixes'] if len(prefixes) > 1: app.logger.warning("More than one prefixes present. " "Picking first one.") cidr = netaddr.IPNetwork(prefixes[0]) subnet_cidr = _get_subnet_cidr_using_cidr(cidr) else: app.logger.error("Default neutron pools not found") req_pool_res = {'PoolID': pool_id, 'Pool': subnet_cidr} return flask.jsonify(req_pool_res) @app.route('/IpamDriver.RequestAddress', methods=['POST']) def ipam_request_address(): """Allocates the IP address in the given request. This function takes the following JSON data and add the given IP address in the allocation_pools attribute of the subnet. :: { "PoolID": string "Address": string "Options": map[string]string } Then the following response is returned. :: { "Address": string "Data": map[string]string } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#requestaddress # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /IpamDriver.RequestAddress" .format(json_data)) jsonschema.validate(json_data, schemata.REQUEST_ADDRESS_SCHEMA) pool_id = json_data['PoolID'] req_address = json_data['Address'] allocated_address = '' subnet_cidr = '' pool_prefix_len = '' pools = _get_subnetpools_by_attrs(id=pool_id) if pools: pool = pools[0] prefixes = pool['prefixes'] if len(prefixes) > 1: app.logger.warning("More than one prefixes present. Picking " "first one.") for prefix in prefixes: cidr = netaddr.IPNetwork(prefix) pool_prefix_len = str(cidr.prefixlen) subnet_network = str(cidr.network) subnet_cidr = '/'.join([subnet_network, pool_prefix_len]) break else: raise exceptions.NoResourceException( "No subnetpools with id {0} is found." .format(pool_id)) # check if any subnet with matching cidr is present subnets = _get_subnets_by_attrs(cidr=subnet_cidr) if subnets: subnet = subnets[0] # allocating address for container port neutron_network_id = subnet['network_id'] try: port = { 'name': 'kuryr-unbound-port', 'admin_state_up': True, 'network_id': neutron_network_id, } fixed_ips = port['fixed_ips'] = [] fixed_ip = {'subnet_id': subnet['id']} if req_address: fixed_ip['ip_address'] = req_address fixed_ips.append(fixed_ip) created_port_resp = app.neutron.create_port({'port': port}) created_port = created_port_resp['port'] allocated_address = created_port['fixed_ips'][0]['ip_address'] allocated_address = '/'.join( [allocated_address, str(cidr.prefixlen)]) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend during ip allocation on" "Neutron side: {0}".format(ex)) raise else: # Auxiliary address or gw_address is received at network creation time. # This address cannot be reserved with neutron at this time as subnet # is not created yet. In /NetworkDriver.CreateNetwork this address will # be reserved with neutron. allocated_address = '/'.join([req_address, pool_prefix_len]) return flask.jsonify({'Address': allocated_address}) @app.route('/IpamDriver.ReleasePool', methods=['POST']) def ipam_release_pool(): """Deletes a new Neutron subnetpool from the given reuest. This function takes the following JSON data and delegates the subnetpool deletion to the Neutron client. :: { "PoolID": string } Then the following JSON response is returned. :: {} See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#releasepool # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /IpamDriver.ReleasePool" .format(json_data)) jsonschema.validate(json_data, schemata.RELEASE_POOL_SCHEMA) pool_id = json_data['PoolID'] try: app.neutron.delete_subnetpool(pool_id) except n_exceptions.Conflict as ex: app.logger.info("The subnetpool with ID {0} is still in use." " It can't be deleted for now.".format(pool_id)) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend during deleting a " "Neutron subnetpool: {0}".format(ex)) raise return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/IpamDriver.ReleaseAddress', methods=['POST']) def ipam_release_address(): """Deallocates the IP address in the given request. This function takes the following JSON data and remove the given IP address from the allocation_pool attribute of the subnet. :: { "PoolID": string "Address": string } Then the following response is returned. :: {} See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#releaseaddress # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /IpamDriver.ReleaseAddress" .format(json_data)) jsonschema.validate(json_data, schemata.RELEASE_ADDRESS_SCHEMA) pool_id = json_data['PoolID'] rel_address = json_data['Address'] filtered_ports = [] pools = _get_subnetpools_by_attrs(id=pool_id) if pools: pool = pools[0] prefixes = pool['prefixes'] for prefix in prefixes: cidr = netaddr.IPNetwork(prefix) subnet_network = str(cidr.network) subnet_cidr = '/'.join([subnet_network, str(cidr.prefixlen)]) else: raise exceptions.NoResourceException( "No subnetpools with id {0} is found." .format(pool_id)) # check if any subnet with matching cidr is present subnets = _get_subnets_by_attrs(cidr=subnet_cidr) if not len(subnets): raise exceptions.NoResourceException( "No subnet is found using pool {0} " "and pool_cidr {1}".format(pool_id, cidr)) subnet = subnets[0] cidr_address = netaddr.IPNetwork(rel_address) rcvd_fixed_ips = [] fixed_ip = {'subnet_id': subnet['id']} fixed_ip['ip_address'] = str(cidr_address.ip) rcvd_fixed_ips.append(fixed_ip) try: filtered_ports = [] all_ports = app.neutron.list_ports() for port in all_ports['ports']: if port['fixed_ips'] == rcvd_fixed_ips: filtered_ports.append(port) for port in filtered_ports: app.neutron.delete_port(port['id']) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend while fetching and deleting port, " "{0}".format(ex)) raise return flask.jsonify(constants.SCHEMA['SUCCESS']) neutron_client() Fix wrong checking code The code checks filtered_networks in duplicate and mismatch with its declarer. Change-Id: Ie407369c34c088b6f504c2494ef8833a49ac0aef # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import os_client_config import flask import jsonschema import netaddr from neutronclient.common import exceptions as n_exceptions from neutronclient.neutron import client from oslo_concurrency import processutils from oslo_config import cfg from oslo_utils import excutils from kuryr import app from kuryr import binding from kuryr.common import config from kuryr.common import constants from kuryr.common import exceptions from kuryr import schemata from kuryr import utils MANDATORY_NEUTRON_EXTENSION = "subnet_allocation" def _get_cloud_config(cloud='devstack-admin'): return os_client_config.OpenStackConfig().get_one_cloud(cloud=cloud) def _credentials(cloud='devstack-admin'): """Retrieves credentials to run functional tests Credentials are either read via os-client-config from the environment or from a config file ('clouds.yaml'). Environment variables override those from the config file. devstack produces a clouds.yaml with two named clouds - one named 'devstack' which has user privs and one named 'devstack-admin' which has admin privs. This function will default to getting the devstack-admin cloud as that is the current expected behavior. """ return _get_cloud_config(cloud=cloud).get_auth_args() def _get_neutron_client_from_creds(): creds = _credentials() username = creds['username'] tenant_name = creds['project_name'] password = creds['password'] auth_url = creds['auth_url'] + "/v2.0" neutron_client = client.Client('2.0', username=username, tenant_name=tenant_name, password=password, auth_url=auth_url) return neutron_client def get_neutron_client(): """Creates the Neutron client for communicating with Neutron.""" try: # First try to retrieve neutron client from a working OS deployment # This is used for gate testing. # Since this always use admin credentials, next patch will introduce # a config parameter that disable this for production environments neutron_client = _get_neutron_client_from_creds() return neutron_client except Exception: pass cfg.CONF.import_group('neutron_client', 'kuryr.common.config') cfg.CONF.import_group('keystone_client', 'kuryr.common.config') keystone_conf = cfg.CONF.keystone_client username = keystone_conf.admin_user tenant_name = keystone_conf.admin_tenant_name password = keystone_conf.admin_password auth_token = keystone_conf.admin_token auth_uri = keystone_conf.auth_uri.rstrip('/') neutron_uri = cfg.CONF.neutron_client.neutron_uri if username and password: # Authenticate with password crentials neutron_client = utils.get_neutron_client( url=neutron_uri, username=username, tenant_name=tenant_name, password=password, auth_url=auth_uri) else: neutron_client = utils.get_neutron_client_simple( url=neutron_uri, auth_url=auth_uri, token=auth_token) return neutron_client def neutron_client(): if not hasattr(app, 'neutron'): app.neutron = get_neutron_client() app.enable_dhcp = cfg.CONF.neutron_client.enable_dhcp app.neutron.format = 'json' def check_for_neutron_ext_support(): """Validates for mandatory extension support availability in neutron.""" try: app.neutron.show_extension(MANDATORY_NEUTRON_EXTENSION) except n_exceptions.NeutronClientException as e: if e.status_code == n_exceptions.NotFound.status_code: raise exceptions.MandatoryApiMissing( "Neutron extension with alias '{0}' not found" .format(MANDATORY_NEUTRON_EXTENSION)) # TODO(tfukushima): Retrieve the following subnet names from the config file. SUBNET_POOLS_V4 = [ p.strip() for p in os.environ.get('SUBNET_POOLS_V4', 'kuryr').split(',')] SUBNET_POOLS_V6 = [ p.strip() for p in os.environ.get('SUBNET_POOLS_V6', 'kuryr6').split(',')] def _cache_default_subnetpool_ids(app): """Caches IDs of the default subnetpools as app.DEFAULT_POOL_IDS.""" if not hasattr(app, 'DEFAULT_POOL_IDS'): default_subnetpool_id_set = set() try: subnetpool_names = SUBNET_POOLS_V4 + SUBNET_POOLS_V6 for subnetpool_name in subnetpool_names: subnetpools = app.neutron.list_subnetpools( name=subnetpool_name) for subnetpool in subnetpools['subnetpools']: default_subnetpool_id_set.add(subnetpool['id']) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happened during retrieving the default " "subnet pools.".format(ex)) app.DEFAULT_POOL_IDS = frozenset(default_subnetpool_id_set) def _get_networks_by_attrs(**attrs): networks = app.neutron.list_networks(**attrs) if len(networks.get('networks', [])) > 1: raise exceptions.DuplicatedResourceException( "Multiple Neutron networks exist for the params {0}" .format(', '.join(['{0}={1}'.format(k, v) for k, v in attrs.items()]))) return networks['networks'] def _get_subnets_by_attrs(**attrs): subnets = app.neutron.list_subnets(**attrs) if len(subnets.get('subnets', [])) > 2: # subnets for IPv4 and/or IPv6 raise exceptions.DuplicatedResourceException( "Multiple Neutron subnets exist for the params {0} " .format(', '.join(['{0}={1}'.format(k, v) for k, v in attrs.items()]))) return subnets['subnets'] def _get_ports_by_attrs(**attrs): ports = app.neutron.list_ports(**attrs) if len(ports.get('ports', [])) > 1: raise exceptions.DuplicatedResourceException( "Multiple Neutron ports exist for the params {0} " .format(', '.join(['{0}={1}'.format(k, v) for k, v in attrs.items()]))) return ports['ports'] def _get_subnetpools_by_attrs(**attrs): subnetpools = app.neutron.list_subnetpools(**attrs) if len(subnetpools.get('subnetpools', [])) > 1: raise exceptions.DuplicatedResourceException( "Multiple Neutron subnetspool exist for the params {0} " .format(', '.join(['{0}={1}'.format(k, v) for k, v in attrs.items()]))) return subnetpools['subnetpools'] def _get_subnet_cidr_using_cidr(cidr): subnet_network = str(cidr.network) subnet_cidr = '/'.join([subnet_network, str(cidr.prefixlen)]) return subnet_cidr def _get_subnets_by_interface_cidr(neutron_network_id, interface_cidr): cidr = netaddr.IPNetwork(interface_cidr) subnet_network = cidr.network subnet_cidr = '/'.join([str(subnet_network), str(cidr.prefixlen)]) subnets = _get_subnets_by_attrs( network_id=neutron_network_id, cidr=subnet_cidr) return subnets def _process_interface_address(port_dict, subnets_dict_by_id, response_interface): assigned_address = port_dict['ip_address'] subnet_id = port_dict['subnet_id'] subnet = subnets_dict_by_id[subnet_id] cidr = netaddr.IPNetwork(subnet['cidr']) assigned_address += '/' + str(cidr.prefixlen) if cidr.version == 4: response_interface['Address'] = assigned_address else: response_interface['AddressIPv6'] = assigned_address def _create_port(endpoint_id, neutron_network_id, interface_mac, fixed_ips): port = { 'name': utils.get_neutron_port_name(endpoint_id), 'admin_state_up': True, 'network_id': neutron_network_id, 'device_owner': constants.DEVICE_OWNER, 'device_id': endpoint_id, 'binding:host_id': utils.get_hostname(), 'fixed_ips': fixed_ips } if interface_mac: port['mac_address'] = interface_mac try: rcvd_port = app.neutron.create_port({'port': port}) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend during creating a " "Neutron port: {0}".format(ex)) raise return rcvd_port['port'] def _update_port(port, endpoint_id): port['name'] = '-'.join([endpoint_id, 'port']) try: response_port = app.neutron.update_port({'port': port}) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend during creating a " "Neutron port: {0}".format(ex)) raise return response_port def _get_fixed_ips_by_interface_cidr(subnets, interface_cidrv4, interface_cidrv6, fixed_ips): for subnet in subnets: fixed_ip = {'subnet_id': subnet['id']} if interface_cidrv4 or interface_cidrv6: if subnet['ip_version'] == 4 and interface_cidrv4: cidr = netaddr.IPNetwork(interface_cidrv4) elif subnet['ip_version'] == 6 and interface_cidrv6: cidr = netaddr.IPNetwork(interface_cidrv6) subnet_cidr = '/'.join([str(cidr.network), str(cidr.prefixlen)]) if subnet['cidr'] != subnet_cidr: continue fixed_ip['ip_address'] = str(cidr.ip) fixed_ips.append(fixed_ip) def _create_or_update_port(neutron_network_id, endpoint_id, interface_cidrv4, interface_cidrv6, interface_mac): response_interface = {} subnets = [] fixed_ips = [] subnetsv4 = subnetsv6 = [] if interface_cidrv4: subnetsv4 = _get_subnets_by_interface_cidr( neutron_network_id, interface_cidrv4) if interface_cidrv6: subnetsv6 = _get_subnets_by_interface_cidr( neutron_network_id, interface_cidrv6) subnets = subnetsv4 + subnetsv6 if not len(subnets): raise exceptions.NoResourceException( "No subnet exist for the cidrs {0} and {1} " .format(interface_cidrv4, interface_cidrv6)) if len(subnets) > 2: raise exceptions.DuplicatedResourceException( "Multiple subnets exist for the cidrs {0} and {1}" .format(interface_cidrv4, interface_cidrv6)) _get_fixed_ips_by_interface_cidr(subnets, interface_cidrv4, interface_cidrv6, fixed_ips) filtered_ports = app.neutron.list_ports(fixed_ips=fixed_ips) num_port = len(filtered_ports.get('ports', [])) if not num_port: response_port = _create_port(endpoint_id, neutron_network_id, interface_mac, fixed_ips) elif num_port == 1: port = filtered_ports['ports'][0] response_port = _update_port(port, endpoint_id) else: raise n_exceptions.DuplicatedResourceException( "Multiple ports exist for the cidrs {0} and {1}" .format(interface_cidrv4, interface_cidrv6)) created_fixed_ips = response_port['fixed_ips'] subnets_dict_by_id = {subnet['id']: subnet for subnet in subnets} if not interface_mac: response_interface['MacAddress'] = response_port['mac_address'] if not (interface_cidrv4 or interface_cidrv6): if 'ip_address' in response_port: _process_interface_address( response_port, subnets_dict_by_id, response_interface) for fixed_ip in created_fixed_ips: _process_interface_address( fixed_ip, subnets_dict_by_id, response_interface) return response_interface @app.route('/Plugin.Activate', methods=['POST']) def plugin_activate(): """Returns the list of the implemented drivers. This function returns the list of the implemented drivers defaults to ``[NetworkDriver, IpamDriver]`` in the handshake of the remote driver, which happens right before the first request against Kuryr. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#handshake # noqa """ return flask.jsonify(constants.SCHEMA['PLUGIN_ACTIVATE']) @app.route('/NetworkDriver.GetCapabilities', methods=['POST']) def plugin_scope(): """Returns the capability as the remote network driver. This function returns the capability of the remote network driver, which is ``global`` or ``local`` and defaults to ``global``. With ``global`` capability, the network information is shared among multipe Docker daemons if the distributed store is appropriately configured. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#set-capability # noqa """ capabilities = {'Scope': cfg.CONF.capability_scope} return flask.jsonify(capabilities) @app.route('/NetworkDriver.DiscoverNew', methods=['POST']) def network_driver_discover_new(): """The callback function for the DiscoverNew notification. The DiscoverNew notification includes the type of the resource that has been newly discovered and possibly other information associated with the resource. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#discovernew-notification # noqa """ return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.DiscoverDelete', methods=['POST']) def network_driver_discover_delete(): """The callback function for the DiscoverDelete notification. The DiscoverDelete notification includes the type of the resource that has been deleted and possibly other information associated with the resource. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#discoverdelete-notification # noqa """ return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.CreateNetwork', methods=['POST']) def network_driver_create_network(): """Creates a new Neutron Network which name is the given NetworkID. This function takes the following JSON data and delegates the actual network creation to the Neutron client. libnetwork's NetworkID is used as the name of Network in Neutron. :: { "NetworkID": string, "IPv4Data" : [{ "AddressSpace": string, "Pool": ipv4-cidr-string, "Gateway" : ipv4-address, "AuxAddresses": { "<identifier1>" : "<ipv4-address1>", "<identifier2>" : "<ipv4-address2>", ... } }, ...], "IPv6Data" : [{ "AddressSpace": string, "Pool": ipv6-cidr-string, "Gateway" : ipv6-address, "AuxAddresses": { "<identifier1>" : "<ipv6-address1>", "<identifier2>" : "<ipv6-address2>", ... } }, ...], "Options": { ... } } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#create-network # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.CreateNetwork" .format(json_data)) jsonschema.validate(json_data, schemata.NETWORK_CREATE_SCHEMA) neutron_network_name = json_data['NetworkID'] pool_cidr = json_data['IPv4Data'][0]['Pool'] network = app.neutron.create_network( {'network': {'name': neutron_network_name, "admin_state_up": True}}) app.logger.info("Created a new network with name {0} successfully: {1}" .format(neutron_network_name, network)) cidr = netaddr.IPNetwork(pool_cidr) subnet_network = str(cidr.network) subnet_cidr = '/'.join([subnet_network, str(cidr.prefixlen)]) subnets = _get_subnets_by_attrs( network_id=network['network']['id'], cidr=subnet_cidr) if not subnets: new_subnets = [{ 'name': pool_cidr, 'network_id': network['network']['id'], 'ip_version': cidr.version, 'cidr': subnet_cidr, }] app.neutron.create_subnet({'subnets': new_subnets}) return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.DeleteNetwork', methods=['POST']) def network_driver_delete_network(): """Deletes the Neutron Network which name is the given NetworkID. This function takes the following JSON data and delegates the actual network deletion to the Neutron client. :: { "NetworkID": string } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#delete-network # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.DeleteNetwork" .format(json_data)) jsonschema.validate(json_data, schemata.NETWORK_DELETE_SCHEMA) neutron_network_name = json_data['NetworkID'] try: filtered_networks = _get_networks_by_attrs(name=neutron_network_name) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happened during listing " "Neutron networks: {0}".format(ex)) raise # We assume Neutron's Network names are not conflicted in Kuryr because # they are Docker IDs, 256 bits hashed values, which are rarely conflicted. # However, if there're multiple networks associated with the single # NetworkID, it raises DuplicatedResourceException and stops processes. # See the following doc for more details about Docker's IDs: # https://github.com/docker/docker/blob/master/docs/terms/container.md#container-ids # noqa neutron_network_id = filtered_networks[0]['id'] filtered_subnets = _get_subnets_by_attrs( network_id=neutron_network_id) for subnet in filtered_subnets: try: subnetpool_id = subnet.get('subnetpool_id', None) _cache_default_subnetpool_ids(app) if subnetpool_id not in app.DEFAULT_POOL_IDS: # If the subnet to be deleted has any port, when some ports # are referring to the subnets in other words, # delete_subnet throws an exception, SubnetInUse that # extends Conflict. This can happen when the multiple # Docker endpoints are created with the same subnet CIDR # and it's totally the normal case. So we'd just log that # and continue to proceed. app.neutron.delete_subnet(subnet['id']) except n_exceptions.Conflict as ex: app.logger.error("Subnet, {0}, is in use. " "Network cant be deleted.".format(subnet['id'])) raise except n_exceptions.NeutronClientException as ex: app.logger.error("Error happened during deleting a " "Neutron subnets: {0}".format(ex)) raise try: app.neutron.delete_network(neutron_network_id) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happened during deleting a " "Neutron network: {0}".format(ex)) raise app.logger.info("Deleted the network with ID {0} successfully" .format(neutron_network_id)) return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.CreateEndpoint', methods=['POST']) def network_driver_create_endpoint(): """Creates new Neutron Subnets and a Port with the given EndpointID. This function takes the following JSON data and delegates the actual endpoint creation to the Neutron client mapping it into Subnet and Port. :: { "NetworkID": string, "EndpointID": string, "Options": { ... }, "Interface": { "Address": string, "AddressIPv6": string, "MacAddress": string } } Then the following JSON response is returned. :: { "Interface": { "Address": string, "AddressIPv6": string, "MacAddress": string } } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#create-endpoint # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.CreateEndpoint" .format(json_data)) jsonschema.validate(json_data, schemata.ENDPOINT_CREATE_SCHEMA) neutron_network_name = json_data['NetworkID'] endpoint_id = json_data['EndpointID'] filtered_networks = _get_networks_by_attrs(name=neutron_network_name) if not filtered_networks: return flask.jsonify({ 'Err': "Neutron network associated with ID {0} doesn't exist." .format(neutron_network_name) }) else: neutron_network_id = filtered_networks[0]['id'] interface = json_data['Interface'] or {} # Workaround for null interface_cidrv4 = interface.get('Address', '') interface_cidrv6 = interface.get('AddressIPv6', '') interface_mac = interface.get('MacAddress', '') if not interface_cidrv4 and not interface_cidrv6: return flask.jsonify({ 'Err': "Interface address v4 or v6 not provided." }) response_interface = _create_or_update_port( neutron_network_id, endpoint_id, interface_cidrv4, interface_cidrv6, interface_mac) return flask.jsonify({'Interface': response_interface}) @app.route('/NetworkDriver.EndpointOperInfo', methods=['POST']) def network_driver_endpoint_operational_info(): return flask.jsonify(constants.SCHEMA['ENDPOINT_OPER_INFO']) @app.route('/NetworkDriver.DeleteEndpoint', methods=['POST']) def network_driver_delete_endpoint(): """Deletes Neutron Subnets and a Port with the given EndpointID. This function takes the following JSON data and delegates the actual endpoint deletion to the Neutron client mapping it into Subnet and Port. :: { "NetworkID": string, "EndpointID": string } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#delete-endpoint # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.DeleteEndpoint" .format(json_data)) jsonschema.validate(json_data, schemata.ENDPOINT_DELETE_SCHEMA) return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/NetworkDriver.Join', methods=['POST']) def network_driver_join(): """Binds a Neutron Port to a network interface attached to a container. This function takes the following JSON data, creates a veth pair, put one end inside of the container and binds another end to the Neutron Port specified in the request. :: { "NetworkID": string, "EndpointID": string, "SandboxKey": string, "Options": { ... } } If the binding is succeeded, the following JSON response is returned.:: { "InterfaceName": { SrcName: string, DstPrefix: string }, "Gateway": string, "GatewayIPv6": string, "StaticRoutes": [{ "Destination": string, "RouteType": int, "NextHop": string, }, ...] } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/remote.md#join # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.Join" .format(json_data)) jsonschema.validate(json_data, schemata.JOIN_SCHEMA) neutron_network_name = json_data['NetworkID'] endpoint_id = json_data['EndpointID'] filtered_networks = _get_networks_by_attrs(name=neutron_network_name) if not filtered_networks: return flask.jsonify({ 'Err': "Neutron network associated with ID {0} doesn't exit." .format(neutron_network_name) }) else: neutron_network_id = filtered_networks[0]['id'] neutron_port_name = utils.get_neutron_port_name(endpoint_id) filtered_ports = _get_ports_by_attrs(name=neutron_port_name) if not filtered_ports: raise exceptions.NoResourceException( "The port doesn't exist for the name {0}" .format(neutron_port_name)) neutron_port = filtered_ports[0] all_subnets = _get_subnets_by_attrs(network_id=neutron_network_id) try: ifname, peer_name, (stdout, stderr) = binding.port_bind( endpoint_id, neutron_port, all_subnets) app.logger.debug(stdout) if stderr: app.logger.error(stderr) except exceptions.VethCreationFailure as ex: with excutils.save_and_reraise_exception(): app.logger.error('Preparing the veth pair was failed: {0}.' .format(ex)) except processutils.ProcessExecutionError: with excutils.save_and_reraise_exception(): app.logger.error( 'Could not bind the Neutron port to the veth endpoint.') join_response = { "InterfaceName": { "SrcName": peer_name, "DstPrefix": config.CONF.binding.veth_dst_prefix }, "StaticRoutes": [] } for subnet in all_subnets: if subnet['ip_version'] == 4: join_response['Gateway'] = subnet.get('gateway_ip', '') else: join_response['GatewayIPv6'] = subnet.get('gateway_ip', '') host_routes = subnet.get('host_routes', []) for host_route in host_routes: static_route = { 'Destination': host_route['destination'] } if host_route.get('nexthop', None): static_route['RouteType'] = constants.TYPES['NEXTHOP'] static_route['NextHop'] = host_route['nexthop'] else: static_route['RouteType'] = constants.TYPES['CONNECTED'] join_response['StaticRoutes'].append(static_route) return flask.jsonify(join_response) @app.route('/NetworkDriver.Leave', methods=['POST']) def network_driver_leave(): """Unbinds a Neutron Port to a network interface attached to a container. This function takes the following JSON data and delete the veth pair corresponding to the given info. :: { "NetworkID": string, "EndpointID": string } """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /NetworkDriver.DeleteEndpoint" .format(json_data)) jsonschema.validate(json_data, schemata.LEAVE_SCHEMA) neutron_network_name = json_data['NetworkID'] endpoint_id = json_data['EndpointID'] filtered_networks = _get_networks_by_attrs(name=neutron_network_name) if not filtered_networks: return flask.jsonify({ 'Err': "Neutron network associated with ID {0} doesn't exit." .format(neutron_network_name) }) else: neutron_port_name = utils.get_neutron_port_name(endpoint_id) filtered_ports = _get_ports_by_attrs(name=neutron_port_name) if not filtered_ports: raise exceptions.NoResourceException( "The port doesn't exist for the name {0}" .format(neutron_port_name)) neutron_port = filtered_ports[0] try: stdout, stderr = binding.port_unbind(endpoint_id, neutron_port) app.logger.debug(stdout) if stderr: app.logger.error(stderr) except processutils.ProcessExecutionError: with excutils.save_and_reraise_exception(): app.logger.error( 'Could not unbind the Neutron port from the veth ' 'endpoint.') except exceptions.VethDeletionFailure: with excutils.save_and_reraise_exception(): app.logger.error('Cleaning the veth pair up was failed.') return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/IpamDriver.GetDefaultAddressSpaces', methods=['POST']) def ipam_get_default_address_spaces(): """Provides the default address spaces for the IPAM. This function is called after the registration of the IPAM driver and the plugin set the returned values as the default address spaces for the IPAM. The address spaces can be configured in the config file. See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#getdefaultaddressspaces # noqa """ app.logger.debug("Received /IpamDriver.GetDefaultAddressSpaces") address_spaces = { 'LocalDefaultAddressSpace': cfg.CONF.local_default_address_space, 'GlobalDefaultAddressSpace': cfg.CONF.global_default_address_space} return flask.jsonify(address_spaces) @app.route('/IpamDriver.RequestPool', methods=['POST']) def ipam_request_pool(): """Creates a new Neutron subnetpool from the given request. This funciton takes the following JSON data and delegates the subnetpool creation to the Neutron client. :: { "AddressSpace": string "Pool": string "SubPool": string "Options": map[string]string "V6": bool } Then the following JSON response is returned. :: { "PoolID": string "Pool": string "Data": map[string]string } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#requestpool # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /IpamDriver.RequestPool" .format(json_data)) jsonschema.validate(json_data, schemata.REQUEST_POOL_SCHEMA) requested_pool = json_data['Pool'] requested_subpool = json_data['SubPool'] v6 = json_data['V6'] pool_id = '' subnet_cidr = '' if requested_pool: app.logger.info("Creating subnetpool with the given pool CIDR") if requested_subpool: cidr = netaddr.IPNetwork(requested_subpool) else: cidr = netaddr.IPNetwork(requested_pool) subnet_cidr = _get_subnet_cidr_using_cidr(cidr) pool_name = utils.get_neutron_subnetpool_name(subnet_cidr) # Check if requested pool already exist pools = _get_subnetpools_by_attrs(name=pool_name) if pools: pool_id = pools[0]['id'] if not pools: new_subnetpool = { 'name': pool_name, 'default_prefixlen': cidr.prefixlen, 'prefixes': [subnet_cidr]} created_subnetpool_response = app.neutron.create_subnetpool( {'subnetpool': new_subnetpool}) pool = created_subnetpool_response['subnetpool'] pool_id = pool['id'] else: if v6: default_pool_list = SUBNET_POOLS_V6 else: default_pool_list = SUBNET_POOLS_V4 pool_name = default_pool_list[0] pools = _get_subnetpools_by_attrs(name=pool_name) if pools: pool = pools[0] pool_id = pool['id'] prefixes = pool['prefixes'] if len(prefixes) > 1: app.logger.warning("More than one prefixes present. " "Picking first one.") cidr = netaddr.IPNetwork(prefixes[0]) subnet_cidr = _get_subnet_cidr_using_cidr(cidr) else: app.logger.error("Default neutron pools not found") req_pool_res = {'PoolID': pool_id, 'Pool': subnet_cidr} return flask.jsonify(req_pool_res) @app.route('/IpamDriver.RequestAddress', methods=['POST']) def ipam_request_address(): """Allocates the IP address in the given request. This function takes the following JSON data and add the given IP address in the allocation_pools attribute of the subnet. :: { "PoolID": string "Address": string "Options": map[string]string } Then the following response is returned. :: { "Address": string "Data": map[string]string } See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#requestaddress # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /IpamDriver.RequestAddress" .format(json_data)) jsonschema.validate(json_data, schemata.REQUEST_ADDRESS_SCHEMA) pool_id = json_data['PoolID'] req_address = json_data['Address'] allocated_address = '' subnet_cidr = '' pool_prefix_len = '' pools = _get_subnetpools_by_attrs(id=pool_id) if pools: pool = pools[0] prefixes = pool['prefixes'] if len(prefixes) > 1: app.logger.warning("More than one prefixes present. Picking " "first one.") for prefix in prefixes: cidr = netaddr.IPNetwork(prefix) pool_prefix_len = str(cidr.prefixlen) subnet_network = str(cidr.network) subnet_cidr = '/'.join([subnet_network, pool_prefix_len]) break else: raise exceptions.NoResourceException( "No subnetpools with id {0} is found." .format(pool_id)) # check if any subnet with matching cidr is present subnets = _get_subnets_by_attrs(cidr=subnet_cidr) if subnets: subnet = subnets[0] # allocating address for container port neutron_network_id = subnet['network_id'] try: port = { 'name': 'kuryr-unbound-port', 'admin_state_up': True, 'network_id': neutron_network_id, } fixed_ips = port['fixed_ips'] = [] fixed_ip = {'subnet_id': subnet['id']} if req_address: fixed_ip['ip_address'] = req_address fixed_ips.append(fixed_ip) created_port_resp = app.neutron.create_port({'port': port}) created_port = created_port_resp['port'] allocated_address = created_port['fixed_ips'][0]['ip_address'] allocated_address = '/'.join( [allocated_address, str(cidr.prefixlen)]) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend during ip allocation on" "Neutron side: {0}".format(ex)) raise else: # Auxiliary address or gw_address is received at network creation time. # This address cannot be reserved with neutron at this time as subnet # is not created yet. In /NetworkDriver.CreateNetwork this address will # be reserved with neutron. allocated_address = '/'.join([req_address, pool_prefix_len]) return flask.jsonify({'Address': allocated_address}) @app.route('/IpamDriver.ReleasePool', methods=['POST']) def ipam_release_pool(): """Deletes a new Neutron subnetpool from the given reuest. This function takes the following JSON data and delegates the subnetpool deletion to the Neutron client. :: { "PoolID": string } Then the following JSON response is returned. :: {} See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#releasepool # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /IpamDriver.ReleasePool" .format(json_data)) jsonschema.validate(json_data, schemata.RELEASE_POOL_SCHEMA) pool_id = json_data['PoolID'] try: app.neutron.delete_subnetpool(pool_id) except n_exceptions.Conflict as ex: app.logger.info("The subnetpool with ID {0} is still in use." " It can't be deleted for now.".format(pool_id)) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend during deleting a " "Neutron subnetpool: {0}".format(ex)) raise return flask.jsonify(constants.SCHEMA['SUCCESS']) @app.route('/IpamDriver.ReleaseAddress', methods=['POST']) def ipam_release_address(): """Deallocates the IP address in the given request. This function takes the following JSON data and remove the given IP address from the allocation_pool attribute of the subnet. :: { "PoolID": string "Address": string } Then the following response is returned. :: {} See the following link for more details about the spec: https://github.com/docker/libnetwork/blob/master/docs/ipam.md#releaseaddress # noqa """ json_data = flask.request.get_json(force=True) app.logger.debug("Received JSON data {0} for /IpamDriver.ReleaseAddress" .format(json_data)) jsonschema.validate(json_data, schemata.RELEASE_ADDRESS_SCHEMA) pool_id = json_data['PoolID'] rel_address = json_data['Address'] filtered_ports = [] pools = _get_subnetpools_by_attrs(id=pool_id) if pools: pool = pools[0] prefixes = pool['prefixes'] for prefix in prefixes: cidr = netaddr.IPNetwork(prefix) subnet_network = str(cidr.network) subnet_cidr = '/'.join([subnet_network, str(cidr.prefixlen)]) else: raise exceptions.NoResourceException( "No subnetpools with id {0} is found." .format(pool_id)) # check if any subnet with matching cidr is present subnets = _get_subnets_by_attrs(cidr=subnet_cidr) if not len(subnets): raise exceptions.NoResourceException( "No subnet is found using pool {0} " "and pool_cidr {1}".format(pool_id, cidr)) subnet = subnets[0] cidr_address = netaddr.IPNetwork(rel_address) rcvd_fixed_ips = [] fixed_ip = {'subnet_id': subnet['id']} fixed_ip['ip_address'] = str(cidr_address.ip) rcvd_fixed_ips.append(fixed_ip) try: filtered_ports = [] all_ports = app.neutron.list_ports() for port in all_ports['ports']: if port['fixed_ips'] == rcvd_fixed_ips: filtered_ports.append(port) for port in filtered_ports: app.neutron.delete_port(port['id']) except n_exceptions.NeutronClientException as ex: app.logger.error("Error happend while fetching and deleting port, " "{0}".format(ex)) raise return flask.jsonify(constants.SCHEMA['SUCCESS']) neutron_client()
# # furl: URL manipulation made simple. # # Arthur Grunseid # grunseid.com # grunseid@gmail.com # # Copyright: LOLOLOL # # License: Build Amazing Things (Unlicense) import abc import urllib import urlparse import warnings class Path(object): """ Represents a URL path comprised of zero or more path segments. http://tools.ietf.org/html/rfc3986#section-3.3 Path parameters are currently not supported. Attributes: segments: List of zero or more path segments comprising this path. If the path string has a trailing '/', the last segment will be '' and self.isdir will be True and self.isfile will be False. An empty segment list represents an empty path, not '/' (though they have the same meaning). isabsolute: Boolean whether or not this is an absolute path or not. An absolute path starts with a '/'. self.isabsolute is False if the path is empty (self.segments == [] and str(path) == ''). """ def __init__(self, path=''): self.segments = [] self.isabsolute = False if path: self.parse(path) def parse(self, path=''): self.isabsolute = (path and path[0] == '/') if isinstance(path, list): segments = url_path_join(*path).split('/') else: segments = path.split('/') if len(segments) > 1 and segments[0] == '': segments.pop(0) self.segments = [urllib.unquote(segment) for segment in segments] def add(self, path=None): """ Add <path> to the existing path. <path> can either be a list of segments or a string to append to the existing path. Returns: <self>. """ if path: if isinstance(path, list): if self.segments[-1] == '': self.segments.pop(-1) self.segments += path else: self.parse(url_path_join(str(self), path)) return self def set(self, path=None): if path: self.parse(path) return self def remove(self, path=None): if path: if path == True: self.parse('') elif isinstance(path, list): self.parse(url_path_remove(str(self), '/'.join(path))) else: self.parse(url_path_remove(str(self), path)) return self @property def isdir(self): """ Returns: True if the path ends on a directory, False otherwise. If True, the last segment is '', representing the trailing '/' of the path. """ return self.segments == [] or (self.segments and self.segments[-1] == '') @property def isfile(self): """ Returns: True if the path ends on a file, False otherwise. If True, the last segment is not '', representing some file as the last segment of the path. """ return not self.isdir def __str__(self): if self.segments and self.isabsolute: return '/'.join([''] + self.segments) return '/'.join(self.segments) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) class PathCompositionInterface(object): """ Abstract class interface for a parent class that contains a Path. """ __metaclass__ = abc.ABCMeta def __init__(self): self._path = Path() @property def path(self): return self._path @property def pathstr(self): return str(self._path) def __setattr__(self, attr, value): """ Returns: True if this attribute is handled and set here, False otherwise. """ if attr == 'path': self._path.parse(value) return True return False class Query(object): """ Represents a URL query comprised of zero or more unique parameters and their respective values. http://tools.ietf.org/html/rfc3986#section-3.4 Repeated URL parameters, like 'a=1&a=2', are deprecated to their first value, 'a=1'. This is a tradeoff in favor of ease of use over the rarely needed flexibility of repeated query parameters. As a result, interacting with query parameters can be performed with strings instead of lists of strings. if furl('...').args['meat'] == 'pumps': ... instead of val = furl('...').args['meat'] if len(val) == 1 and val[0] == 'pumps': ... In the future, support for repeated URL parameters could be added, possibly with a a constructor argument like repeated_params=True. Attributes: params: Dictionary of query parameter key:value pairs. Parameters in self.params are maintained URL decoded, 'a b' not 'a+b'. """ def __init__(self, query=None): self.params = {} if query: self.parse(query) def parse(self, query): if isinstance(query, dict): self.params = {k:urllib.unquote_plus(v) for k, v in query.iteritems()} else: self.params = parse_qs(query) def add(self, args=None): if args: for param, value in args.iteritems(): self.params[param] = value return self def set(self, query=None): if query: self.parse(query) return self def remove(self, query=None): if query == True: self.parse('') elif isinstance(query, list): for key in query: self.params.pop(key, None) return self def __str__(self): params = {str(key):str(val) for key, val in self.params.iteritems()} return urllib.urlencode(params) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) class QueryCompositionInterface(object): """ Abstract class interface for a parent class that contains a Query. """ __metaclass__ = abc.ABCMeta def __init__(self): self._query = Query() @property def query(self): return self._query @property def querystr(self): return str(self._query) @property def args(self): """ Shortcut method to access the query parameters, self._query.params. """ return self._query.params def __setattr__(self, attr, value): """ Returns: True if this attribute is handled and set here, False otherwise. """ if attr == 'args' or attr == 'query': self._query.parse(value) return True return False class Fragment(PathCompositionInterface, QueryCompositionInterface): """ Represents a URL fragment, comprised internally of a Path and Query optionally separated by a '?' character. http://tools.ietf.org/html/rfc3986#section-3.5 Attributes: path: Path object representing the path portion of this fragment. query: Query object representing the query portion of this fragment. separator: Boolean whether or not a '?' separator should be included in the string representation of this fragment. When False, a '?' character will not separate the fragment path from the fragment query in the fragment string. This is useful to build fragments like '#!arg1=val1&arg2=val2', where no separating '?' is desired. """ def __init__(self, fragment=''): PathCompositionInterface.__init__(self) QueryCompositionInterface.__init__(self) self.separator = True if fragment: self.parse(fragment) def parse(self, fragment): self.path.parse('') self.query.parse('') self.separator = True toks = fragment.split('?', 1) if len(toks) == 0: self._path.parse('') self._query.parse('') elif len(toks) == 1: # Does this fragment look like a path or a query? Default to path. if '=' in fragment: # ex: '#variable=value' self._query.parse(fragment) else: # ex: '#supinthisthread' self._path.parse(fragment) else: self._path.parse(toks[0]) self._query.parse(toks[1]) def add(self, path=None, args=None): self.path.add(path) self.query.add(args) return self def set(self, path=None, args=None, separator=None): self.path.set(path) self.query.set(args) if separator == True or separator == False: self.separator = separator return self def remove(self, fragment=None, path=None, args=None): if fragment == True: self.parse('') self.path.remove(path) self.query.remove(args) return self def __setattr__(self, attr, value): if (not PathCompositionInterface.__setattr__(self, attr, value) and not QueryCompositionInterface.__setattr__(self, attr, value)): object.__setattr__(self, attr, value) def __str__(self): path, query = str(self._path), str(self._query) if query and path: return path + ('?' if self.separator else '') + query return path + query def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) class FragmentCompositionInterface(object): """ Abstract class interface for a parent class that contains a Fragment. """ __metaclass__ = abc.ABCMeta def __init__(self): self._fragment = Fragment() @property def fragment(self): return self._fragment @property def fragmentstr(self): return str(self._fragment) def __setattr__(self, attr, value): """ Returns: True if this attribute is handled and set here, False otherwise. """ if attr == 'fragment': self.fragment.parse(value) return True return False class furl(PathCompositionInterface, QueryCompositionInterface, FragmentCompositionInterface): """ Represents a URL comprised of six components scheme://host:port/path?query#fragment Attributes: DEFAULT_PORTS: Map of various URL schemes to their default ports. Scheme strings are lowercase. scheme: URL scheme ('http', 'https', etc). All lowercase. host: URL host (domain, IPv4 address, or IPv6 address), not including port. All lowercase. port: Port. Valid port values are 1-65535, or None meaning no port specified. netloc: Network location. Combined host and port string. path: Path object from PathCompositionInterface. query: Query object from QueryCompositionInterface. fragment: Fragment object from FragmentCompositionInterface. """ DEFAULT_PORTS = { 'http' : 80, 'https' : 443, } def __init__(self, url=None): """ Raises: ValueError on invalid url. """ PathCompositionInterface.__init__(self) QueryCompositionInterface.__init__(self) FragmentCompositionInterface.__init__(self) self.scheme = '' self._host = '' self._port = None if url: self.parse(url) # Raises ValueError on invalid url. def parse(self, url): """ Parse and load a URL. Raises: ValueError on invalid URL (for example malformed IPv6 address or invalid port). """ tokens = urlsplit(url) # Raises ValueError on malformed IPv6 address. self.netloc = tokens.netloc # Raises ValueError. self.scheme = tokens.scheme.lower() if not self.port: self._port = self.DEFAULT_PORTS.get(self.scheme) self.path.parse(tokens.path) self.query.parse(tokens.query) self.fragment.parse(tokens.fragment) return self @property def host(self): return self._host @host.setter def host(self, host): """ Raises: ValueError on malformed IPv6 address. """ urlparse.urlsplit('http://%s/' % host) # Raises ValueError. self._host = host @property def port(self): return self._port @port.setter def port(self, port): """ A port value can 1-65535 or None meaning no port specified. If <port> is None and self.scheme is a known scheme in self.DEFAULT_PORTS, the default port value from self.DEFAULT_PORTS will be used. Raises: ValueError on invalid port. """ if port is None: self._port = self.DEFAULT_PORTS.get(self.scheme) elif isvalidport(port): self._port = int(str(port)) else: raise ValueError("Invalid port: '%s'" % port) @property def netloc(self): netloc = self.host if self.port and self.port != self.DEFAULT_PORTS.get(self.scheme): netloc = '%s:%i' % (self.host, self.port) return netloc @netloc.setter def netloc(self, netloc): """ Params: netloc: Network location string, like 'google.com' or 'google.com:99'. Raises: ValueError on invalid port or malformed IPv6 address. """ # Raises ValueError on malformed IPv6 addresses. urlparse.urlsplit('http://%s/' % netloc) host = port = None if ':' in netloc: # IPv6 address literal. if ']' in netloc: colonpos, bracketpos = netloc.rfind(':'), netloc.rfind(']') if colonpos > bracketpos and colonpos != bracketpos + 1: raise ValueError("Invalid netloc: '%s'" % netloc) elif colonpos > bracketpos and colonpos == bracketpos + 1: host, port = netloc.rsplit(':', 1) else: host = netloc.lower() else: host, port = netloc.rsplit(':', 1) host = host.lower() else: host = netloc.lower() # Avoid side effects by assigning self.port before self.host so that if an # exception is raised when assigning self.port self.host isn't updated. self.port = port # Raises ValueError on invalid port. self.host = host @property def url(self): return str(self) @url.setter def url(self, url): return self._parse(url) def add(self, args=None, path=None, fragment_path=None, fragment_args=None, query_params=None): """ Add components to a URL and return this furl instance, <self>. Existing URL parameters that conflict with values to be added in <args> or <query_params> will be overwritten with the new values in <args> or <query_params>. For example furl('http://www.google.com/?a=OLD&b=b').add(params={'a':'NEW', 'c':'c'}) will overwrite the old value of parameter 'a' with the new value of parameter 'a' provided in <args>. The resulting URL would be 'http://www.google.com/?a=NEW&b=b&c=c' If both <args> and <query_params> are provided, a UserWarning is raised because their values could overlap and thus potentially conflict. If their values conflict, <query_params> takes precedence over <args>. Parameters: args: Shortcut for <query_params>. path: A list of path segments to add to the existing path segments, or a path string to join with the existing path string. query_params: A dictionary of query keys and values to add to the query. fragment_path: A list of path segments to add to the existing fragment path segments, or a path string to join with the existing fragment path string. fragment_args: A dictionary of query keys and values to add to the fragment's query. Returns: <self>. """ if args and query_params: warnstr = ('Possible parameter overlap: both <args> and <query_params>' 'provided. See furl.add() documentation for more details.') warnings.warn(warnstr, UserWarning) self.path.add(path) self.query.add(args) self.query.add(query_params) self.fragment.add(path=fragment_path, args=fragment_args) return self def set(self, args=None, path=None, fragment=None, scheme=None, netloc=None, fragment_path=None, fragment_args=None, fragment_separator=None, host=None, port=None, query=None, query_params=None): """ Set components of a url and return this furl instance, <self>. If any overlapping, and hence possibly conflicting, parameters are provided, appropriate UserWarning's will be raised. The groups of parameters that could potentially overlap are <netloc> and (<host> or <port>) <fragment> and (<fragment_path> and/or <fragment_args>) any two or all of <query>, <args>, and/or <query_params> In all of the above groups, the latter parameter(s) take precedence over the earlier parameter(s). So, for example furl('http://google.com/').set(netloc='yahoo.com:99', host='bing.com', port=40) will result in a UserWarning being raised and the url becoming 'http://bing.com:40/' not 'http://yahoo.com:99/ Parameters: args: Shortcut for query_params. path: A list of path segments or a path string to adopt. fragment: Fragment string to adopt. scheme: Scheme string to adopt. netloc: Network location string to adopt. query: Query string to adopt. query_params: A dictionary of query keys and values to adopt. fragment_path: A list of path segments to adopt for the fragment's path or a path string to adopt as the fragment's path. fragment_args: A dictionary of query keys and values for the fragment's query to adopt. fragment_separator: Boolean whether or not there should be a '?' separator between the fragment path and fragment query. host: Host string to adopt. port: Port number to adopt. Raises: ValueError on invalid port. UserWarning if <netloc> and (<host> and/or <port>) are provided. UserWarning if <query>, <args>, and/or <query_params> are provided. UserWarning if <fragment> and (<fragment_path>, <fragment_args>, and/or <fragment_separator>) are provided. Returns: <self>. """ if netloc and (host or port): warnstr = ('Possible parameter overlap: <netloc> and <host> and/or ' '<port> provided. See furl.set() documentation for more ' 'details.') warnings.warn(warnstr, UserWarning) if (args and query) or (query and query_params) or (args and query_params): warnstr = ('Possible parameter overlap: <query>, <args>, and/or' '<query_params> provided. See furl.set() documentation for more' 'details.') warnings.warn(warnstr, UserWarning) if (fragment and (fragment_path or fragment_args or (fragment_separator is not None))): warnstr = ('Possible parameter overlap: <fragment> and (<fragment_path>' 'and/or <fragment_args>) or <fragment> and <fragment_separator>' 'provided. See furl.set() documentation for more details.') warnings.warn(warnstr, UserWarning) # Avoid side effects if exceptions are raised. oldnetloc, oldport = self.netloc, self.port try: if netloc: self.netloc = netloc # Raises ValueError on invalid port or malformed IP. if port: self.port = port # Raises ValueError on invalid port. except ValueError: self.netloc, self.port = oldnetloc, oldport raise if scheme: self.scheme = scheme if host: self.host = host self.path.set(path) self.query.set(query) self.query.set(args) self.query.set(query_params) if fragment: self.fragment.parse(fragment) self.fragment.set(path=fragment_path, args=fragment_args, separator=fragment_separator) return self def remove(self, args=None, path=None, fragment=None, query=None, query_params=None, port=None, fragment_path=None, fragment_args=None): """ Remove components of url and return this furl instance, <self>. Parameters: args: Shortcut for query_params. path: A list of path segments to remove from the end of the existing path segments list, or a path string to remove from the end of the existing path string, or True to remove the path entirely. query: If True, remove the query portion of the URL entirely. query_params: A list of query keys to remove from the query, if they exist. port: If True, remove the port from the network location string, if it exists. fragment: If True, remove the fragment portion of the URL entirely. fragment_path: A list of path segments to remove from the end of the fragment's path segments or a path string to remove from the end of the fragment's path string. fragment_args: A list of query keys to remove from the fragment's query, if they exist. Returns: <self>. """ if port: self.port = None self.path.remove(path) self.query.remove(args) self.query.remove(query) self.fragment.remove(fragment) self.query.remove(query_params) self.fragment.path.remove(fragment_path) self.fragment.query.remove(fragment_args) return self def __setattr__(self, attr, value): if (not PathCompositionInterface.__setattr__(self, attr, value) and not QueryCompositionInterface.__setattr__(self, attr, value) and not FragmentCompositionInterface.__setattr__(self, attr, value)): object.__setattr__(self, attr, value) def __str__(self): tokens = (self.scheme, self.netloc, urllib.quote(self.pathstr), self.querystr, self.fragmentstr) return urlparse.urlunsplit(tokens) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) def parse_qs(query): """ Parse a query string to a dictionary of parameter key:value pairs, removing any duplicate url parameters. I.e. 'a=1&a=2' would become {'a':'1'}. """ return {key:val[0] for key, val in urlparse.parse_qs(query).iteritems()} def urlsplit(url): """ urlparse.urlsplit() doesn't separate the query string from the path for schemes not in the list urlparse.uses_query, but furl should support proper parsing of query strings and paths for any scheme users decide to use (custom schemes, internal schemes, etc). So as a workaround, use 'http', a scheme in urlparse.uses_query, for the purposes of urlparse.urlsplit(), but then revert back to the original scheme provided. Parameters: url: URL string to split. Returns: urlparse.SplitResult tuple subclass (just like urlparse.urlsplit() does) with fields (scheme, netloc, path, query, fragment, username, password, hostname, port). See http://docs.python.org/library/urlparse.html#urlparse.urlsplit for more details. """ def _change_urltoks_scheme(tup, scheme): l = list(tup) l[0] = scheme return tuple(l) toks = urlparse.urlsplit(url) if not toks.scheme or toks.scheme in urlparse.uses_query: return toks original_scheme = toks.scheme httpurl = _change_urltoks_scheme(toks, 'http') toks = urlparse.urlsplit(urlparse.urlunsplit(httpurl)) return urlparse.SplitResult(*_change_urltoks_scheme(toks, original_scheme)) def url_path_join(*args): """ Join multiple URL string paths together. Similar to os.path.join(), but for URL path components. Returns: A URL path combined from all provided paths. """ tokens = [] if args and args[0] and args[0][0] == '/': tokens = [''] for arg in args: tokens += filter(lambda s: s != '', arg.split('/')) if tokens == [''] or (args and ((arg and arg[-1] == '/') or args[-1] == '')): tokens.append('') return '/'.join(tokens) def url_path_remove(original, toremove): """ Removes the <toremove> portion from the end of the path <original>, if it exists. Returns: A URL path string with <toremove> removed from the end of <original>. If <toremove> cannot be removed from the end of <original>, then <original> is returned unmodified. """ extra_slash = False removefrom = original if toremove and toremove[-1] == '/' and original and original[-1] != '/': removefrom = original + '/' elif original and original[-1] == '/' and toremove and toremove[-1] != '/': extra_slash = True removefrom = original[:-1] if toremove == removefrom[-1 * len(toremove):]: ret = removefrom[:len(removefrom) - len(toremove)] if extra_slash and not ret: ret += '/' return ret return original def isvalidport(port): port = str(port) if not port.isdigit() or int(port) == 0 or int(port) > 65535: return False return True Removed dictionary comprehensions for compatibility with Python 2.6 and earlier. # # furl: URL manipulation made simple. # # Arthur Grunseid # grunseid.com # grunseid@gmail.com # # Copyright: LOLOLOL # # License: Build Amazing Things (Unlicense) import abc import urllib import urlparse import warnings class Path(object): """ Represents a URL path comprised of zero or more path segments. http://tools.ietf.org/html/rfc3986#section-3.3 Path parameters are currently not supported. Attributes: segments: List of zero or more path segments comprising this path. If the path string has a trailing '/', the last segment will be '' and self.isdir will be True and self.isfile will be False. An empty segment list represents an empty path, not '/' (though they have the same meaning). isabsolute: Boolean whether or not this is an absolute path or not. An absolute path starts with a '/'. self.isabsolute is False if the path is empty (self.segments == [] and str(path) == ''). """ def __init__(self, path=''): self.segments = [] self.isabsolute = False if path: self.parse(path) def parse(self, path=''): self.isabsolute = (path and path[0] == '/') if isinstance(path, list): segments = url_path_join(*path).split('/') else: segments = path.split('/') if len(segments) > 1 and segments[0] == '': segments.pop(0) self.segments = [urllib.unquote(segment) for segment in segments] def add(self, path=None): """ Add <path> to the existing path. <path> can either be a list of segments or a string to append to the existing path. Returns: <self>. """ if path: if isinstance(path, list): if self.segments[-1] == '': self.segments.pop(-1) self.segments += path else: self.parse(url_path_join(str(self), path)) return self def set(self, path=None): if path: self.parse(path) return self def remove(self, path=None): if path: if path == True: self.parse('') elif isinstance(path, list): self.parse(url_path_remove(str(self), '/'.join(path))) else: self.parse(url_path_remove(str(self), path)) return self @property def isdir(self): """ Returns: True if the path ends on a directory, False otherwise. If True, the last segment is '', representing the trailing '/' of the path. """ return self.segments == [] or (self.segments and self.segments[-1] == '') @property def isfile(self): """ Returns: True if the path ends on a file, False otherwise. If True, the last segment is not '', representing some file as the last segment of the path. """ return not self.isdir def __str__(self): if self.segments and self.isabsolute: return '/'.join([''] + self.segments) return '/'.join(self.segments) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) class PathCompositionInterface(object): """ Abstract class interface for a parent class that contains a Path. """ __metaclass__ = abc.ABCMeta def __init__(self): self._path = Path() @property def path(self): return self._path @property def pathstr(self): return str(self._path) def __setattr__(self, attr, value): """ Returns: True if this attribute is handled and set here, False otherwise. """ if attr == 'path': self._path.parse(value) return True return False class Query(object): """ Represents a URL query comprised of zero or more unique parameters and their respective values. http://tools.ietf.org/html/rfc3986#section-3.4 Repeated URL parameters, like 'a=1&a=2', are deprecated to their first value, 'a=1'. This is a tradeoff in favor of ease of use over the rarely needed flexibility of repeated query parameters. As a result, interacting with query parameters can be performed with strings instead of lists of strings. if furl('...').args['meat'] == 'pumps': ... instead of val = furl('...').args['meat'] if len(val) == 1 and val[0] == 'pumps': ... In the future, support for repeated URL parameters could be added, possibly with a a constructor argument like repeated_params=True. Attributes: params: Dictionary of query parameter key:value pairs. Parameters in self.params are maintained URL decoded, 'a b' not 'a+b'. """ def __init__(self, query=None): self.params = {} if query: self.parse(query) def parse(self, query): if isinstance(query, dict): # py2.7+: {k:urllib.unquote_plus(v) for k, v in query.iteritems()} tmp = dict((k,urllib.unquote_plus(v)) for (k,v) in query.iteritems()) self.params = tmp else: self.params = parse_qs(query) def add(self, args=None): if args: for param, value in args.iteritems(): self.params[param] = value return self def set(self, query=None): if query: self.parse(query) return self def remove(self, query=None): if query == True: self.parse('') elif isinstance(query, list): for key in query: self.params.pop(key, None) return self def __str__(self): # py2.7+: {str(key):str(val) for key, val in self.params.iteritems()} params = dict((str(key),str(val)) for (key,val) in self.params.iteritems()) return urllib.urlencode(params) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) class QueryCompositionInterface(object): """ Abstract class interface for a parent class that contains a Query. """ __metaclass__ = abc.ABCMeta def __init__(self): self._query = Query() @property def query(self): return self._query @property def querystr(self): return str(self._query) @property def args(self): """ Shortcut method to access the query parameters, self._query.params. """ return self._query.params def __setattr__(self, attr, value): """ Returns: True if this attribute is handled and set here, False otherwise. """ if attr == 'args' or attr == 'query': self._query.parse(value) return True return False class Fragment(PathCompositionInterface, QueryCompositionInterface): """ Represents a URL fragment, comprised internally of a Path and Query optionally separated by a '?' character. http://tools.ietf.org/html/rfc3986#section-3.5 Attributes: path: Path object representing the path portion of this fragment. query: Query object representing the query portion of this fragment. separator: Boolean whether or not a '?' separator should be included in the string representation of this fragment. When False, a '?' character will not separate the fragment path from the fragment query in the fragment string. This is useful to build fragments like '#!arg1=val1&arg2=val2', where no separating '?' is desired. """ def __init__(self, fragment=''): PathCompositionInterface.__init__(self) QueryCompositionInterface.__init__(self) self.separator = True if fragment: self.parse(fragment) def parse(self, fragment): self.path.parse('') self.query.parse('') self.separator = True toks = fragment.split('?', 1) if len(toks) == 0: self._path.parse('') self._query.parse('') elif len(toks) == 1: # Does this fragment look like a path or a query? Default to path. if '=' in fragment: # ex: '#variable=value' self._query.parse(fragment) else: # ex: '#supinthisthread' self._path.parse(fragment) else: self._path.parse(toks[0]) self._query.parse(toks[1]) def add(self, path=None, args=None): self.path.add(path) self.query.add(args) return self def set(self, path=None, args=None, separator=None): self.path.set(path) self.query.set(args) if separator == True or separator == False: self.separator = separator return self def remove(self, fragment=None, path=None, args=None): if fragment == True: self.parse('') self.path.remove(path) self.query.remove(args) return self def __setattr__(self, attr, value): if (not PathCompositionInterface.__setattr__(self, attr, value) and not QueryCompositionInterface.__setattr__(self, attr, value)): object.__setattr__(self, attr, value) def __str__(self): path, query = str(self._path), str(self._query) if query and path: return path + ('?' if self.separator else '') + query return path + query def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) class FragmentCompositionInterface(object): """ Abstract class interface for a parent class that contains a Fragment. """ __metaclass__ = abc.ABCMeta def __init__(self): self._fragment = Fragment() @property def fragment(self): return self._fragment @property def fragmentstr(self): return str(self._fragment) def __setattr__(self, attr, value): """ Returns: True if this attribute is handled and set here, False otherwise. """ if attr == 'fragment': self.fragment.parse(value) return True return False class furl(PathCompositionInterface, QueryCompositionInterface, FragmentCompositionInterface): """ Represents a URL comprised of six components scheme://host:port/path?query#fragment Attributes: DEFAULT_PORTS: Map of various URL schemes to their default ports. Scheme strings are lowercase. scheme: URL scheme ('http', 'https', etc). All lowercase. host: URL host (domain, IPv4 address, or IPv6 address), not including port. All lowercase. port: Port. Valid port values are 1-65535, or None meaning no port specified. netloc: Network location. Combined host and port string. path: Path object from PathCompositionInterface. query: Query object from QueryCompositionInterface. fragment: Fragment object from FragmentCompositionInterface. """ DEFAULT_PORTS = { 'http' : 80, 'https' : 443, } def __init__(self, url=None): """ Raises: ValueError on invalid url. """ PathCompositionInterface.__init__(self) QueryCompositionInterface.__init__(self) FragmentCompositionInterface.__init__(self) self.scheme = '' self._host = '' self._port = None if url: self.parse(url) # Raises ValueError on invalid url. def parse(self, url): """ Parse and load a URL. Raises: ValueError on invalid URL (for example malformed IPv6 address or invalid port). """ tokens = urlsplit(url) # Raises ValueError on malformed IPv6 address. self.netloc = tokens.netloc # Raises ValueError. self.scheme = tokens.scheme.lower() if not self.port: self._port = self.DEFAULT_PORTS.get(self.scheme) self.path.parse(tokens.path) self.query.parse(tokens.query) self.fragment.parse(tokens.fragment) return self @property def host(self): return self._host @host.setter def host(self, host): """ Raises: ValueError on malformed IPv6 address. """ urlparse.urlsplit('http://%s/' % host) # Raises ValueError. self._host = host @property def port(self): return self._port @port.setter def port(self, port): """ A port value can 1-65535 or None meaning no port specified. If <port> is None and self.scheme is a known scheme in self.DEFAULT_PORTS, the default port value from self.DEFAULT_PORTS will be used. Raises: ValueError on invalid port. """ if port is None: self._port = self.DEFAULT_PORTS.get(self.scheme) elif isvalidport(port): self._port = int(str(port)) else: raise ValueError("Invalid port: '%s'" % port) @property def netloc(self): netloc = self.host if self.port and self.port != self.DEFAULT_PORTS.get(self.scheme): netloc = '%s:%i' % (self.host, self.port) return netloc @netloc.setter def netloc(self, netloc): """ Params: netloc: Network location string, like 'google.com' or 'google.com:99'. Raises: ValueError on invalid port or malformed IPv6 address. """ # Raises ValueError on malformed IPv6 addresses. urlparse.urlsplit('http://%s/' % netloc) host = port = None if ':' in netloc: # IPv6 address literal. if ']' in netloc: colonpos, bracketpos = netloc.rfind(':'), netloc.rfind(']') if colonpos > bracketpos and colonpos != bracketpos + 1: raise ValueError("Invalid netloc: '%s'" % netloc) elif colonpos > bracketpos and colonpos == bracketpos + 1: host, port = netloc.rsplit(':', 1) else: host = netloc.lower() else: host, port = netloc.rsplit(':', 1) host = host.lower() else: host = netloc.lower() # Avoid side effects by assigning self.port before self.host so that if an # exception is raised when assigning self.port self.host isn't updated. self.port = port # Raises ValueError on invalid port. self.host = host @property def url(self): return str(self) @url.setter def url(self, url): return self._parse(url) def add(self, args=None, path=None, fragment_path=None, fragment_args=None, query_params=None): """ Add components to a URL and return this furl instance, <self>. Existing URL parameters that conflict with values to be added in <args> or <query_params> will be overwritten with the new values in <args> or <query_params>. For example furl('http://www.google.com/?a=OLD&b=b').add(params={'a':'NEW', 'c':'c'}) will overwrite the old value of parameter 'a' with the new value of parameter 'a' provided in <args>. The resulting URL would be 'http://www.google.com/?a=NEW&b=b&c=c' If both <args> and <query_params> are provided, a UserWarning is raised because their values could overlap and thus potentially conflict. If their values conflict, <query_params> takes precedence over <args>. Parameters: args: Shortcut for <query_params>. path: A list of path segments to add to the existing path segments, or a path string to join with the existing path string. query_params: A dictionary of query keys and values to add to the query. fragment_path: A list of path segments to add to the existing fragment path segments, or a path string to join with the existing fragment path string. fragment_args: A dictionary of query keys and values to add to the fragment's query. Returns: <self>. """ if args and query_params: warnstr = ('Possible parameter overlap: both <args> and <query_params>' 'provided. See furl.add() documentation for more details.') warnings.warn(warnstr, UserWarning) self.path.add(path) self.query.add(args) self.query.add(query_params) self.fragment.add(path=fragment_path, args=fragment_args) return self def set(self, args=None, path=None, fragment=None, scheme=None, netloc=None, fragment_path=None, fragment_args=None, fragment_separator=None, host=None, port=None, query=None, query_params=None): """ Set components of a url and return this furl instance, <self>. If any overlapping, and hence possibly conflicting, parameters are provided, appropriate UserWarning's will be raised. The groups of parameters that could potentially overlap are <netloc> and (<host> or <port>) <fragment> and (<fragment_path> and/or <fragment_args>) any two or all of <query>, <args>, and/or <query_params> In all of the above groups, the latter parameter(s) take precedence over the earlier parameter(s). So, for example furl('http://google.com/').set(netloc='yahoo.com:99', host='bing.com', port=40) will result in a UserWarning being raised and the url becoming 'http://bing.com:40/' not 'http://yahoo.com:99/ Parameters: args: Shortcut for query_params. path: A list of path segments or a path string to adopt. fragment: Fragment string to adopt. scheme: Scheme string to adopt. netloc: Network location string to adopt. query: Query string to adopt. query_params: A dictionary of query keys and values to adopt. fragment_path: A list of path segments to adopt for the fragment's path or a path string to adopt as the fragment's path. fragment_args: A dictionary of query keys and values for the fragment's query to adopt. fragment_separator: Boolean whether or not there should be a '?' separator between the fragment path and fragment query. host: Host string to adopt. port: Port number to adopt. Raises: ValueError on invalid port. UserWarning if <netloc> and (<host> and/or <port>) are provided. UserWarning if <query>, <args>, and/or <query_params> are provided. UserWarning if <fragment> and (<fragment_path>, <fragment_args>, and/or <fragment_separator>) are provided. Returns: <self>. """ if netloc and (host or port): warnstr = ('Possible parameter overlap: <netloc> and <host> and/or ' '<port> provided. See furl.set() documentation for more ' 'details.') warnings.warn(warnstr, UserWarning) if (args and query) or (query and query_params) or (args and query_params): warnstr = ('Possible parameter overlap: <query>, <args>, and/or' '<query_params> provided. See furl.set() documentation for more' 'details.') warnings.warn(warnstr, UserWarning) if (fragment and (fragment_path or fragment_args or (fragment_separator is not None))): warnstr = ('Possible parameter overlap: <fragment> and (<fragment_path>' 'and/or <fragment_args>) or <fragment> and <fragment_separator>' 'provided. See furl.set() documentation for more details.') warnings.warn(warnstr, UserWarning) # Avoid side effects if exceptions are raised. oldnetloc, oldport = self.netloc, self.port try: if netloc: self.netloc = netloc # Raises ValueError on invalid port or malformed IP. if port: self.port = port # Raises ValueError on invalid port. except ValueError: self.netloc, self.port = oldnetloc, oldport raise if scheme: self.scheme = scheme if host: self.host = host self.path.set(path) self.query.set(query) self.query.set(args) self.query.set(query_params) if fragment: self.fragment.parse(fragment) self.fragment.set(path=fragment_path, args=fragment_args, separator=fragment_separator) return self def remove(self, args=None, path=None, fragment=None, query=None, query_params=None, port=None, fragment_path=None, fragment_args=None): """ Remove components of url and return this furl instance, <self>. Parameters: args: Shortcut for query_params. path: A list of path segments to remove from the end of the existing path segments list, or a path string to remove from the end of the existing path string, or True to remove the path entirely. query: If True, remove the query portion of the URL entirely. query_params: A list of query keys to remove from the query, if they exist. port: If True, remove the port from the network location string, if it exists. fragment: If True, remove the fragment portion of the URL entirely. fragment_path: A list of path segments to remove from the end of the fragment's path segments or a path string to remove from the end of the fragment's path string. fragment_args: A list of query keys to remove from the fragment's query, if they exist. Returns: <self>. """ if port: self.port = None self.path.remove(path) self.query.remove(args) self.query.remove(query) self.fragment.remove(fragment) self.query.remove(query_params) self.fragment.path.remove(fragment_path) self.fragment.query.remove(fragment_args) return self def __setattr__(self, attr, value): if (not PathCompositionInterface.__setattr__(self, attr, value) and not QueryCompositionInterface.__setattr__(self, attr, value) and not FragmentCompositionInterface.__setattr__(self, attr, value)): object.__setattr__(self, attr, value) def __str__(self): tokens = (self.scheme, self.netloc, urllib.quote(self.pathstr), self.querystr, self.fragmentstr) return urlparse.urlunsplit(tokens) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) def parse_qs(query): """ Parse a query string to a dictionary of parameter key:value pairs, removing any duplicate url parameters. I.e. 'a=1&a=2' would become {'a':'1'}. """ # py2.7+: {key:val[0] for key, val in urlparse.parse_qs(query).iteritems()} return dict((k,v[0]) for (k,v) in urlparse.parse_qs(query).iteritems()) def urlsplit(url): """ urlparse.urlsplit() doesn't separate the query string from the path for schemes not in the list urlparse.uses_query, but furl should support proper parsing of query strings and paths for any scheme users decide to use (custom schemes, internal schemes, etc). So as a workaround, use 'http', a scheme in urlparse.uses_query, for the purposes of urlparse.urlsplit(), but then revert back to the original scheme provided. Parameters: url: URL string to split. Returns: urlparse.SplitResult tuple subclass (just like urlparse.urlsplit() does) with fields (scheme, netloc, path, query, fragment, username, password, hostname, port). See http://docs.python.org/library/urlparse.html#urlparse.urlsplit for more details. """ def _change_urltoks_scheme(tup, scheme): l = list(tup) l[0] = scheme return tuple(l) toks = urlparse.urlsplit(url) if not toks.scheme or toks.scheme in urlparse.uses_query: return toks original_scheme = toks.scheme httpurl = _change_urltoks_scheme(toks, 'http') toks = urlparse.urlsplit(urlparse.urlunsplit(httpurl)) return urlparse.SplitResult(*_change_urltoks_scheme(toks, original_scheme)) def url_path_join(*args): """ Join multiple URL string paths together. Similar to os.path.join(), but for URL path components. Returns: A URL path combined from all provided paths. """ tokens = [] if args and args[0] and args[0][0] == '/': tokens = [''] for arg in args: tokens += filter(lambda s: s != '', arg.split('/')) if tokens == [''] or (args and ((arg and arg[-1] == '/') or args[-1] == '')): tokens.append('') return '/'.join(tokens) def url_path_remove(original, toremove): """ Removes the <toremove> portion from the end of the path <original>, if it exists. Returns: A URL path string with <toremove> removed from the end of <original>. If <toremove> cannot be removed from the end of <original>, then <original> is returned unmodified. """ extra_slash = False removefrom = original if toremove and toremove[-1] == '/' and original and original[-1] != '/': removefrom = original + '/' elif original and original[-1] == '/' and toremove and toremove[-1] != '/': extra_slash = True removefrom = original[:-1] if toremove == removefrom[-1 * len(toremove):]: ret = removefrom[:len(removefrom) - len(toremove)] if extra_slash and not ret: ret += '/' return ret return original def isvalidport(port): port = str(port) if not port.isdigit() or int(port) == 0 or int(port) > 65535: return False return True
"""Manage Network Application files.""" import json import logging import os import re import shutil import tarfile import tempfile import urllib from pathlib import Path from jinja2 import Environment, FileSystemLoader from kytos.utils.client import NAppsClient from kytos.utils.config import KytosConfig log = logging.getLogger(__name__) class NAppsManager: """Deal with NApps at filesystem level and ask Kyco to (un)load NApps.""" def __init__(self, controller=None): """If controller is not informed, the necessary paths must be. If ``controller`` is available, NApps will be (un)loaded at runtime and you don't need to inform the paths. Otherwise, you should inform the required paths for the methods called. Args: controller (kyco.Controller): Controller to (un)load NApps. install_path (str): Folder where NApps should be installed. If None, use the controller's configuration. enabled_path (str): Folder where enabled NApps are stored. If None, use the controller's configuration. """ self._controller = controller self._config = KytosConfig().config self._installed = Path(self._config.get('napps', 'installed_path')) self._enabled = Path(self._config.get('napps', 'enabled_path')) self.user = None self.napp = None def set_napp(self, user, napp): """Set info about NApp. Args: user (str): NApps Server username. napp (str): NApp name. """ self.user = user self.napp = napp @property def napp_id(self): """Identifier of NApp.""" return '/'.join((self.user, self.napp)) @staticmethod def _get_napps(napps_dir): """List of (author, napp_name) found in ``napps_dir``.""" jsons = napps_dir.glob('*/*/kytos.json') return sorted(j.parts[-3:-1] for j in jsons) def get_enabled(self): """Sorted list of (author, napp_name) of enabled napps.""" return self._get_napps(self._enabled) def get_installed(self): """Sorted list of (author, napp_name) of installed napps.""" return self._get_napps(self._installed) def is_installed(self): """Whether a NApp is installed.""" return (self.user, self.napp) in self.get_installed() def get_disabled(self): """Sorted list of (author, napp_name) of disabled napps. The difference of installed and enabled. """ installed = set(self.get_installed()) enabled = set(self.get_enabled()) return sorted(installed - enabled) def get_description(self, user=None, napp=None): """Return the description from kytos.json.""" if user is None: user = self.user if napp is None: napp = self.napp kj = self._installed / user / napp / 'kytos.json' try: with kj.open() as f: meta = json.load(f) return meta['description'] except (FileNotFoundError, json.JSONDecodeError, KeyError): return '' def disable(self): """Disable a NApp if it is enabled.""" enabled = self._enabled / self.user / self.napp try: enabled.unlink() if self._controller is not None: self._controller.unload_napp(self.user, self.napp) except FileNotFoundError: pass # OK, it was already disabled def enable(self): """Enable a NApp if not already enabled. Raises: FileNotFoundError: If NApp is not installed. PermissionError: No filesystem permission to enable NApp. """ enabled = self._enabled / self.user / self.napp installed = self._installed / self.user / self.napp if not installed.is_dir(): raise FileNotFoundError('Install NApp {} first.'.format( self.napp_id)) elif not enabled.exists(): self._check_module(installed.parent) try: # Create symlink enabled.symlink_to(installed) if self._controller is not None: self._controller.load_napp(self.user, self.napp) except FileExistsError: pass # OK, NApp was already enabled except PermissionError: raise PermissionError('Permission error on enabling NApp. Try ' 'with sudo.') def is_enabled(self): """Whether a NApp is enabled.""" return (self.user, self.napp) in self.get_enabled() def uninstall(self): """Delete code inside NApp directory, if existent.""" if self.is_installed(): installed = self._installed / self.user / self.napp if installed.is_symlink(): installed.unlink() else: shutil.rmtree(str(installed)) @staticmethod def valid_name(username): """Check the validity of the given 'name'. The following checks are done: - name starts with a letter - name contains only letters, numbers or underscores """ return username and re.match(r'[a-zA-Z][a-zA-Z0-9_]{2,}$', username) @staticmethod def render_template(templates_path, template_filename, context): """Render Jinja2 template for a NApp structure.""" TEMPLATE_ENV = Environment(autoescape=False, trim_blocks=False, loader=FileSystemLoader(templates_path)) return TEMPLATE_ENV.get_template(template_filename).render(context) @staticmethod def search(pattern): """Search all server NApps matching pattern. Args: pattern (str): Python regular expression. """ def match(napp): """Whether a NApp metadata matches the pattern.""" strings = ['{}/{}'.format(napp['author'], napp['name']), napp['description']] + napp['tags'] return any(pattern.match(string) for string in strings) napps = NAppsClient().get_napps() return [napp for napp in napps if match(napp)] def install_local(self): """Make a symlink in install folder to a local NApp. Raises: FileNotFoundError: If NApp is not found. """ folder = self._get_local_folder() installed = self._installed / self.user / self.napp self._check_module(installed.parent) installed.symlink_to(folder.resolve()) def _get_local_folder(self, root=None): """Return local NApp root folder. Search for kytos.json in _./_ folder and _./user/napp_. Args: root (pathlib.Path): Where to begin searching. Raises: FileNotFoundError: If there is no such local NApp. Return: pathlib.Path: NApp root folder. """ if root is None: root = Path() for folders in ['.'], [self.user, self.napp]: kytos_json = root / Path(*folders) / 'kytos.json' if kytos_json.exists(): return kytos_json.parent raise FileNotFoundError('kytos.json not found.') def install_remote(self): """Download, extract and install NApp.""" package, pkg_folder = None, None try: package = self._download() pkg_folder = self._extract(package) napp_folder = self._get_local_folder(pkg_folder) dst = self._installed / self.user / self.napp self._check_module(dst.parent) shutil.move(str(napp_folder), str(dst)) finally: # Delete temporary files if package: Path(package).unlink() if pkg_folder and pkg_folder.exists(): shutil.rmtree(str(pkg_folder)) def _download(self): """Download NApp package from server. Raises: urllib.error.HTTPError: If download is not successful. Return: str: Downloaded temp filename. """ api = self._config.get('napps', 'uri') uri = urllib.parse.urljoin(api, '/repo/{}/{}-latest.napp'.format( self.user, self.napp)) return urllib.request.urlretrieve(uri)[0] @staticmethod def _extract(filename): """Extract package to a temporary folder. Return: pathlib.Path: Temp dir with package contents. """ tmp = tempfile.mkdtemp(prefix='kytos') with tarfile.open(filename, 'r:xz') as tar: tar.extractall(tmp) return Path(tmp) @classmethod def create_napp(cls): """Bootstrap a basic NApp strucutre for you to develop your NApp. This will create, on the current folder, a clean structure of a NAPP, filling some contents on this structure. """ base = os.environ.get('VIRTUAL_ENV') or '/' templates_path = os.path.join(base, 'etc', 'skel', 'kytos', 'napp-structure', 'author', 'napp') author = None napp_name = None description = None print('--------------------------------------------------------------') print('Welcome to the bootstrap process of your NApp.') print('--------------------------------------------------------------') print('In order to answer both the author name and the napp name,') print('You must follow this naming rules:') print(' - name starts with a letter') print(' - name contains only letters, numbers or underscores') print(' - at least three characters') print('--------------------------------------------------------------') print('') msg = 'Please, insert your NApps Server username: ' while not cls.valid_name(author): author = input(msg) while not cls.valid_name(napp_name): napp_name = input('Please, insert you NApp name: ') msg = 'Please, insert a brief description for your NApp [optional]: ' description = input(msg) if not description: # pylint: disable=W0511 description = '# TODO: <<<< Insert here your NApp description >>>>' context = {'author': author, 'napp': napp_name, 'description': description} #: Creating the directory structure (author/name) os.makedirs(author, exist_ok=True) #: Creating ``__init__.py`` files with open(os.path.join(author, '__init__.py'), 'w'): pass os.makedirs(os.path.join(author, napp_name)) with open(os.path.join(author, napp_name, '__init__.py'), 'w'): pass #: Creating the other files based on the templates templates = os.listdir(templates_path) templates.remove('__init__.py') for tmp in templates: fname = os.path.join(author, napp_name, tmp.rsplit('.template')[0]) with open(fname, 'w') as file: content = cls.render_template(templates_path, tmp, context) file.write(content) msg = '\nCongratulations! Your NApp have been bootsrapped!\nNow you ' msg += 'can go to the directory {}/{} and begin to code your NApp.' print(msg.format(author, napp_name)) print('Have fun!') @staticmethod def _check_module(folder): """Create module folder with empty __init__.py if it doesn't exist. Args: folder (pathlib.Path): Module path. """ if not folder.exists(): folder.mkdir() (folder / '__init__.py').touch() Added upload method on the NAppsManager, with some more accessories methods """Manage Network Application files.""" import json import logging import os import re import shutil import sys import tarfile import tempfile import urllib from pathlib import Path from jinja2 import Environment, FileSystemLoader from kytos.utils.client import NAppsClient from kytos.utils.config import KytosConfig log = logging.getLogger(__name__) class NAppsManager: """Deal with NApps at filesystem level and ask Kyco to (un)load NApps.""" def __init__(self, controller=None): """If controller is not informed, the necessary paths must be. If ``controller`` is available, NApps will be (un)loaded at runtime and you don't need to inform the paths. Otherwise, you should inform the required paths for the methods called. Args: controller (kyco.Controller): Controller to (un)load NApps. install_path (str): Folder where NApps should be installed. If None, use the controller's configuration. enabled_path (str): Folder where enabled NApps are stored. If None, use the controller's configuration. """ self._controller = controller self._config = KytosConfig().config self._installed = Path(self._config.get('napps', 'installed_path')) self._enabled = Path(self._config.get('napps', 'enabled_path')) self.user = None self.napp = None def set_napp(self, user, napp): """Set info about NApp. Args: user (str): NApps Server username. napp (str): NApp name. """ self.user = user self.napp = napp @property def napp_id(self): """Identifier of NApp.""" return '/'.join((self.user, self.napp)) @staticmethod def _get_napps(napps_dir): """List of (author, napp_name) found in ``napps_dir``.""" jsons = napps_dir.glob('*/*/kytos.json') return sorted(j.parts[-3:-1] for j in jsons) def get_enabled(self): """Sorted list of (author, napp_name) of enabled napps.""" return self._get_napps(self._enabled) def get_installed(self): """Sorted list of (author, napp_name) of installed napps.""" return self._get_napps(self._installed) def is_installed(self): """Whether a NApp is installed.""" return (self.user, self.napp) in self.get_installed() def get_disabled(self): """Sorted list of (author, napp_name) of disabled napps. The difference of installed and enabled. """ installed = set(self.get_installed()) enabled = set(self.get_enabled()) return sorted(installed - enabled) def get_description(self, user=None, napp=None): """Return the description from kytos.json.""" if user is None: user = self.user if napp is None: napp = self.napp kj = self._installed / user / napp / 'kytos.json' try: with kj.open() as f: meta = json.load(f) return meta['description'] except (FileNotFoundError, json.JSONDecodeError, KeyError): return '' def disable(self): """Disable a NApp if it is enabled.""" enabled = self._enabled / self.user / self.napp try: enabled.unlink() if self._controller is not None: self._controller.unload_napp(self.user, self.napp) except FileNotFoundError: pass # OK, it was already disabled def enable(self): """Enable a NApp if not already enabled. Raises: FileNotFoundError: If NApp is not installed. PermissionError: No filesystem permission to enable NApp. """ enabled = self._enabled / self.user / self.napp installed = self._installed / self.user / self.napp if not installed.is_dir(): raise FileNotFoundError('Install NApp {} first.'.format( self.napp_id)) elif not enabled.exists(): self._check_module(installed.parent) try: # Create symlink enabled.symlink_to(installed) if self._controller is not None: self._controller.load_napp(self.user, self.napp) except FileExistsError: pass # OK, NApp was already enabled except PermissionError: raise PermissionError('Permission error on enabling NApp. Try ' 'with sudo.') def is_enabled(self): """Whether a NApp is enabled.""" return (self.user, self.napp) in self.get_enabled() def uninstall(self): """Delete code inside NApp directory, if existent.""" if self.is_installed(): installed = self._installed / self.user / self.napp if installed.is_symlink(): installed.unlink() else: shutil.rmtree(str(installed)) @staticmethod def valid_name(username): """Check the validity of the given 'name'. The following checks are done: - name starts with a letter - name contains only letters, numbers or underscores """ return username and re.match(r'[a-zA-Z][a-zA-Z0-9_]{2,}$', username) @staticmethod def render_template(templates_path, template_filename, context): """Render Jinja2 template for a NApp structure.""" TEMPLATE_ENV = Environment(autoescape=False, trim_blocks=False, loader=FileSystemLoader(templates_path)) return TEMPLATE_ENV.get_template(template_filename).render(context) @staticmethod def search(pattern): """Search all server NApps matching pattern. Args: pattern (str): Python regular expression. """ def match(napp): """Whether a NApp metadata matches the pattern.""" strings = ['{}/{}'.format(napp['author'], napp['name']), napp['description']] + napp['tags'] return any(pattern.match(string) for string in strings) napps = NAppsClient().get_napps() return [napp for napp in napps if match(napp)] def install_local(self): """Make a symlink in install folder to a local NApp. Raises: FileNotFoundError: If NApp is not found. """ folder = self._get_local_folder() installed = self._installed / self.user / self.napp self._check_module(installed.parent) installed.symlink_to(folder.resolve()) def _get_local_folder(self, root=None): """Return local NApp root folder. Search for kytos.json in _./_ folder and _./user/napp_. Args: root (pathlib.Path): Where to begin searching. Raises: FileNotFoundError: If there is no such local NApp. Return: pathlib.Path: NApp root folder. """ if root is None: root = Path() for folders in ['.'], [self.user, self.napp]: kytos_json = root / Path(*folders) / 'kytos.json' if kytos_json.exists(): return kytos_json.parent raise FileNotFoundError('kytos.json not found.') def install_remote(self): """Download, extract and install NApp.""" package, pkg_folder = None, None try: package = self._download() pkg_folder = self._extract(package) napp_folder = self._get_local_folder(pkg_folder) dst = self._installed / self.user / self.napp self._check_module(dst.parent) shutil.move(str(napp_folder), str(dst)) finally: # Delete temporary files if package: Path(package).unlink() if pkg_folder and pkg_folder.exists(): shutil.rmtree(str(pkg_folder)) def _download(self): """Download NApp package from server. Raises: urllib.error.HTTPError: If download is not successful. Return: str: Downloaded temp filename. """ api = self._config.get('napps', 'uri') uri = urllib.parse.urljoin(api, '/repo/{}/{}-latest.napp'.format( self.user, self.napp)) return urllib.request.urlretrieve(uri)[0] @staticmethod def _extract(filename): """Extract package to a temporary folder. Return: pathlib.Path: Temp dir with package contents. """ tmp = tempfile.mkdtemp(prefix='kytos') with tarfile.open(filename, 'r:xz') as tar: tar.extractall(tmp) return Path(tmp) @classmethod def create_napp(cls): """Bootstrap a basic NApp strucutre for you to develop your NApp. This will create, on the current folder, a clean structure of a NAPP, filling some contents on this structure. """ base = os.environ.get('VIRTUAL_ENV') or '/' templates_path = os.path.join(base, 'etc', 'skel', 'kytos', 'napp-structure', 'author', 'napp') author = None napp_name = None description = None print('--------------------------------------------------------------') print('Welcome to the bootstrap process of your NApp.') print('--------------------------------------------------------------') print('In order to answer both the author name and the napp name,') print('You must follow this naming rules:') print(' - name starts with a letter') print(' - name contains only letters, numbers or underscores') print(' - at least three characters') print('--------------------------------------------------------------') print('') msg = 'Please, insert your NApps Server username: ' while not cls.valid_name(author): author = input(msg) while not cls.valid_name(napp_name): napp_name = input('Please, insert you NApp name: ') msg = 'Please, insert a brief description for your NApp [optional]: ' description = input(msg) if not description: # pylint: disable=W0511 description = '# TODO: <<<< Insert here your NApp description >>>>' context = {'author': author, 'napp': napp_name, 'description': description} #: Creating the directory structure (author/name) os.makedirs(author, exist_ok=True) #: Creating ``__init__.py`` files with open(os.path.join(author, '__init__.py'), 'w'): pass os.makedirs(os.path.join(author, napp_name)) with open(os.path.join(author, napp_name, '__init__.py'), 'w'): pass #: Creating the other files based on the templates templates = os.listdir(templates_path) templates.remove('__init__.py') for tmp in templates: fname = os.path.join(author, napp_name, tmp.rsplit('.template')[0]) with open(fname, 'w') as file: content = cls.render_template(templates_path, tmp, context) file.write(content) msg = '\nCongratulations! Your NApp have been bootsrapped!\nNow you ' msg += 'can go to the directory {}/{} and begin to code your NApp.' print(msg.format(author, napp_name)) print('Have fun!') @staticmethod def _check_module(folder): """Create module folder with empty __init__.py if it doesn't exist. Args: folder (pathlib.Path): Module path. """ if not folder.exists(): folder.mkdir() (folder / '__init__.py').touch() def build_napp_package(napp_identifier): """Builds the .napp file to be sent to the napps server. Args: napp_identifier (str): Identifier formatted as <author>/<napp_name> Return: file_payload (binary): The binary representation of the napp package that will be POSTed to the napp server. """ ignored_extensions = ['.swp', '.pyc', '.napp'] ignored_dirs = ['__pycache__'] files = os.listdir() for filename in files: if os.path.isfile(filename) and '.' in filename and \ filename.rsplit('.', 1)[1] in ignored_extensions: files.remove(filename) elif os.path.isdir(filename) and filename in ignored_dirs: files.remove(filename) # Create the '.napp' package napp_file = tarfile.open(napp_identifier + '.napp', 'x:xz') [napp_file.add(f) for f in files] napp_file.close() # Get the binary payload of the package file_payload = open(napp_identifier + '.napp', 'rb') # remove the created package from the filesystem os.remove(napp_identifier + '.napp') return file_payload def create_metadata(self, *args, **kwargs): """Generate the metadata to send the napp package.""" json_filename = kwargs.get('json_filename', 'kytos.json') readme_filename = kwargs.get('readme_filename', 'README.rst') ignore_json = kwargs.get('ignore_json', False) metadata = {} if not ignore_json: try: with open(json_filename) as json_file: metadata = json.load(json_file) except FileNotFoundError: print("ERROR: Could not access kytos.json file.") sys.exit(1) try: with open(readme_filename) as readme_file: metadata['readme'] = readme_file.read() except FileNotFoundError: metadata['readme'] = '' return metadata def upload(self, *args, **kwargs): metadata = self.create_metadata(*args, **kwargs) package = self.build_napp_package(metadata['name']) KytosClient().upload_napp(metadata, package)
from typing import Iterable from re import compile from collections import namedtuple from subprocess import getoutput import click PREFIX = 'test' SUFFIX = "g2sd" NAME_RE = compile("menuentry '(?P<name>[\w\d\W\D]*)' -") KERNEL_RE = compile("linux(?:[\t ]*)(?P<kernel>.*) root=(?P<root>[\w\d\-=\/]*)") INIT_RE = compile("initrd(?:[\t ])(?P<initrd>.*)") MenuEntry = namedtuple('MenuEntry', 'name kernel root initrd') def gen_menu_entries(input: Iterable[str]) -> Iterable[MenuEntry]: args = [] for num, line in enumerate(input): try: line = line.strip() if line.startswith('menuentry'): if args: args = [] name = NAME_RE.findall(line) args.extend(name) elif line.startswith("linux"): all = KERNEL_RE.findall(line) args.extend(all[0]) elif line.startswith("initrd"): init = INIT_RE.findall(line) args.extend(init) yield MenuEntry(*args) args = [] except Exception as ex: print(args, ex) break def convert_root_entry(root_str: str) -> str: if root_str.startswith('UUID'): _, uuid = root_str.split('=') cmd = "blkid -t %s" % root_str elif root_str.startswith("PARTUUID"): return root_str else: cmd = "blkid %s" % root_str blkid_out = getoutput(cmd) partuuid_str = blkid_out.split(' ')[-1] partuuid_str = partuuid_str.replace('"', '') return partuuid_str def menuentry_to_systemd(me: MenuEntry) -> str: partuuid = convert_root_entry(me.root) return "title %s\nlinux %s\ninitrd %s\noptions %s" % (me.name, me.kernel, me.initrd, partuuid) @click.command() @click.argument("grub_file") @click.argument("path") def cmd(grub_file: str, path: str): with open(grub_file, "r") as file: grub = file.read().splitlines() for index, me in enumerate(gen_menu_entries(grub)): with open(path + f'/loaders/entries/{index}_{SUFFIX}.conf', 'w+') as file: file.write(menuentry_to_systemd(me)) if __name__ == "__main__": cmd() Update help information and use typing.namedtuple from typing import Iterable, NamedTuple from re import compile from collections import namedtuple from subprocess import getoutput import click PREFIX = 'test' SUFFIX = "g2sd" NAME_RE = compile("menuentry '(?P<name>[\w\d\W\D]*)' -") KERNEL_RE = compile("linux(?:[\t ]*)(?P<kernel>.*) root=(?P<root>[\w\d\-=\/]*)") INIT_RE = compile("initrd(?:[\t ])(?P<initrd>.*)") #MenuEntry = namedtuple('MenuEntry', 'name kernel root initrd') class MenuEntry(NamedTuple): name: str kernel: str root: str initrd: str def gen_menu_entries(input: Iterable[str]) -> Iterable[MenuEntry]: args = [] for num, line in enumerate(input): try: line = line.strip() if line.startswith('menuentry'): if args: args = [] name = NAME_RE.findall(line) args.extend(name) elif line.startswith("linux"): all = KERNEL_RE.findall(line) args.extend(all[0]) elif line.startswith("initrd"): init = INIT_RE.findall(line) args.extend(init) yield MenuEntry(*args) args = [] except Exception as ex: print(args, ex) break def convert_root_entry(root_str: str) -> str: if root_str.startswith('UUID'): _, uuid = root_str.split('=') cmd = "blkid -t %s" % root_str elif root_str.startswith("PARTUUID"): return root_str else: cmd = "blkid %s" % root_str blkid_out = getoutput(cmd) partuuid_str = blkid_out.split(' ')[-1] partuuid_str = partuuid_str.replace('"', '') return partuuid_str def menuentry_to_systemd(me: MenuEntry) -> str: partuuid = convert_root_entry(me.root) return "title %s\nlinux %s\ninitrd %s\noptions %s" % (me.name, me.kernel, me.initrd, partuuid) @click.command(help="Convert your grub.cfg bootloader entries into systemd-boot loaders. GRUB_FILE is usually located in /boot/grub and your ESP_PATH is usually /boot.") @click.argument("grub_file", type=click.Path(dir_okay=False, exists=True, readable=True)) @click.argument("esp_path", type=click.Path(dir_okay=True, exists=True, writable=True)) def cmd(grub_file: str, path: str): with open(grub_file, "r") as file: grub = file.read().splitlines() for index, me in enumerate(gen_menu_entries(grub)): with open(path + f'/loaders/entries/{index}_{SUFFIX}.conf', 'w+') as file: file.write(menuentry_to_systemd(me)) if __name__ == "__main__": cmd()
"""Utilities for Lambda functions deployed using humilis.""" import base64 from datetime import datetime from dateutil import tz import json import logging import os import traceback import urllib2 import uuid import boto3 from botocore.exceptions import ClientError import raven logger = logging.getLogger() logger.setLevel(logging.INFO) class CriticalError(Exception): def __init__(self, exception): self.__exception = exception def __str__(self): return str(self.__exception) class StateTableError(Exception): pass class ErrorStreamError(Exception): pass class RequiresStreamNameError(Exception): pass class BadKinesisEventError(Exception): pass def _secrets_table_name(environment=None, stage=None): """The name of the secrets table associated to a humilis deployment.""" if environment is None: environment = os.environ.get("HUMILIS_ENVIRONMENT") if stage is None: stage = os.environ.get("HUMILIS_STAGE") if environment: if stage: return "{environment}-{stage}-secrets".format(**locals()) else: return "{environment}-secrets".format(**locals()) def _state_table_name(environment=None, layer=None, stage=None): """The name of the state table associated to a humilis deployment.""" if environment is None: # For backwards compatiblity environment = os.environ.get("HUMILIS_ENVIRONMENT") if layer is None: layer = os.environ.get("HUMILIS_LAYER") if stage is None: stage = os.environ.get("HUMILIS_STAGE") if environment: if stage: return "{environment}-{layer}-{stage}-state".format( **locals()) else: return "{environment}-{layer}-state".format(**locals()) def get_secret(key, environment=None, stage=None, namespace=None): """Retrieves a secret from the secrets vault.""" # Get the encrypted secret from DynamoDB table_name = _secrets_table_name(environment=environment, stage=stage) if namespace: key = "{}:{}".format(namespace, key) if table_name is None: logger.warning("Can't produce secrets table name: unable to retrieve " "secret '{}'".format(key)) return client = boto3.client('dynamodb') try: logger.info("Retriving key '{}' from table '{}'".format( key, table_name)) encrypted = client.get_item( TableName=table_name, Key={'id': {'S': key}}).get('Item', {}).get('value', {}).get('B') except ClientError: logger.info("DynamoDB error when retrieving secret '{}'".format(key)) traceback.print_exc() return if encrypted is None: return # Decrypt using KMS client = boto3.client('kms') try: value = client.decrypt(CiphertextBlob=encrypted)['Plaintext'].decode() except ClientError: logger.error("KMS error when trying to decrypt secret") traceback.print_exc() return try: value = json.loads(value) except (TypeError, ValueError): # It's ok, the client should know how to deal with the value pass return value def get_state(key, namespace=None, table_name=None, environment=None, layer=None, stage=None, shard_id=None, consistent=None, deserializer=json.loads): """Gets a state value from the state table.""" if consistent is None: consistent = True if table_name is None: table_name = _state_table_name(environment=environment, layer=layer, stage=stage) if not table_name: logger.warning("Can't produce state table name: unable to retrieve " "state item '{}'".format(key)) return dynamodb = boto3.resource("dynamodb") table = dynamodb.Table(table_name) logger.info("Getting key '{}' from table '{}'".format(key, table_name)) try: if namespace: key = "{}:{}".format(namespace, key) if shard_id: key = "{}:{}".format(shard_id, key) value = table.get_item( Key={"id": key}, ConsistentRead=consistent).get( "Item", {}).get("value") except ClientError: logger.warning("DynamoDB error when retrieving key '{}' from table " "'{}'".format(key, table_name)) traceback.print_exc() return try: if deserializer: value = deserializer(value) except (TypeError, ValueError): # It's ok, the client should know how to deal with the value pass return value def set_state(key, value, table_name=None, environment=None, layer=None, stage=None, shard_id=None, namespace=None, serializer=json.dumps): """Sets a state value.""" if table_name is None: table_name = _state_table_name(environment=environment, layer=layer, stage=stage) if not table_name: msg = ("Can't produce state table name: unable to set state " "item '{}'".format(key)) logger.error(msg) raise StateTableError(msg) return dynamodb = boto3.resource("dynamodb") table = dynamodb.Table(table_name) logger.info("Putting {} -> {} in DynamoDB table {}".format(key, value, table_name)) if not isinstance(value, str): # Serialize using json try: value = serializer(value) except TypeError: logger.warning("Unable to json-serialize state '{}".format( key)) # Try to store the value as it is elif serializer: logger.warning("Value is already a string: not serializing") if namespace: key = "{}:{}".format(namespace, key) if shard_id: key = "{}:{}".format(shard_id, key) resp = table.put_item(Item={"id": key, "value": value}) logger.info("Response from DynamoDB: '{}'".format(resp)) return resp def send_to_delivery_stream(events, stream_name): """Sends a list of events to a Firehose delivery stream.""" records = [] if stream_name is None: msg = "Must provide the name of the Kinesis stream: None provided" logger.error(msg) raise RequiresStreamNameError(msg) for event in events: if not isinstance(event, str): # csv events already have a newline event = json.dumps(event) + "\n" records.append({"Data": event}) firehose = boto3.client("firehose") logger.info("Delivering {} records to Firehose stream '{}'".format( len(records), stream_name)) resp = firehose.put_record_batch( DeliveryStreamName=stream_name, Records=records) return resp def send_to_kinesis_stream(events, stream_name, partition_key=None, serializer=json.dumps): """Sends events to a Kinesis stream.""" records = [] if stream_name is None: msg = "Must provide the name of the Kinesis stream: None provided" logger.error(msg) raise RequiresStreamNameError(msg) for event in events: if partition_key is None: partition_key_value = str(uuid.uuid4()) elif hasattr(partition_key, "__call__"): partition_key_value = partition_key(event) else: partition_key_value = partition_key if not isinstance(event, str): event = serializer(event) record = {"Data": event, "PartitionKey": partition_key_value} records.append(record) kinesis = boto3.client("kinesis") resp = kinesis.put_records(StreamName=stream_name, Records=records) return resp def sentry_monitor(environment=None, stage=None, layer=None, error_stream=None): if not error_stream: error_stream = {} config = { "environment": environment, "stage": stage, "layer": layer, "mapper": error_stream.get("mapper"), "filter": error_stream.get("filter"), "partition_key": error_stream.get("partition_key"), "error_stream": error_stream.get("kinesis_stream"), "error_delivery_stream": error_stream.get("firehose_delivery_stream")} logger.info("Environment config: {}".format(config)) def decorator(func): """A decorator that adds Sentry monitoring to a Lambda handler.""" def wrapper(event, context): logger.info("Retrieving Sentry DSN for environment '{}' and " "stage '{}'".format(environment, stage)) dsn = get_secret("sentry.dsn", environment=environment, stage=stage) if dsn is None: logger.warning("Unable to retrieve sentry DSN") else: try: client = raven.Client(dsn) except: # We don't want to break the application. Add some retry # logic later. logger.error("Raven client error: skipping Sentry") logger.error(traceback.print_exc()) dsn = None if dsn is not None: client.user_context(context_dict(context)) try: return func(event, context) except CriticalError as err: logger.error(err) if dsn is not None: client.captureException() raise except: if dsn is not None: try: client.captureException() except: logger.error("Raven error capturing exception") logger.error(traceback.print_exc()) raise try: # Send the failed payloads to the errored events to the # error stream and resume if not config["error_stream"] \ and not config["error_delivery_stream"]: msg = ("Error sending errors to Error stream: " "no error streams were provided") logger.error(msg) raise try: # Try unpacking as if it were a Kinesis event payloads, shard_id = unpack_kinesis_event( event, deserializer=None) except KeyError: # If not a Kinesis event, just unpack the records payloads = event["Records"] shard_id = None # Add info about the error so that we are able to # repush the events to the right place after fixing # them. error_payloads = [] fc = config["filter"] mc = config["mapper"] state_args = dict(environment=environment, layer=layer, stage=stage, shard_id=shard_id) for p in payloads: if fc and not fc(p, state_args): continue if mc: mc(p, state_args) payload = { "context": state_args, "payload": p} error_payloads.append(payload) logger.info("Error payloads: {}".format( json.dumps(error_payloads, indent=4))) if not error_payloads: logger.info("All error payloads were filtered out: " "will silently ignore the errors") return if config["error_stream"]: send_to_kinesis_stream( error_payloads, config["error_stream"], partition_key=config["partition_key"]) logger.info("Sent payload to Kinesis stream " "'{}'".format(error_stream)) else: logger.info("No error stream specified: skipping") if config["error_delivery_stream"]: send_to_delivery_stream( error_payloads, config["error_delivery_stream"]) msg = ("Sent payload to Firehose delivery stream " "'{}'").format(config["error_delivery_stream"]) logger.info(msg) else: logger.info("No delivery stream specified: skipping") except: if dsn is not None: try: client.captureException() except: logger.error("Raven error capturing exception") logger.error(traceback.print_exc()) msg = "Error delivering errors to Error stream(s)" logger.error(msg) raise # If we were able to deliver the error events to the error # stream, we silent the exception to prevent blocking the # pipeline. pass return wrapper return decorator def in_aws_lambda(): """Returns true if running in AWS Lambda service.""" return "AWS_SESSION_TOKEN" in os.environ \ and "AWS_SESSION_TOKEN" in os.environ def context_dict(context): """Creates a dict with context information for Sentry.""" d = { "function_name": context.function_name, "function_version": context.function_version, "invoked_function_arn": context.invoked_function_arn, "memory_limit_in_mb": context.memory_limit_in_mb, "aws_request_id": context.aws_request_id, "log_group_name": context.log_group_name, "cognito_identity_id": context.identity.cognito_identity_id, "cognito_identity_pool_id": context.identity.cognito_identity_pool_id} for k, v in os.environ.items(): if k not in {"AWS_SECURITY_TOKEN", "AWS_SESSION_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"}: # Do not log credentials d[k] = v return d def unpack_kinesis_event(kinesis_event, deserializer=None, embed_timestamp=False): """Extracts events (a list of dicts) from a Kinesis event.""" records = kinesis_event["Records"] events = [] shard_ids = set() for rec in records: payload = base64.decodestring(rec["kinesis"]["data"]).decode() shard_ids.add(rec["eventID"].split(":")[0]) if deserializer: try: payload = deserializer(payload) except ValueError: logger.error("Error deserializing Kinesis payload: {}".format( payload)) raise if isinstance(payload, dict) and embed_timestamp: ts = rec["kinesis"].get("approximateArrivalTimestamp") if ts: ts = datetime.fromtimestamp(ts, tz=tz.tzutc()) ts_str = ("{year:04d}-{month:02d}-{day:02d} " "{hour:02d}:{minute:02d}:{second:02d}").format( year=ts.year, month=ts.month, day=ts.day, hour=ts.hour, minute=ts.minute, second=ts.second) else: ts_str = "" payload[embed_timestamp] = ts_str events.append(payload) if len(shard_ids) > 1: msg = "Kinesis event contains records from several shards: {}".format( shard_ids) raise(BadKinesisEventError(msg)) return events, shard_ids.pop() def send_cf_response(event, context, response_status, reason=None, response_data=None, physical_resource_id=None): """Responds to Cloudformation after a create/update/delete operation.""" response_data = response_data or {} reason = reason or "See the details in CloudWatch Log Stream: " + \ context.log_stream_name physical_resource_id = physical_resource_id or context.log_stream_name response_body = json.dumps( { 'Status': response_status, 'Reason': reason, 'PhysicalResourceId': physical_resource_id, 'StackId': event['StackId'], 'RequestId': event['RequestId'], 'LogicalResourceId': event['LogicalResourceId'], 'Data': response_data } ) opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request(event["ResponseURL"], data=response_body) request.add_header("Content-Type", "") request.add_header("Content-Length", len(response_body)) request.get_method = lambda: 'PUT' try: response = opener.open(request) print("Status code: {}".format(response.getcode())) print("Status message: {}".format(response.msg)) return True except urllib2.HTTPError as exc: print("Failed executing HTTP request: {}".format(exc.code)) return False Cleanup """Utilities for Lambda functions deployed using humilis.""" import base64 from datetime import datetime from dateutil import tz import json import logging import os import traceback import urllib2 import uuid import boto3 from botocore.exceptions import ClientError import raven logger = logging.getLogger() logger.setLevel(logging.INFO) class CriticalError(Exception): def __init__(self, exception): self.__exception = exception def __str__(self): return str(self.__exception) class StateTableError(Exception): pass class ErrorStreamError(Exception): pass class RequiresStreamNameError(Exception): pass class BadKinesisEventError(Exception): pass def _secrets_table_name(environment=None, stage=None): """The name of the secrets table associated to a humilis deployment.""" if environment is None: environment = os.environ.get("HUMILIS_ENVIRONMENT") if stage is None: stage = os.environ.get("HUMILIS_STAGE") if environment: if stage: return "{environment}-{stage}-secrets".format(**locals()) else: return "{environment}-secrets".format(**locals()) def _state_table_name(environment=None, layer=None, stage=None): """The name of the state table associated to a humilis deployment.""" if environment is None: # For backwards compatiblity environment = os.environ.get("HUMILIS_ENVIRONMENT") if layer is None: layer = os.environ.get("HUMILIS_LAYER") if stage is None: stage = os.environ.get("HUMILIS_STAGE") if environment: if stage: return "{environment}-{layer}-{stage}-state".format( **locals()) else: return "{environment}-{layer}-state".format(**locals()) def get_secret(key, environment=None, stage=None, namespace=None): """Retrieves a secret from the secrets vault.""" # Get the encrypted secret from DynamoDB table_name = _secrets_table_name(environment=environment, stage=stage) if namespace: key = "{}:{}".format(namespace, key) if table_name is None: logger.warning("Can't produce secrets table name: unable to retrieve " "secret '{}'".format(key)) return client = boto3.client('dynamodb') try: logger.info("Retriving key '{}' from table '{}'".format( key, table_name)) encrypted = client.get_item( TableName=table_name, Key={'id': {'S': key}}).get('Item', {}).get('value', {}).get('B') except ClientError: logger.info("DynamoDB error when retrieving secret '{}'".format(key)) traceback.print_exc() return if encrypted is None: return # Decrypt using KMS client = boto3.client('kms') try: value = client.decrypt(CiphertextBlob=encrypted)['Plaintext'].decode() except ClientError: logger.error("KMS error when trying to decrypt secret") traceback.print_exc() return try: value = json.loads(value) except (TypeError, ValueError): # It's ok, the client should know how to deal with the value pass return value def get_state(key, namespace=None, table_name=None, environment=None, layer=None, stage=None, shard_id=None, consistent=None, deserializer=json.loads): """Gets a state value from the state table.""" if consistent is None: consistent = True if table_name is None: table_name = _state_table_name(environment=environment, layer=layer, stage=stage) if not table_name: logger.warning("Can't produce state table name: unable to retrieve " "state item '{}'".format(key)) return dynamodb = boto3.resource("dynamodb") table = dynamodb.Table(table_name) logger.info("Getting key '{}' from table '{}'".format(key, table_name)) try: if namespace: key = "{}:{}".format(namespace, key) if shard_id: key = "{}:{}".format(shard_id, key) value = table.get_item( Key={"id": key}, ConsistentRead=consistent).get( "Item", {}).get("value") except ClientError: logger.warning("DynamoDB error when retrieving key '{}' from table " "'{}'".format(key, table_name)) traceback.print_exc() return try: if deserializer: value = deserializer(value) except (TypeError, ValueError): # It's ok, the client should know how to deal with the value pass return value def set_state(key, value, table_name=None, environment=None, layer=None, stage=None, shard_id=None, namespace=None, serializer=json.dumps): """Sets a state value.""" if table_name is None: table_name = _state_table_name(environment=environment, layer=layer, stage=stage) if not table_name: msg = ("Can't produce state table name: unable to set state " "item '{}'".format(key)) logger.error(msg) raise StateTableError(msg) return dynamodb = boto3.resource("dynamodb") table = dynamodb.Table(table_name) logger.info("Putting {} -> {} in DynamoDB table {}".format(key, value, table_name)) if not isinstance(value, str): # Serialize using json try: value = serializer(value) except TypeError: logger.warning("Unable to json-serialize state '{}".format( key)) # Try to store the value as it is elif serializer: logger.warning("Value is already a string: not serializing") if namespace: key = "{}:{}".format(namespace, key) if shard_id: key = "{}:{}".format(shard_id, key) resp = table.put_item(Item={"id": key, "value": value}) logger.info("Response from DynamoDB: '{}'".format(resp)) return resp def send_to_delivery_stream(events, stream_name): """Sends a list of events to a Firehose delivery stream.""" records = [] if stream_name is None: msg = "Must provide the name of the Kinesis stream: None provided" logger.error(msg) raise RequiresStreamNameError(msg) for event in events: if not isinstance(event, str): # csv events already have a newline event = json.dumps(event) + "\n" records.append({"Data": event}) firehose = boto3.client("firehose") logger.info("Delivering {} records to Firehose stream '{}'".format( len(records), stream_name)) resp = firehose.put_record_batch( DeliveryStreamName=stream_name, Records=records) return resp def send_to_kinesis_stream(events, stream_name, partition_key=None, serializer=json.dumps): """Sends events to a Kinesis stream.""" records = [] if stream_name is None: msg = "Must provide the name of the Kinesis stream: None provided" logger.error(msg) raise RequiresStreamNameError(msg) for event in events: if partition_key is None: partition_key_value = str(uuid.uuid4()) elif hasattr(partition_key, "__call__"): partition_key_value = partition_key(event) else: partition_key_value = partition_key if not isinstance(event, str): event = serializer(event) record = {"Data": event, "PartitionKey": partition_key_value} records.append(record) kinesis = boto3.client("kinesis") resp = kinesis.put_records(StreamName=stream_name, Records=records) return resp def sentry_monitor(environment=None, stage=None, layer=None, error_stream=None): if not error_stream: error_stream = {} config = { "environment": environment, "stage": stage, "layer": layer, "mapper": error_stream.get("mapper"), "filter": error_stream.get("filter"), "partition_key": error_stream.get("partition_key"), "error_stream": error_stream.get("kinesis_stream"), "error_delivery_stream": error_stream.get("firehose_delivery_stream")} logger.info("Environment config: {}".format(config)) def decorator(func): """A decorator that adds Sentry monitoring to a Lambda handler.""" def wrapper(event, context): logger.info("Retrieving Sentry DSN for environment '{}' and " "stage '{}'".format(environment, stage)) dsn = get_secret("sentry.dsn", environment=environment, stage=stage) if dsn is None: logger.warning("Unable to retrieve sentry DSN") else: try: client = raven.Client(dsn) except: # We don't want to break the application. Add some retry # logic later. logger.error("Raven client error: skipping Sentry") logger.error(traceback.print_exc()) dsn = None if dsn is not None: client.user_context(context_dict(context)) try: return func(event, context) except CriticalError: if dsn is not None: client.captureException() raise except: if dsn is not None: try: client.captureException() except: logger.error("Raven error capturing exception") logger.error(traceback.print_exc()) raise try: # Send the failed payloads to the errored events to the # error stream and resume if not config["error_stream"] \ and not config["error_delivery_stream"]: msg = ("Error sending errors to Error stream: " "no error streams were provided") logger.error(msg) raise try: # Try unpacking as if it were a Kinesis event payloads, shard_id = unpack_kinesis_event( event, deserializer=None) except KeyError: # If not a Kinesis event, just unpack the records payloads = event["Records"] shard_id = None # Add info about the error so that we are able to # repush the events to the right place after fixing # them. error_payloads = [] fc = config["filter"] mc = config["mapper"] state_args = dict(environment=environment, layer=layer, stage=stage, shard_id=shard_id) for p in payloads: if fc and not fc(p, state_args): continue if mc: mc(p, state_args) payload = { "context": state_args, "payload": p} error_payloads.append(payload) logger.info("Error payloads: {}".format( json.dumps(error_payloads, indent=4))) if not error_payloads: logger.info("All error payloads were filtered out: " "will silently ignore the errors") return if config["error_stream"]: send_to_kinesis_stream( error_payloads, config["error_stream"], partition_key=config["partition_key"]) logger.info("Sent payload to Kinesis stream " "'{}'".format(error_stream)) else: logger.info("No error stream specified: skipping") if config["error_delivery_stream"]: send_to_delivery_stream( error_payloads, config["error_delivery_stream"]) msg = ("Sent payload to Firehose delivery stream " "'{}'").format(config["error_delivery_stream"]) logger.info(msg) else: logger.info("No delivery stream specified: skipping") except: if dsn is not None: try: client.captureException() except: logger.error("Raven error capturing exception") logger.error(traceback.print_exc()) msg = "Error delivering errors to Error stream(s)" logger.error(msg) raise # If we were able to deliver the error events to the error # stream, we silent the exception to prevent blocking the # pipeline. pass return wrapper return decorator def in_aws_lambda(): """Returns true if running in AWS Lambda service.""" return "AWS_SESSION_TOKEN" in os.environ \ and "AWS_SESSION_TOKEN" in os.environ def context_dict(context): """Creates a dict with context information for Sentry.""" d = { "function_name": context.function_name, "function_version": context.function_version, "invoked_function_arn": context.invoked_function_arn, "memory_limit_in_mb": context.memory_limit_in_mb, "aws_request_id": context.aws_request_id, "log_group_name": context.log_group_name, "cognito_identity_id": context.identity.cognito_identity_id, "cognito_identity_pool_id": context.identity.cognito_identity_pool_id} for k, v in os.environ.items(): if k not in {"AWS_SECURITY_TOKEN", "AWS_SESSION_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"}: # Do not log credentials d[k] = v return d def unpack_kinesis_event(kinesis_event, deserializer=None, embed_timestamp=False): """Extracts events (a list of dicts) from a Kinesis event.""" records = kinesis_event["Records"] events = [] shard_ids = set() for rec in records: payload = base64.decodestring(rec["kinesis"]["data"]).decode() shard_ids.add(rec["eventID"].split(":")[0]) if deserializer: try: payload = deserializer(payload) except ValueError: logger.error("Error deserializing Kinesis payload: {}".format( payload)) raise if isinstance(payload, dict) and embed_timestamp: ts = rec["kinesis"].get("approximateArrivalTimestamp") if ts: ts = datetime.fromtimestamp(ts, tz=tz.tzutc()) ts_str = ("{year:04d}-{month:02d}-{day:02d} " "{hour:02d}:{minute:02d}:{second:02d}").format( year=ts.year, month=ts.month, day=ts.day, hour=ts.hour, minute=ts.minute, second=ts.second) else: ts_str = "" payload[embed_timestamp] = ts_str events.append(payload) if len(shard_ids) > 1: msg = "Kinesis event contains records from several shards: {}".format( shard_ids) raise(BadKinesisEventError(msg)) return events, shard_ids.pop() def send_cf_response(event, context, response_status, reason=None, response_data=None, physical_resource_id=None): """Responds to Cloudformation after a create/update/delete operation.""" response_data = response_data or {} reason = reason or "See the details in CloudWatch Log Stream: " + \ context.log_stream_name physical_resource_id = physical_resource_id or context.log_stream_name response_body = json.dumps( { 'Status': response_status, 'Reason': reason, 'PhysicalResourceId': physical_resource_id, 'StackId': event['StackId'], 'RequestId': event['RequestId'], 'LogicalResourceId': event['LogicalResourceId'], 'Data': response_data } ) opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request(event["ResponseURL"], data=response_body) request.add_header("Content-Type", "") request.add_header("Content-Length", len(response_body)) request.get_method = lambda: 'PUT' try: response = opener.open(request) print("Status code: {}".format(response.getcode())) print("Status message: {}".format(response.msg)) return True except urllib2.HTTPError as exc: print("Failed executing HTTP request: {}".format(exc.code)) return False
#! /usr/env/python """ Python implementation of ModelGrid, a base class used to create and manage grids for 2D numerical models. Do NOT add new documentation here. Grid documentation is now built in a semi- automated fashion. To modify the text seen on the web, edit the files `docs/text_for_[gridfile].py.txt`. """ import numpy import numpy as np import warnings from time import time import six from six.moves import range from landlab.testing.decorators import track_this_method from landlab.utils import count_repeated_values from landlab.core.utils import argsort_points_by_x_then_y from landlab.utils.decorators import make_return_array_immutable, deprecated from landlab.field import ModelDataFields, ModelDataFieldsMixIn from landlab.field.scalar_data_fields import FieldError from . import grid_funcs as gfuncs from ..core.utils import as_id_array from ..core.utils import add_module_functions_to_class from .decorators import (override_array_setitem_and_reset, return_id_array, return_readonly_id_array) #: Indicates an index is, in some way, *bad*. BAD_INDEX_VALUE = -1 # DEJH thinks the user should be able to override this value if they want # Map names grid elements to the ModelGrid attribute that contains the count # of that element in the grid. _ARRAY_LENGTH_ATTRIBUTES = { 'node': 'number_of_nodes', 'patch': 'number_of_patches', 'link': 'number_of_links', 'corner': 'number_of_corners', 'face': 'number_of_faces', 'cell': 'number_of_cells', 'active_link': 'number_of_active_links', 'active_face': 'number_of_active_faces', 'core_node': 'number_of_core_nodes', 'core_cell': 'number_of_core_cells', } # Fields whose sizes can not change. _SIZED_FIELDS = {'node', 'link', 'patch', 'corner', 'face', 'cell', } # Define the boundary-type codes #: Indicates a node is *core*. CORE_NODE = 0 #: Indicates a boundary node is has a fixed values. FIXED_VALUE_BOUNDARY = 1 #: Indicates a boundary node is has a fixed gradient. FIXED_GRADIENT_BOUNDARY = 2 #: Indicates a boundary node is wrap-around. LOOPED_BOUNDARY = 3 #: Indicates a boundary node is closed CLOSED_BOUNDARY = 4 # Define the link types #: Indicates a link is *active*, and can carry flux ACTIVE_LINK = 0 #: Indicates a link has a fixed (gradient) value, & behaves as a boundary FIXED_LINK = 2 #: Indicates a link is *inactive*, and cannot carry flux INACTIVE_LINK = 4 BOUNDARY_STATUS_FLAGS_LIST = [ FIXED_VALUE_BOUNDARY, FIXED_GRADIENT_BOUNDARY, LOOPED_BOUNDARY, CLOSED_BOUNDARY, ] BOUNDARY_STATUS_FLAGS = set(BOUNDARY_STATUS_FLAGS_LIST) LINK_STATUS_FLAGS_LIST = [ ACTIVE_LINK, FIXED_LINK, INACTIVE_LINK, ] LINK_STATUS_FLAGS = set(LINK_STATUS_FLAGS_LIST) def _sort_points_into_quadrants(x, y, nodes): """Divide x, y points into quadrants. Divide points with locations given in the *x*, and *y* arrays into north, south, east, and west quadrants. Returns nodes contained in quadrants (west, east, north, south). Parameters ---------- x : array_like X-coordinates of points. y : array_like Y-coordinates of points. nodes : array_like Nodes associated with points. Returns ------- tuple of array_like Tuple of nodes in each coordinate. Nodes are grouped as (*east*, *north*, *west*, *south*). Examples -------- >>> import numpy as np >>> from landlab.grid.base import _sort_points_into_quadrants >>> x = np.array([0, 1, 0, -1]) >>> y = np.array([1, 0, -1, 0]) >>> nodes = np.array([1, 2, 3, 4]) >>> _sort_points_into_quadrants(x, y, nodes) (array([2]), array([1]), array([4]), array([3])) """ above_x_axis = y > 0 right_of_y_axis = x > 0 closer_to_y_axis = numpy.abs(y) >= numpy.abs(x) north_nodes = nodes[above_x_axis & closer_to_y_axis] south_nodes = nodes[(~ above_x_axis) & closer_to_y_axis] east_nodes = nodes[right_of_y_axis & (~ closer_to_y_axis)] west_nodes = nodes[(~ right_of_y_axis) & (~ closer_to_y_axis)] return (east_nodes, north_nodes, west_nodes, south_nodes) def _default_axis_names(n_dims): """Name of each axis. Parameters ---------- n_dims : int Number of spatial dimensions. Returns ------- tuple of str Name of each axis. Examples -------- >>> from landlab.grid.base import _default_axis_names >>> _default_axis_names(1) ('x',) >>> _default_axis_names(2) ('y', 'x') >>> _default_axis_names(3) ('z', 'y', 'x') """ _DEFAULT_NAMES = ('z', 'y', 'x') return _DEFAULT_NAMES[- n_dims:] def _default_axis_units(n_dims): """Unit names for each axis. Parameters ---------- n_dims : int Number of spatial dimensions. Returns ------- tuple of str Units of each axis. Examples -------- >>> from landlab.grid.base import _default_axis_units >>> _default_axis_units(1) ('-',) >>> _default_axis_units(2) ('-', '-') >>> _default_axis_units(3) ('-', '-', '-') """ return ('-', ) * n_dims def find_true_vector_from_link_vector_pair(L1, L2, b1x, b1y, b2x, b2y): r"""Separate a pair of links with vector values into x and y components. The concept here is that a pair of adjacent links attached to a node are projections of a 'true' but unknown vector. This function finds and returns the x and y components of this true vector. The trivial case is the situation in which the two links are orthogonal and aligned with the grid axes, in which case the vectors of these two links *are* the x and y components. Parameters ---------- L1, L2 : float Values (magnitudes) associated with the two links b1x, b1y, b2x, b2y : float Unit vectors of the two links Returns ------- ax, ay : float x and y components of the 'true' vector Notes ----- The function does an inverse vector projection. Suppose we have a given 'true' vector :math:`a`, and we want to project it onto two other lines with unit vectors (b1x,b1y) and (b2x,b2y). In the context of Landlab, the 'true' vector is some unknown vector quantity, which might for example represent the local water flow velocity. The lines represent two adjacent links in the grid. Let :math:`\mathbf{a}` be the true vector, :math:`\mathbf{B}` be a different vector with unit vector :math:`\mathbf{b}`, and :math:`L` be the scalar projection of *a* onto *B*. Then, ..math:: L = \mathbf{a} \dot \mathbf{b} = a_x b_x + a_y b_y, where :math:`(a_x,a_y)` are the components of **a** and :math:`(b_x,b_y)` are the components of the unit vector **b**. In this case, we know *b* (the link unit vector), and we want to know the *x* and *y* components of **a**. The problem is that we have one equation and two unknowns (:math:`a_x` and :math:`a_y`). But we can solve this if we have *two* vectors, both of which are projections of **a**. Using the subscripts 1 and 2 to denote the two vectors, we can obtain equations for both :math:`a_x` and :math:`a_y`: ..math:: a_x = L_1 / b_{1x} - a_y b_{1y} / b_{1x} a_y = L_2 / b_{2y} - a_x b_{2x} / b_{2y} Substituting the second into the first, ..math:: a_x = [L_1/b_{1x}-L_2 b_{1y}/(b_{1x} b_{2y})] / [1-b_{1y} b_{2x}/(b_{1x} b_{2y})] Hence, we find the original vector :math:`(a_x,a_y)` from two links with unit vectors :math:`(b_{1x},b_{1y})` and :math:`(b_{2x},b_{2y})` and associated values :math:`L_1` and :math:`L_2`. Note that the above equations require that :math:`b_{1x}>0` and :math:`b_{2y}>0`. If this isn't the case, we invert the order of the two links, which requires :math:`b_{2x}>0` and :math:`b_{1y}>0`. If none of these conditions is met, then we have a degenerate case. Examples -------- The following example represents the active links in a 7-node hexagonal grid, with just one core node. The 'true' vector has a magnitude of 5 units and an orientation of 30 degrees, pointing up and to the right (i.e., the postive-x and postive-y quadrant), so that its vector components are 4 (x) and 3 (y) (in other words, it is a 3-4-5 triangle). The values assigned to L below are the projection of that true vector onto the six link vectors. The algorithm should recover the correct vector component values of 4 and 3. The FOR loop examines each pair of links in turn. >>> import numpy as np >>> from landlab.grid.base import find_true_vector_from_link_vector_pair >>> bx = np.array([0.5, -0.5, -1., -0.5, 1., 0.5]) >>> by = np.array([0.866, 0.866, 0., -0.866, 0., -0.866]) >>> L = np.array([4.6, 0.6, -4., -4.6, 4., -0.6]) >>> for i in range(5): ... ax, ay = find_true_vector_from_link_vector_pair( ... L[i], L[i+1], bx[i], by[i], bx[i+1], by[i+1]) ... round(ax,1), round(ay,1) (4.0, 3.0) (4.0, 3.0) (4.0, 3.0) (4.0, 3.0) (4.0, 3.0) """ assert ((b1x != 0 and b2y != 0) or (b2x != 0 and b1y != 0)), \ 'Improper unit vectors' if b1x != 0. and b2y != 0.: ax = (L1 / b1x - L2 * (b1y / (b1x * b2y))) / \ (1. - (b1y * b2x) / (b1x * b2y)) ay = L2 / b2y - ax * (b2x / b2y) elif b2x != 0. and b1y != 0.: ax = (L2 / b2x - L1 * (b2y / (b2x * b1y))) / \ (1. - (b2y * b1x) / (b2x * b1y)) ay = L1 / b1y - ax * (b1x / b1y) return ax, ay class ModelGrid(ModelDataFieldsMixIn): """Base class for 2D structured or unstructured grids for numerical models. The idea is to have at least two inherited classes, RasterModelGrid and DelaunayModelGrid, that can create and manage grids. To this might be added a GenericModelGrid, which would be an unstructured polygonal grid that doesn't necessarily obey or understand the Delaunay triangulation, but rather simply accepts an input grid from the user. Also a :class:`~.HexModelGrid` for hexagonal. Attributes ---------- at_node : dict-like Values at nodes. at_cell : dict-like Values at cells. at_link : dict-like Values at links. at_face : dict-like Values at faces. at_grid: dict-like Global values Other Parameters ---------------- axis_name : tuple, optional Name of axes axis_units : tuple, optional Units of coordinates """ # Debugging flags (if True, activates some output statements) _DEBUG_VERBOSE = False _DEBUG_TRACK_METHODS = False at_node = {} # : Values defined at nodes at_link = {} # : Values defined at links at_patch = {} # : Values defined at patches at_corner = {} # : Values defined at corners at_face = {} # : Values defined at faces at_cell = {} # : Values defined at cells # : Nodes on the other end of links pointing into a node. _node_inlink_matrix = numpy.array([], dtype=numpy.int32) # : Nodes on the other end of links pointing out of a node. _node_outlink_matrix = numpy.array([], dtype=numpy.int32) def __init__(self, **kwds): super(ModelGrid, self).__init__() self.axis_name = kwds.get('axis_name', _default_axis_names(self.ndim)) self.axis_units = kwds.get( 'axis_units', _default_axis_units(self.ndim)) self._link_length = None self._all_node_distances_map = None self._all_node_azimuths_map = None self._node_unit_vector_sum_x = None self._node_unit_vector_sum_y = None self._link_unit_vec_x = None self._link_unit_vec_y = None self.bc_set_code = 0 # Sort links according to the x and y coordinates of their midpoints. # Assumes 1) node_at_link_tail and node_at_link_head have been # created, and 2) so have node_x and node_y. # self._sort_links_by_midpoint() for loc in _SIZED_FIELDS: size = self.number_of_elements(loc) ModelDataFields.new_field_location(self, loc, size=size) ModelDataFields.new_field_location(self, 'grid', size=1) # for loc in _UNSIZED_FIELDS: # ModelDataFields.new_field_location(self, loc, size=None) ModelDataFields.set_default_group(self, 'node') def _create_link_face_coords(self): """Create x, y coordinates for link-face intersections. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4), 1.) >>> mg.x_of_link array([ 0.5, 1.5, 2.5, 0. , 1. , 2. , 3. , 0.5, 1.5, 2.5, 0. , 1. , 2. , 3. , 0.5, 1.5, 2.5]) >>> mg.y_of_link array([ 0. , 0. , 0. , 0.5, 0.5, 0.5, 0.5, 1. , 1. , 1. , 1.5, 1.5, 1.5, 1.5, 2. , 2. , 2. ]) >>> np.all(mg.x_of_link[mg.link_at_face] == mg.x_of_face) True >>> np.all(mg.y_of_link[mg.link_at_face] == mg.y_of_face) True """ self._link_x = (self.x_of_node[self.node_at_link_head] + self.x_of_node[self.node_at_link_tail])/2. self._link_y = (self.y_of_node[self.node_at_link_head] + self.y_of_node[self.node_at_link_tail])/2. def _create_neighbor_list(self, **kwds): """Create list of neighbor node IDs. Creates a list of IDs of neighbor nodes for each node, as a 2D array. Only record neighbor nodes that are on the other end of an *active* link. Nodes attached to *inactive* links or neighbor nodes that would be outside of the grid are given an ID of :const:`~landlab.grid.base.BAD_INDEX_VALUE`. Neighbors are ordered as [*right*, *top*, *left*, *bottom*]. """ self._active_neighbor_nodes = self.neighbors_at_node.copy() self._active_neighbor_nodes[ self.active_link_dirs_at_node == 0] = BAD_INDEX_VALUE self.neighbor_list_created = True return self._active_neighbor_nodes @classmethod def from_file(cls, file_like): params = load_params(file_like) return cls.from_dict(params) @classmethod def from_dict(cls, params): raise NotImplementedError('from_dict') def _initialize(self): raise NotImplementedError('_initialize') @property def ndim(self): """Number of spatial dimensions of the grid. LLCATS: GINF """ return 2 def _setup_nodes(self): """Set up the node id array.""" self._nodes = np.arange(self.number_of_nodes, dtype=int) return self._nodes @property @make_return_array_immutable def nodes(self): """Get node ids for the grid. Examples -------- >>> from landlab import RadialModelGrid >>> mg = RadialModelGrid(num_shells=1) >>> mg.nodes array([0, 1, 2, 3, 4, 5, 6]) LLCATS: NINF """ try: return self._nodes except AttributeError: return self._setup_nodes() @property @override_array_setitem_and_reset('_update_links_nodes_cells_to_new_BCs') def status_at_node(self): """Get array of the boundary status for each node. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> from landlab import FIXED_GRADIENT_BOUNDARY, FIXED_LINK >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node.reshape((4, 5)) array([[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]], dtype=int8) >>> np.any(mg.status_at_link == FIXED_LINK) False >>> mg.status_at_node[mg.nodes_at_left_edge] = FIXED_GRADIENT_BOUNDARY >>> mg.status_at_node.reshape((4, 5)) array([[2, 1, 1, 1, 1], [2, 0, 0, 0, 1], [2, 0, 0, 0, 1], [2, 1, 1, 1, 1]], dtype=int8) >>> np.any(mg.status_at_link == FIXED_LINK) # links auto-update True LLCATS: NINF BC """ return self._node_status @status_at_node.setter def status_at_node(self, new_status): """Set the array of node boundary statuses.""" self._node_status[:] = new_status[:] self._update_links_nodes_cells_to_new_BCs() @property @make_return_array_immutable def neighbors_at_node(self): """Get neighboring nodes. Examples -------- >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> grid = RasterModelGrid((4, 3)) >>> neighbors = grid.neighbors_at_node.copy() >>> neighbors[neighbors == BAD_INDEX_VALUE] = -1 >>> neighbors # doctest: +NORMALIZE_WHITESPACE array([[ 1, 3, -1, -1], [ 2, 4, 0, -1], [-1, 5, 1, -1], [ 4, 6, -1, 0], [ 5, 7, 3, 1], [-1, 8, 4, 2], [ 7, 9, -1, 3], [ 8, 10, 6, 4], [-1, 11, 7, 5], [10, -1, -1, 6], [11, -1, 9, 7], [-1, -1, 10, 8]]) LLCATS: NINF CONN """ return self._neighbors_at_node @property @return_readonly_id_array def active_neighbors_at_node(self): """Get list of neighbor node IDs. Return lists of neighbor nodes, where the neighbor is connected by an active link. For each node, the list gives neighbor ids as [right, top, left, bottom]. Nodes at the end of inactive links or nodes in missing positions get BAD_INDEX_VALUE. Examples -------- >>> from landlab.grid.base import BAD_INDEX_VALUE as X >>> from landlab import RasterModelGrid, HexModelGrid, CLOSED_BOUNDARY >>> rmg = RasterModelGrid((4, 5)) >>> np.array_equal(rmg.active_neighbors_at_node[[-1, 6, 2]], ... [[X, X, X, X], [ 7, 11, 5, 1], [X, 7, X, X]]) True >>> rmg.active_neighbors_at_node[7] array([ 8, 12, 6, 2]) >>> rmg.active_neighbors_at_node[2] array([-1, 7, -1, -1]) >>> hmg = HexModelGrid(3, 2) >>> hmg.status_at_node[0] = CLOSED_BOUNDARY >>> hmg.active_neighbors_at_node array([[-1, -1, -1, -1, -1, -1], [-1, 3, -1, -1, -1, -1], [ 3, -1, -1, -1, -1, -1], [ 4, 6, 5, 2, -1, 1], [-1, 3, -1, -1, -1, -1], [-1, -1, 3, -1, -1, -1], [-1, 3, -1, -1, -1, -1]]) LLCATS: NINF CONN BC """ try: return self._active_neighbor_nodes except AttributeError: self._active_neighbor_nodes = self._create_neighbor_list() return self._active_neighbor_nodes @property @make_return_array_immutable def links_at_node(self): """Get links of nodes. Returns ------- (NODES, LINKS) ndarray of int Link for the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. Order is anticlockwise from east. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 3)) >>> grid.links_at_node # doctest: +NORMALIZE_WHITESPACE array([[ 0, 2, -1, -1], [ 1, 3, 0, -1], [-1, 4, 1, -1], [ 5, 7, -1, 2], [ 6, 8, 5, 3], [-1, 9, 6, 4], [10, 12, -1, 7], [11, 13, 10, 8], [-1, 14, 11, 9], [15, -1, -1, 12], [16, -1, 15, 13], [-1, -1, 16, 14]]) >>> grid.links_at_node[4] array([6, 8, 5, 3]) >>> grid.links_at_node[(4, 7), :] array([[ 6, 8, 5, 3], [11, 13, 10, 8]]) LLCATS: NINF LINF CONN """ return self._links_at_node @property @make_return_array_immutable def link_dirs_at_node(self): """Link directions at each node: 1=incoming, -1=outgoing, 0=none. Returns ------- (NODES, LINKS) ndarray of int Link directions relative to the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. A zero indicates no link at this position. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 3)) >>> grid.link_dirs_at_node # doctest: +NORMALIZE_WHITESPACE array([[-1, -1, 0, 0], [-1, -1, 1, 0], [ 0, -1, 1, 0], [-1, -1, 0, 1], [-1, -1, 1, 1], [ 0, -1, 1, 1], [-1, -1, 0, 1], [-1, -1, 1, 1], [ 0, -1, 1, 1], [-1, 0, 0, 1], [-1, 0, 1, 1], [ 0, 0, 1, 1]], dtype=int8) >>> grid.link_dirs_at_node[4] array([-1, -1, 1, 1], dtype=int8) >>> grid.link_dirs_at_node[(4, 7), :] array([[-1, -1, 1, 1], [-1, -1, 1, 1]], dtype=int8) LLCATS: NINF LINF CONN """ return self._link_dirs_at_node @property @make_return_array_immutable def active_link_dirs_at_node(self): """ Link flux directions at each node: 1=incoming flux, -1=outgoing flux, 0=no flux. Note that inactive links receive zero, but active and fixed links are both reported normally. Returns ------- (NODES, LINKS) ndarray of int Link directions relative to the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. A zero indicates no link at this position. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> grid = RasterModelGrid((4, 3)) >>> grid.status_at_node[grid.nodes_at_left_edge] = CLOSED_BOUNDARY >>> grid.active_link_dirs_at_node # doctest: +NORMALIZE_WHITESPACE array([[ 0, 0, 0, 0], [ 0, -1, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [-1, -1, 0, 1], [ 0, 0, 1, 0], [ 0, 0, 0, 0], [-1, -1, 0, 1], [ 0, 0, 1, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 1], [ 0, 0, 0, 0]], dtype=int8) LLCATS: NINF LINF CONN """ return self._active_link_dirs_at_node @property def node_at_cell(self): """Node ID associated with grid cells. Examples -------- >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> grid = RasterModelGrid((4, 5)) >>> grid.node_at_cell # doctest: +NORMALIZE_WHITESPACE array([ 6, 7, 8, 11, 12, 13]) LLCATS: NINF CINF CONN """ return self._node_at_cell @property def cell_at_node(self): """Node ID associated with grid cells. Examples -------- >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> grid = RasterModelGrid((4, 5)) >>> ids = grid.cell_at_node >>> ids[ids == BAD_INDEX_VALUE] = -1 >>> ids # doctest: +NORMALIZE_WHITESPACE array([-1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, 3, 4, 5, -1, -1, -1, -1, -1, -1]) LLCATS: CINF NINF CONN """ return self._cell_at_node @property @return_readonly_id_array def core_nodes(self): """Get array of core nodes. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.core_nodes array([ 6, 7, 8, 11, 12, 13]) LLCATS: NINF BC """ try: return self._core_nodes except AttributeError: (core_node_ids, ) = numpy.where(self._node_status == CORE_NODE) return core_node_ids @property @return_readonly_id_array def boundary_nodes(self): """Get array of boundary nodes. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.boundary_nodes array([ 0, 1, 2, 3, 4, 5, 9, 10, 14, 15, 16, 17, 18, 19]) LLCATS: NINF BC """ try: return self._boundary_nodes except: (boundary_node_ids, ) = numpy.where(self._node_status != CORE_NODE) return boundary_node_ids @property @return_readonly_id_array def open_boundary_nodes(self): """Get array of open boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge, ... mg.nodes_at_bottom_edge): ... mg.status_at_node[edge] = CLOSED_BOUNDARY >>> mg.open_boundary_nodes array([16, 17, 18]) LLCATS: NINF BC """ (open_boundary_node_ids, ) = numpy.where( (self._node_status != CLOSED_BOUNDARY) & (self._node_status != CORE_NODE)) return open_boundary_node_ids @property @return_readonly_id_array def closed_boundary_nodes(self): """Get array of closed boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.closed_boundary_nodes array([15, 16, 17, 18, 19]) LLCATS: NINF BC """ (closed_boundary_node_ids, ) = numpy.where( self._node_status == CLOSED_BOUNDARY) return closed_boundary_node_ids @property @return_readonly_id_array def fixed_gradient_boundary_nodes(self): """Get array of fixed gradient boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[mg.nodes_at_top_edge] = FIXED_GRADIENT_BOUNDARY >>> mg.fixed_gradient_boundary_nodes array([15, 16, 17, 18, 19]) LLCATS: NINF BC """ (fixed_gradient_boundary_node_ids, ) = numpy.where( self._node_status == FIXED_GRADIENT_BOUNDARY) return fixed_gradient_boundary_node_ids @property @return_readonly_id_array def fixed_gradient_boundary_node_fixed_link(self): """ An array of the fixed_links connected to fixed gradient boundary nodes. Note that on a raster, some nodes (notably the corners) can be FIXED_GRADIENT_BOUNDARY, but not have a true FIXED_LINK neighboring link. In such cases, the link returned will be a closed link joining the corner node to a neighboring FIXED_GRADIENT_BOUNDARY node (see example). An AssertionError will be raised if for some reason a FIXED_GRADIENT_BOUNDARY node exists which has neither a FIXED_GRADIENT_BOUNDARY neighbor, or a FIXED_LINK. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab import FIXED_GRADIENT_BOUNDARY >>> grid = RasterModelGrid((3, 4)) >>> leftedge = grid.nodes_at_left_edge >>> grid.status_at_node[leftedge] = FIXED_GRADIENT_BOUNDARY >>> grid.fixed_gradient_boundary_nodes array([0, 4, 8]) >>> grid.fixed_gradient_boundary_node_fixed_link array([ 3, 7, 10]) """ try: return self._fixed_gradient_boundary_node_links except AttributeError: self._create_fixed_gradient_boundary_node_links() return self._fixed_gradient_boundary_node_links @property @return_readonly_id_array def fixed_gradient_boundary_node_anchor_node(self): """ Returns the node at the other end of the fixed link for a fixed gradient boundary node. Degenerate FIXED_GRADIENT_BOUNDARY nodes (e.g., corners) are handled as in :func:`fixed_gradient_boundary_node_fixed_link`, by pointing to a neighboring FIXED_GRADIENT_BOUNDARY node. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab import FIXED_GRADIENT_BOUNDARY >>> grid = RasterModelGrid((3, 4)) >>> leftedge = grid.nodes_at_left_edge >>> grid.status_at_node[leftedge] = FIXED_GRADIENT_BOUNDARY >>> grid.fixed_gradient_boundary_nodes array([0, 4, 8]) >>> grid.fixed_gradient_boundary_node_fixed_link array([ 3, 7, 10]) >>> grid.fixed_gradient_boundary_node_anchor_node array([4, 5, 4]) """ try: return self._fixed_gradient_boundary_node_anchor_node except AttributeError: self._create_fixed_gradient_boundary_node_anchor_node() return self._fixed_gradient_boundary_node_anchor_node def _create_fixed_gradient_boundary_node_links(self): """ Builds a data structure to hold the fixed_links which control the values of any FIXED_GRADIENT_BOUNDARY nodes in the grid. An AssertionError will be raised if for some reason a FIXED_GRADIENT_BOUNDARY node exists which has neither a FIXED_GRADIENT_BOUNDARY neighbor, or a FIXED_LINK. """ self._fixed_grad_links_created = True self._fixed_gradient_boundary_node_links = np.empty_like( self.fixed_gradient_boundary_nodes, dtype=int) fix_nodes = self.fixed_gradient_boundary_nodes neighbor_links = self.links_at_node[fix_nodes] # -1s boundary_exists = self.link_dirs_at_node[fix_nodes] # next line retains -1 indexes link_stat_badind = self.status_at_link[neighbor_links] == FIXED_LINK true_connection = np.logical_and(link_stat_badind, boundary_exists) true_fix_nodes = true_connection.sum(axis=1).astype(bool) self._fixed_gradient_boundary_node_links[true_fix_nodes] = ( neighbor_links[true_connection]) # resolve any corner nodes neighbor_nodes = self.neighbors_at_node[fix_nodes] # BAD_INDEX_VALUEs neighbor_nodes[neighbor_nodes == BAD_INDEX_VALUE] = -1 fixed_grad_neighbor = np.logical_and((self.status_at_node[ neighbor_nodes] == FIXED_GRADIENT_BOUNDARY), boundary_exists) # ^True when FIXED_GRADIENT_BOUNDARY for real # winnow it down to only one possibility for fixed_grad neighbor: which_neighbor = np.argmax(fixed_grad_neighbor, axis=1) indexing_range = np.arange(fixed_grad_neighbor.shape[0]) a_link_to_fixed_grad = neighbor_links[indexing_range, which_neighbor] corners = np.logical_not(true_fix_nodes) assert np.all( fixed_grad_neighbor[indexing_range, which_neighbor][corners]) self._fixed_gradient_boundary_node_links[ corners] = a_link_to_fixed_grad[corners] def _create_fixed_gradient_boundary_node_anchor_node(self): """ Builds a data structure to hold the nodes which anchor the values of any FIXED_GRADIENT_BOUNDARY nodes in the grid, i.e., those at the other ends of the FIXED_LINKS. An AssertionError will be raised if for some reason a FIXED_GRADIENT_BOUNDARY node exists which has neither a FIXED_GRADIENT_BOUNDARY neighbor, or a FIXED_LINK. """ self._fixed_grad_links_created = True fix_grad_nodes = self.fixed_gradient_boundary_nodes self._fixed_gradient_boundary_node_anchor_node = np.empty_like( fix_grad_nodes) heads_and_tails = np.empty((fix_grad_nodes.size, 2)) which_one = np.empty_like(heads_and_tails, dtype=bool) heads_and_tails[:, 0] = self.node_at_link_head[ self.fixed_gradient_boundary_node_fixed_link] heads_and_tails[:, 1] = self.node_at_link_tail[ self.fixed_gradient_boundary_node_fixed_link] which_one[:, 0] = heads_and_tails[:, 0] == fix_grad_nodes which_one[:, 1] = heads_and_tails[:, 1] == fix_grad_nodes assert np.all(which_one.sum(axis=1) == 1) self._fixed_gradient_boundary_node_anchor_node = heads_and_tails[ np.logical_not(which_one)] @property @return_readonly_id_array def fixed_value_boundary_nodes(self): """Get array of fixed value boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge, ... mg.nodes_at_bottom_edge): ... mg.status_at_node[edge] = CLOSED_BOUNDARY >>> mg.fixed_value_boundary_nodes array([16, 17, 18]) LLCATS: NINF BC """ (fixed_value_boundary_node_ids, ) = numpy.where( self._node_status == FIXED_VALUE_BOUNDARY) return fixed_value_boundary_node_ids @property @return_readonly_id_array def active_faces(self): """Get array of active faces. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.active_faces array([0, 1, 2, 3, 4, 5, 6]) >>> from landlab import CLOSED_BOUNDARY >>> grid.status_at_node[6] = CLOSED_BOUNDARY >>> grid.active_faces array([0, 2, 5]) LLCATS: FINF BC """ try: return self._active_faces except AttributeError: self._create_active_faces() return self._active_faces @property @return_readonly_id_array def active_links(self): """Get array of active links. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.active_links array([ 4, 5, 7, 8, 9, 11, 12]) LLCATS: LINF BC """ try: return self._active_links except AttributeError: self._reset_link_status_list() return self._active_links @property @return_readonly_id_array def fixed_links(self): """Get array of fixed links. Examples -------- >>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY >>> grid = RasterModelGrid((3, 4)) >>> grid.status_at_node # doctest: +NORMALIZE_WHITESPACE array([1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8) >>> grid.fixed_links.size 0 >>> grid.status_at_node[:4] = FIXED_GRADIENT_BOUNDARY >>> grid.status_at_node # doctest: +NORMALIZE_WHITESPACE array([2, 2, 2, 2, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8) >>> grid.fixed_links array([4, 5]) LLCATS: LINF BC """ try: return self._fixed_links except AttributeError: self._reset_link_status_list() return self._fixed_links @property @return_readonly_id_array def node_at_core_cell(self): """Get array of nodes associated with core cells. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[8] = CLOSED_BOUNDARY >>> mg.node_at_core_cell array([ 6, 7, 11, 12, 13]) LLCATS: NINF CINF BC CONN """ (core_cell_ids, ) = numpy.where(self._node_status == CORE_NODE) return core_cell_ids @property def core_cells(self): """Get array of core cells. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[8] = CLOSED_BOUNDARY >>> mg.core_cells array([0, 1, 3, 4, 5]) LLCATS: CINF BC """ return self._core_cells @property def node_at_link_head(self): """Get array of the node at each link head (*to-node*). Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.node_at_link_head[:5] array([1, 2, 3, 4, 5]) LLCATS: NINF LINF CONN """ return self._node_at_link_head @property def node_at_link_tail(self): """Get array of the node at each link tail (*from-node*). Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.node_at_link_tail[:5] array([0, 1, 2, 3, 0]) LLCATS: NINF LINF CONN """ return self._node_at_link_tail @property def face_at_link(self): """Get array of faces associated with links. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.face_at_link[5:7] array([0, 1]) >>> np.all(mg.face_at_link[:5]==BAD_INDEX_VALUE) True LLCATS: FINF LINF CONN """ try: return self._face_at_link except AttributeError: return self._create_face_at_link() @property def link_at_face(self): """Get array of links associated with faces. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.link_at_face[0:3] array([5, 6, 7]) LLCATS: LINF FINF CONN """ try: return self._link_at_face except AttributeError: return self._create_link_at_face() @property def number_of_nodes(self): """Total number of nodes. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_nodes 20 LLCATS: NINF """ return len(self._cell_at_node) @property def number_of_corners(self): """Total number of corners. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_corners 12 LLCATS: CNINF """ return self.number_of_patches @property def number_of_cells(self): """Total number of cells. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_cells 6 LLCATS: CINF """ return len(self._node_at_cell) @property def number_of_links(self): """Total number of links. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.number_of_links 17 LLCATS: LINF """ return self._status_at_link.size @property def number_of_faces(self): """Total number of faces. Returns ------- int Total number of faces in the grid. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.number_of_faces 7 LLCATS: FINF """ return len(self.link_at_face) @property def number_of_active_faces(self): """Total number of active faces. Returns ------- int Total number of active faces in the grid. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.number_of_active_faces 7 The number of active faces is updated when a node status changes. >>> from landlab import CLOSED_BOUNDARY >>> grid.status_at_node[6] = CLOSED_BOUNDARY >>> grid.number_of_active_faces 3 LLCATS: FINF BC """ return self.active_faces.size @property def number_of_core_nodes(self): """Number of core nodes. The number of core nodes on the grid (i.e., excluding all boundary nodes). Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_core_nodes 6 >>> grid.status_at_node[7] = CLOSED_BOUNDARY >>> grid.number_of_core_nodes 5 LLCATS: NINF BC """ return self._core_nodes.size @property def number_of_core_cells(self): """Number of core cells. A core cell excludes all boundary cells. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_core_cells 6 >>> grid.status_at_node[7] = CLOSED_BOUNDARY >>> grid.number_of_core_cells 5 LLCATS: CINF BC """ return self._core_cells.size @property def number_of_active_links(self): """Number of active links. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.number_of_active_links 17 >>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge, ... mg.nodes_at_bottom_edge): ... mg.status_at_node[edge] = CLOSED_BOUNDARY >>> mg.number_of_active_links 10 LLCATS: LINF BC """ return self.active_links.size @property def number_of_fixed_links(self): """Number of fixed links. Examples -------- >>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.number_of_fixed_links 0 >>> mg.status_at_node[mg.nodes_at_top_edge] = FIXED_GRADIENT_BOUNDARY >>> mg.number_of_fixed_links 3 LLCATS: LINF BC """ try: return self._fixed_links.size except AttributeError: self._reset_link_status_list() return self._fixed_links.size def number_of_elements(self, name): """Number of instances of an element. Get the number of instances of a grid element in a grid. Parameters ---------- name : {'node', 'cell', 'link', 'face', 'core_node', 'core_cell', 'active_link', 'active_face'} Name of the grid element. Returns ------- int Number of elements in the grid. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.number_of_elements('node') 20 >>> mg.number_of_elements('core_cell') 6 >>> mg.number_of_elements('link') 31 >>> mg.number_of_elements('active_link') 17 >>> mg.status_at_node[8] = CLOSED_BOUNDARY >>> mg.number_of_elements('link') 31 >>> mg.number_of_elements('active_link') 13 LLCATS: GINF """ try: return getattr(self, _ARRAY_LENGTH_ATTRIBUTES[name]) except KeyError: raise TypeError( '{name}: element name not understood'.format(name=name)) @property @make_return_array_immutable def node_x(self): """Get array of the x-coordinates of nodes. See also -------- x_of_node Exquivalent method. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.node_x.reshape((4, 5)) array([[ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.]]) LLCATS: NINF MEAS """ return self._node_x @property @make_return_array_immutable def node_y(self): """Get array of the y-coordinates of nodes. See also -------- y_of_node Exquivalent method. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.node_y.reshape((4, 5)) array([[ 0., 0., 0., 0., 0.], [ 2., 2., 2., 2., 2.], [ 4., 4., 4., 4., 4.], [ 6., 6., 6., 6., 6.]]) LLCATS: NINF MEAS """ return self._node_y @property @make_return_array_immutable def x_of_node(self): """Get array of the x-coordinates of nodes. See also -------- node_x Exquivalent method. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.x_of_node.reshape((4, 5)) array([[ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.]]) LLCATS: NINF MEAS """ return self._node_x @property @make_return_array_immutable def y_of_node(self): """Get array of the y-coordinates of nodes. See also -------- node_y Exquivalent method. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.y_of_node.reshape((4, 5)) array([[ 0., 0., 0., 0., 0.], [ 2., 2., 2., 2., 2.], [ 4., 4., 4., 4., 4.], [ 6., 6., 6., 6., 6.]]) LLCATS: NINF MEAS """ return self._node_y @property @make_return_array_immutable def x_of_cell(self): """Get array of the x-coordinates of nodes at cells. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.x_of_cell.reshape((2, 3)) array([[ 3., 6., 9.], [ 3., 6., 9.]]) LLCATS: CINF MEAS """ return self._node_x[self.node_at_cell] @property @make_return_array_immutable def y_of_cell(self): """Get array of the y-coordinates of nodes at cells. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.y_of_cell.reshape((2, 3)) array([[ 2., 2., 2.], [ 4., 4., 4.]]) LLCATS: CINF MEAS """ return self._node_y[self.node_at_cell] @property @make_return_array_immutable def x_of_link(self): """Get array of the x-coordinates of link midpoints. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.x_of_link # doctest: +NORMALIZE_WHITESPACE array([ 1.5, 4.5, 7.5, 10.5, 0. , 3. , 6. , 9. , 12. , 1.5, 4.5, 7.5, 10.5, 0. , 3. , 6. , 9. , 12. , 1.5, 4.5, 7.5, 10.5, 0. , 3. , 6. , 9. , 12. , 1.5, 4.5, 7.5, 10.5]) LLCATS: LINF MEAS """ try: return self._link_x except AttributeError: self._create_link_face_coords() return self._link_x @property @make_return_array_immutable def y_of_link(self): """Get array of the y-coordinates of link midpoints. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.y_of_link # doctest: +NORMALIZE_WHITESPACE array([ 0., 0., 0., 0., 1., 1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3., 3., 4., 4., 4., 4., 5., 5., 5., 5., 5., 6., 6., 6., 6.]) LLCATS: LINF MEAS """ try: return self._link_y except AttributeError: self._create_link_face_coords() return self._link_y @property @make_return_array_immutable def x_of_face(self): """Get array of the x-coordinates of face midpoints. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.x_of_face # doctest: +NORMALIZE_WHITESPACE array([ 3. , 6. , 9. , 1.5, 4.5, 7.5, 10.5, 3. , 6. , 9. , 1.5, 4.5, 7.5, 10.5, 3. , 6. , 9. ]) LLCATS: FINF MEAS """ try: return self._link_x[self.link_at_face] except AttributeError: self._create_link_face_coords() return self._link_x[self.link_at_face] @property @make_return_array_immutable def y_of_face(self): """Get array of the y-coordinates of face midpoints. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.y_of_face # doctest: +NORMALIZE_WHITESPACE array([ 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 4., 4., 4., 4., 5., 5., 5.]) LLCATS: FINF MEAS """ try: return self._link_y[self.link_at_face] except AttributeError: self._create_link_face_coords() return self._link_y[self.link_at_face] @make_return_array_immutable def node_axis_coordinates(self, axis=0): """Get the coordinates of nodes along a particular axis. Return node coordinates from a given *axis* (defaulting to 0). Axis numbering is the same as that for numpy arrays. That is, the zeroth axis is along the rows, and the first along the columns. Parameters ---------- axis : int, optional Coordinate axis. Returns ------- ndarray Coordinates of nodes for a given axis. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.node_axis_coordinates(0) # doctest: +NORMALIZE_WHITESPACE array([ 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 3., 3., 3., 3., 3.]) >>> grid.node_axis_coordinates(1) # doctest: +NORMALIZE_WHITESPACE array([ 0., 1., 2., 3., 4., 0., 1., 2., 3., 4., 0., 1., 2., 3., 4., 0., 1., 2., 3., 4.]) LLCATS: GINF NINF MEAS """ AXES = ('node_y', 'node_x') try: return getattr(self, AXES[axis]) except IndexError: raise ValueError("'axis' entry is out of bounds") @property def axis_units(self): """Get units for each axis. Returns ------- tuple of str The units (as a string) for each of a grid's coordinates. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.axis_units ('-', '-') >>> mg.axis_units = ('km', 'km') >>> mg.axis_units ('km', 'km') LLCATS: GINF """ return self._axis_units @axis_units.setter def axis_units(self, new_units): """Set the units for each coordinate axis.""" if len(new_units) != self.ndim: raise ValueError('length of units does not match grid dimension') self._axis_units = tuple(new_units) @property def axis_name(self): """Get the name of each coordinate axis. Returns ------- tuple of str The names of each axis. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.axis_name ('y', 'x') >>> grid.axis_name = ('lon', 'lat') >>> grid.axis_name ('lon', 'lat') LLCATS: GINF """ return self._axis_name @axis_name.setter def axis_name(self, new_names): """Set the names of a grid's coordinate axes. Raises ------ ValueError If the number of dimension do not match. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.axis_name = ('lon', 'lat') >>> grid.axis_name ('lon', 'lat') """ if len(new_names) != self.ndim: raise ValueError('length of names does not match grid dimension') self._axis_name = tuple(new_names) @property @make_return_array_immutable def status_at_link(self): """Get array of the status of all links. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab import CLOSED_BOUNDARY, FIXED_GRADIENT_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[mg.nodes_at_left_edge] = CLOSED_BOUNDARY >>> mg.status_at_node[mg.nodes_at_right_edge] = FIXED_GRADIENT_BOUNDARY >>> mg.status_at_link # doctest: +NORMALIZE_WHITESPACE array([4, 4, 4, 4, 4, 0, 0, 0, 4, 4, 0, 0, 2, 4, 0, 0, 0, 4, 4, 0, 0, 2, 4, 0, 0, 0, 4, 4, 4, 4, 4]) LLCATS: BC LINF """ return self._status_at_link @property @return_readonly_id_array def link_at_face(self): """Get links associated with faces. Returns an array of the link IDs for the links that intersect faces. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4)) >>> mg.link_at_face array([ 4, 5, 7, 8, 9, 11, 12]) LLCATS: LINF FINF MEAS """ try: return self._link_at_face except AttributeError: return self._create_link_at_face() def _create_number_of_links_at_node(self): """Find and record how many links are attached to each node. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4)) >>> mg.number_of_links_at_node array([2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2]) """ self._number_of_links_at_node = np.zeros(self.number_of_nodes, dtype=np.int) for ln in range(self.number_of_links): self._number_of_links_at_node[self.node_at_link_tail[ln]] += 1 self._number_of_links_at_node[self.node_at_link_head[ln]] += 1 @property def number_of_links_at_node(self): """Number of links connected to each node. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4)) >>> mg.number_of_links_at_node array([2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2]) LLCATS: LINF NINF CONN """ try: return self._number_of_links_at_node except AttributeError: self._create_number_of_links_at_node() return self._number_of_links_at_node def _create_links_and_link_dirs_at_node(self): """Make arrays with links and link directions at each node. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg.links_at_node array([[ 0, 3, 2, -1, -1, -1], [ 1, 5, 4, 0, -1, -1], [ 7, 6, 1, -1, -1, -1], [ 8, 11, 2, -1, -1, -1], [ 9, 13, 12, 8, 3, 4], [10, 15, 14, 9, 5, 6], [16, 10, 7, -1, -1, -1], [17, 11, 12, -1, -1, -1], [18, 17, 13, 14, -1, -1], [18, 15, 16, -1, -1, -1]]) >>> hg.link_dirs_at_node array([[-1, -1, -1, 0, 0, 0], [-1, -1, -1, 1, 0, 0], [-1, -1, 1, 0, 0, 0], [-1, -1, 1, 0, 0, 0], [-1, -1, -1, 1, 1, 1], [-1, -1, -1, 1, 1, 1], [-1, 1, 1, 0, 0, 0], [-1, 1, 1, 0, 0, 0], [-1, 1, 1, 1, 0, 0], [ 1, 1, 1, 0, 0, 0]], dtype=int8) """ # Find maximum number of links per node nlpn = self.number_of_links_at_node # ^this fn should become member and property max_num_links = np.amax(nlpn) nlpn[:] = 0 # we'll zero it out, then rebuild it # Create arrays for link-at-node information self._links_at_node = - np.ones((self.number_of_nodes, max_num_links), dtype=int) self._link_dirs_at_node = np.zeros((self.number_of_nodes, max_num_links), dtype=np.int8) # Sweep over all links for lk in range(self.number_of_links): # Find the IDs of the tail and head nodes t = self.node_at_link_tail[lk] h = self.node_at_link_head[lk] # Add this link to the list for this node, set the direction # (outgoing, indicated by -1), and increment the number found so # far self._links_at_node[t][nlpn[t]] = lk self._links_at_node[h][nlpn[h]] = lk self._link_dirs_at_node[t][nlpn[t]] = -1 self._link_dirs_at_node[h][nlpn[h]] = 1 nlpn[t] += 1 nlpn[h] += 1 # Sort the links at each node by angle, counter-clockwise from +x self._sort_links_at_node_by_angle() # setup the active link equivalent self._active_link_dirs_at_node = self._link_dirs_at_node.copy() inactive_links = (self.status_at_link[self.links_at_node] == INACTIVE_LINK) inactive_links[self.link_dirs_at_node == 0] = False self._active_link_dirs_at_node[inactive_links] = 0 @deprecated(use='vals[links_at_node]*active_link_dirs_at_node', version=1.0) def _active_links_at_node(self, *args): """_active_links_at_node([node_ids]) Active links of a node. Parameters ---------- node_ids : int or list of ints ID(s) of node(s) for which to find connected active links Returns ------- (M, N) ndarray The ids of active links attached to grid nodes with *node_ids*. If *node_ids* is not given, return links for all of the nodes in the grid. M is the number of rows in the grid's _node_active_inlink_matrix, which can vary depending on the type and structure of the grid; in a hex grid, for example, it is 6. Notes ----- On it's way to being obsolete. **Deprecated**. LLCATS: DEPR LINF NINF CONN """ if len(args) == 0: return numpy.vstack((self._node_active_inlink_matrix, self._node_active_outlink_matrix)) elif len(args) == 1: node_ids = numpy.broadcast_arrays(args[0])[0] return numpy.vstack( (self._node_active_inlink_matrix[:, node_ids], self._node_active_outlink_matrix[:, node_ids]) ).reshape(2 * numpy.size(self._node_active_inlink_matrix, 0), -1) else: raise ValueError('only zero or one arguments accepted') @property @make_return_array_immutable def angle_of_link(self): """Find and return the angle of a link about the node at the link tail. Examples -------- >>> from landlab import HexModelGrid >>> mg = HexModelGrid(3, 2) >>> mg.angle_of_link / np.pi * 3. # 60 degree segments array([ 0., 2., 1., 2., 1., 0., 0., 1., 2., 1., 2., 0.]) LLCATS: LINF MEAS """ try: if not self._angle_of_link_created: self._create_angle_of_link() except AttributeError: self._create_angle_of_link() return self._angle_of_link_bothends[-1] @property @make_return_array_immutable def angle_of_link_about_head(self): """Find and return the angle of a link about the node at the link head. Because links have direction, their angle can be specified as an angle about either the node at the link head, or the node at the link tail. The default behaviour of `angle_of_link` is to return the angle about the link tail, but this method gives the angle about the link head. Examples -------- >>> from landlab import HexModelGrid >>> mg = HexModelGrid(3, 2) >>> mg.angle_of_link_about_head[:3] / np.pi * 3. # 60 deg segments array([ 3., 5., 4.]) LLCATS: LINF MEAS """ try: if not self._angle_of_link_created: self._create_angle_of_link() except AttributeError: self._create_angle_of_link() return self._angle_of_link_bothends[1] def _create_angle_of_link(self): """ Build a dict with keys (-1, 1) that contains the angles of the links about both the link heads (1) and link tails (-1). Notes ----- dx and dy are the x and y differences between the link endpoints. Multiplying this by dirs orients these offsets correctly (i.e., the correct node is the origin). The call to arctan2 calculates the angle in radians. Angles in the lower two quadrants will be negative and clockwise from the positive x axis. We want them counter-clockwise, which is what the last couple of lines before the return statement do. LLCATS: LINF MEAS """ self._angle_of_link_bothends = {} for dirs in (-1, 1): dx = -dirs * (self.node_x[self.node_at_link_head] - self.node_x[self.node_at_link_tail]) dy = -dirs * (self.node_y[self.node_at_link_head] - self.node_y[self.node_at_link_tail]) ang = np.arctan2(dy, dx) (lower_two_quads, ) = np.where(ang < 0.0) ang[lower_two_quads] = (2 * np.pi) + ang[lower_two_quads] (no_link, ) = np.where(dirs == 0) ang[no_link] = 2*np.pi self._angle_of_link_bothends[dirs] = ang.copy() self._angle_of_link_created = True def _sort_links_at_node_by_angle(self): """Sort the links_at_node and link_dirs_at_node arrays by angle. """ ang = self.angle_of_link[self.links_at_node] linkhead_at_node = self.link_dirs_at_node == 1 ang[linkhead_at_node] = self.angle_of_link_about_head[ self.links_at_node[linkhead_at_node]] ang[self.link_dirs_at_node == 0] = 100. argsorted = np.argsort(ang, axis=1) indices = np.indices(ang.shape)[0] * ang.shape[1] + argsorted self._links_at_node.flat = self._links_at_node.flat[indices.flatten()] self._link_dirs_at_node.flat = self._link_dirs_at_node.flat[ indices.flatten()] def resolve_values_on_links(self, link_values, out=None): """Resolve the xy-components of links. Resolves values provided defined on links into the x and y directions. Returns values_along_x, values_along_y LLCATS: LINF """ return gfuncs.resolve_values_on_links(self, link_values, out=out) @deprecated(use='no replacement', version=1.0) def resolve_values_on_active_links(self, link_values, out=None): """Resolve the xy-components of active links. Resolves values provided defined on active links into the x and y directions. Returns values_along_x, values_along_y LLCATS: LINF """ return gfuncs.resolve_values_on_active_links(self, link_values, out=out) def link_at_node_is_upwind(self, values, out=None): """ Return a boolean the same shape as :func:`links_at_node` which flags links which are upwind of the node as True. link_at_node_is_upwind iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node. It then return a boolean array the same shape as links_at_node flagging these links. e.g., for a raster, the returned array will be shape (nnodes, 4). Parameters ---------- values : str or array Name of variable field defined at links, or array of values at links. out : ndarray, optional Buffer to place mapped values into or `None` to create a new array. Must be correct shape and boolean dtype. Returns ------- ndarray Boolean of which links are upwind at nodes. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((3, 4)) >>> rmg.at_link['grad'] = np.array([-1., -2., -1., ... -2., -3., -4., -5., ... -1., -2., -1., ... -1., -2., -3., -4., ... -1., -2., -1.]) >>> rmg.link_at_node_is_upwind('grad') array([[False, False, False, False], [False, False, True, False], [False, False, True, False], [False, False, True, False], [False, False, False, True], [False, False, True, True], [False, False, True, True], [False, False, True, True], [False, False, False, True], [False, False, True, True], [False, False, True, True], [False, False, True, True]], dtype=bool) LLCATS: LINF NINF CONN """ if out is None: out = np.empty_like(self.links_at_node, dtype=bool) else: assert out.shape is self.links_at_node.shape assert out.dtype is bool if type(values) is str: vals = self.at_link[values] else: assert len(values) == self.number_of_links vals = values values_at_links = vals[self.links_at_node] * self.link_dirs_at_node # this procedure makes incoming links NEGATIVE np.less(values_at_links, 0., out=out) return out def link_at_node_is_downwind(self, values, out=None): """ Return a boolean the same shape as :func:`links_at_node` which flags links which are downwind of the node as True. link_at_node_is_downwind iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node. It then return a boolean array the same shape as links_at_node flagging these links. e.g., for a raster, the returned array will be shape (nnodes, 4). Parameters ---------- values : str or array Name of variable field defined at links, or array of values at links. out : ndarray, optional Buffer to place mapped values into or `None` to create a new array. Must be correct shape and boolean dtype. Returns ------- ndarray Boolean of which links are downwind at nodes. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((3, 4)) >>> rmg.at_link['grad'] = np.array([-1., -2., -1., ... -2., -3., -4., -5., ... -1., -2., -1., ... -1., -2., -3., -4., ... -1., -2., -1.]) >>> rmg.link_at_node_is_downwind('grad') array([[ True, True, False, False], [ True, True, False, False], [ True, True, False, False], [False, True, False, False], [ True, True, False, False], [ True, True, False, False], [ True, True, False, False], [False, True, False, False], [ True, False, False, False], [ True, False, False, False], [ True, False, False, False], [False, False, False, False]], dtype=bool) LLCATS: LINF NINF CONN """ if out is None: out = np.empty_like(self.links_at_node, dtype=bool) else: assert out.shape is self.links_at_node.shape assert out.dtype is bool if type(values) is str: vals = self.at_link[values] else: assert len(values) == self.number_of_links vals = values values_at_links = vals[self.links_at_node] * self.link_dirs_at_node # this procedure makes incoming links NEGATIVE np.greater(values_at_links, 0., out=out) return out def upwind_links_at_node(self, values, bad_index=-1): """ Return an (nnodes, X) shape array of link IDs of which links are upwind of each node, according to *values* (field or array). X is the maximum upwind links at any node. Nodes with fewer upwind links than this have additional slots filled with *bad_index*. Links are ordered anticlockwise from east. Parameters ---------- values : str or array Name of variable field defined at links, or array of values at links. bad_index : int Index to place in array indicating no link. Returns ------- ndarray Array of upwind link IDs Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((3, 4)) >>> rmg.at_link['grad'] = np.array([-1., -2., -1., ... -2., -3., -4., -5., ... -1., -2., -1., ... -1., -2., -3., -4., ... -1., -2., -1.]) >>> rmg.upwind_links_at_node('grad', bad_index=-1) array([[-1, -1], [ 0, -1], [ 1, -1], [ 2, -1], [ 3, -1], [ 7, 4], [ 8, 5], [ 9, 6], [10, -1], [14, 11], [15, 12], [16, 13]]) LLCATS: LINF NINF CONN """ if type(values) is str: vals = self.at_link[values] else: assert len(values) == self.number_of_links vals = values values_at_links = vals[self.links_at_node] * self.link_dirs_at_node # this procedure makes incoming links NEGATIVE unordered_IDs = np.where(values_at_links < 0., self.links_at_node, bad_index) bad_IDs = unordered_IDs == bad_index nnodes = self.number_of_nodes flat_sorter = (np.argsort(bad_IDs, axis=1) + self.links_at_node.shape[1] * np.arange(nnodes).reshape((nnodes, 1))) big_ordered_array = unordered_IDs.ravel()[flat_sorter].reshape( self.links_at_node.shape) cols_to_cut = int(bad_IDs.sum(axis=1).min()) if cols_to_cut > 0: return big_ordered_array[:, :-cols_to_cut] else: return big_ordered_array def downwind_links_at_node(self, values, bad_index=-1): """ Return an (nnodes, X) shape array of link IDs of which links are downwind of each node, according to *values* (array or field). X is the maximum downwind links at any node. Nodes with fewer downwind links than this have additional slots filled with *bad_index*. Links are ordered anticlockwise from east. Parameters ---------- values : str or array Name of variable field defined at links, or array of values at links. bad_index : int Index to place in array indicating no link. Returns ------- ndarray Array of upwind link IDs Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> rmg = RasterModelGrid((3, 4)) >>> rmg.at_link['grad'] = np.array([-1., -2., -1., ... -2., -3., -4., -5., ... -1., -2., -1., ... -1., -2., -3., -4., ... -1., -2., -1.]) >>> rmg.downwind_links_at_node('grad', bad_index=BAD_INDEX_VALUE) array([[ 0, 3], [ 1, 4], [ 2, 5], [ 6, -1], [ 7, 10], [ 8, 11], [ 9, 12], [13, -1], [14, -1], [15, -1], [16, -1], [-1, -1]]) LLCATS: LINF NINF CONN """ if type(values) is str: vals = self.at_link[values] else: assert len(values) == self.number_of_links vals = values values_at_links = vals[self.links_at_node] * self.link_dirs_at_node # this procedure makes incoming links NEGATIVE unordered_IDs = np.where(values_at_links > 0., self.links_at_node, bad_index) bad_IDs = unordered_IDs == bad_index nnodes = self.number_of_nodes flat_sorter = (np.argsort(bad_IDs, axis=1) + self.links_at_node.shape[1] * np.arange(nnodes).reshape((nnodes, 1))) big_ordered_array = unordered_IDs.ravel()[flat_sorter].reshape( self.links_at_node.shape) cols_to_cut = int(bad_IDs.sum(axis=1).min()) if cols_to_cut > 0: return big_ordered_array[:, :-cols_to_cut] else: return big_ordered_array @property def faces_at_cell(self): """Return array containing face IDs at each cell. Creates array if it doesn't already exist. Examples -------- >>> from landlab import HexModelGrid, RasterModelGrid >>> mg = RasterModelGrid((4, 5)) >>> mg.faces_at_cell array([[ 4, 7, 3, 0], [ 5, 8, 4, 1], [ 6, 9, 5, 2], [11, 14, 10, 7], [12, 15, 11, 8], [13, 16, 12, 9]]) >>> mg = HexModelGrid(3, 4) >>> mg.faces_at_cell array([[ 7, 11, 10, 6, 0, 1], [ 8, 13, 12, 7, 2, 3], [ 9, 15, 14, 8, 4, 5]]) LLCATS: FINF CINF CONN """ try: return self._faces_at_cell except AttributeError: self._create_faces_at_cell() return self._faces_at_cell def number_of_faces_at_cell(self): """Number of faces attached to each cell. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg.number_of_faces_at_cell() array([6, 6]) LLCATS: FINF CINF CONN """ num_faces_at_cell = np.zeros(self.number_of_cells, dtype=np.int) for ln in range(self.number_of_links): cell = self.cell_at_node[self.node_at_link_tail[ln]] if cell != BAD_INDEX_VALUE: num_faces_at_cell[cell] += 1 cell = self.cell_at_node[self.node_at_link_head[ln]] if cell != BAD_INDEX_VALUE: num_faces_at_cell[cell] += 1 return num_faces_at_cell def _sort_faces_at_cell_by_angle(self): """Sort the faces_at_cell array by angle. Assumes links_at_node and link_dirs_at_node created. """ for cell in range(self.number_of_cells): sorted_links = self.links_at_node[self.node_at_cell[cell], :] sorted_faces = self._faces_at_cell[cell, :] = self.face_at_link[ sorted_links] self._faces_at_cell[cell, :] = sorted_faces def _create_faces_at_cell(self): """Construct faces_at_cell array. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg._create_faces_at_cell() >>> hg._faces_at_cell array([[ 5, 8, 7, 4, 0, 1], [ 6, 10, 9, 5, 2, 3]]) """ num_faces = self.number_of_faces_at_cell() self._faces_at_cell = np.zeros((self.number_of_cells, np.amax(num_faces)), dtype=int) num_faces[:] = 0 # Zero out and count again, to use as index for ln in range(self.number_of_links): cell = self.cell_at_node[self.node_at_link_tail[ln]] if cell != BAD_INDEX_VALUE: self._faces_at_cell[cell, num_faces[cell]] = \ self.face_at_link[ln] num_faces[cell] += 1 cell = self.cell_at_node[self.node_at_link_head[ln]] if cell != BAD_INDEX_VALUE: self._faces_at_cell[cell, num_faces[cell]] = \ self.face_at_link[ln] num_faces[cell] += 1 self._sort_faces_at_cell_by_angle() @property @make_return_array_immutable def patches_present_at_node(self): """ A boolean array, False where a patch has a closed node or is missing. The array is the same shape as :func:`patches_at_node`, and is designed to mask it. Note that in cases where patches may have more than 3 nodes (e.g., rasters), a patch is considered still present as long as at least 3 open nodes are present. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((3, 3)) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.patches_at_node array([[ 0, -1, -1, -1], [ 1, 0, -1, -1], [-1, 1, -1, -1], [ 2, -1, -1, 0], [ 3, 2, 0, 1], [-1, 3, 1, -1], [-1, -1, -1, 2], [-1, -1, 2, 3], [-1, -1, 3, -1]]) >>> mg.patches_present_at_node array([[ True, False, False, False], [ True, True, False, False], [False, True, False, False], [False, False, False, True], [False, False, True, True], [False, False, True, False], [False, False, False, False], [False, False, False, False], [False, False, False, False]], dtype=bool) >>> 1 in mg.patches_at_node * mg.patches_present_at_node True >>> 2 in mg.patches_at_node * mg.patches_present_at_node False LLCATS: PINF NINF """ try: return self._patches_present_mask except AttributeError: self.patches_at_node self._reset_patch_status() return self._patches_present_mask @property @make_return_array_immutable def patches_present_at_link(self): """ A boolean array, False where a patch has a closed node or is missing. The array is the same shape as :func:`patches_at_link`, and is designed to mask it. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((3, 3)) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.patches_at_link array([[ 0, -1], [ 1, -1], [ 0, -1], [ 0, 1], [ 1, -1], [ 0, 2], [ 1, 3], [ 2, -1], [ 2, 3], [ 3, -1], [ 2, -1], [ 3, -1]]) >>> mg.patches_present_at_link array([[ True, False], [ True, False], [ True, False], [ True, True], [ True, False], [ True, False], [ True, False], [False, False], [False, False], [False, False], [False, False], [False, False]], dtype=bool) >>> 1 in mg.patches_at_link * mg.patches_present_at_link True >>> 2 in mg.patches_at_link * mg.patches_present_at_link False LLCATS: PINF LINF """ try: return self._patches_present_link_mask except AttributeError: self.patches_at_node self._reset_patch_status() return self._patches_present_link_mask @property @make_return_array_immutable def number_of_patches_present_at_node(self): """Return the number of patches at a node without a closed node. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((3, 3)) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.patches_present_at_node array([[ True, False, False, False], [ True, True, False, False], [False, True, False, False], [False, False, False, True], [False, False, True, True], [False, False, True, False], [False, False, False, False], [False, False, False, False], [False, False, False, False]], dtype=bool) >>> mg.number_of_patches_present_at_node array([1, 2, 1, 1, 2, 1, 0, 0, 0]) LLCATS: PINF NINF BC """ try: return self._number_of_patches_present_at_node except AttributeError: self.patches_at_node self._reset_patch_status() return self._number_of_patches_present_at_node @property @make_return_array_immutable def number_of_patches_present_at_link(self): """Return the number of patches at a link without a closed node. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((3, 3)) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.patches_present_at_link array([[ True, False], [ True, False], [ True, False], [ True, True], [ True, False], [ True, False], [ True, False], [False, False], [False, False], [False, False], [False, False], [False, False]], dtype=bool) >>> mg.number_of_patches_present_at_link array([1, 1, 1, 2, 1, 1, 1, 0, 0, 0, 0, 0]) LLCATS: PINF LINF BC """ try: return self._number_of_patches_present_at_link except AttributeError: self.patches_at_node self._reset_patch_status() return self._number_of_patches_present_at_link def _reset_patch_status(self): """ Creates the array which stores patches_present_at_node. Call whenever boundary conditions are updated on the grid. """ from landlab import RasterModelGrid, VoronoiDelaunayGrid node_status_at_patch = self.status_at_node[self.nodes_at_patch] if isinstance(self, RasterModelGrid): max_nodes_at_patch = 4 elif isinstance(self, VoronoiDelaunayGrid): max_nodes_at_patch = 3 else: max_nodes_at_patch = (self.nodes_at_patch > -1).sum(axis=1) any_node_at_patch_closed = (node_status_at_patch == CLOSED_BOUNDARY).sum(axis=1) > ( max_nodes_at_patch - 3) absent_patches = any_node_at_patch_closed[self.patches_at_node] bad_patches = numpy.logical_or(absent_patches, self.patches_at_node == -1) self._patches_present_mask = numpy.logical_not( bad_patches) self._number_of_patches_present_at_node = numpy.sum( self._patches_present_mask, axis=1) absent_patches = any_node_at_patch_closed[self.patches_at_link] bad_patches = numpy.logical_or(absent_patches, self.patches_at_link == -1) self._patches_present_link_mask = numpy.logical_not( bad_patches) self._number_of_patches_present_at_link = numpy.sum( self._patches_present_link_mask, axis=1) def calc_hillshade_at_node(self, alt=45., az=315., slp=None, asp=None, unit='degrees', elevs='topographic__elevation'): """Get array of hillshade. .. codeauthor:: Katy Barnhart <katherine.barnhart@colorado.edu> Parameters ---------- alt : float Sun altitude (from horizon) - defaults to 45 degrees az : float Sun azimuth (CW from north) - defaults to 315 degrees slp : float slope of cells at surface - optional asp : float aspect of cells at surface (from north) - optional (with slp) unit : string 'degrees' (default) or 'radians' - only needed if slp and asp are not provided If slp and asp are both not specified, 'elevs' must be provided as a grid field name (defaults to 'topographic__elevation') or an nnodes-long array of elevation values. In this case, the method will calculate local slopes and aspects internally as part of the hillshade production. Returns ------- ndarray of float Hillshade at each cell. Notes ----- code taken from GeospatialPython.com example from December 14th, 2014 DEJH found what looked like minor sign problems, and adjusted to follow the ArcGIS algorithm: http://help.arcgis.com/en/arcgisdesktop/10.0/ help/index.html#/How_Hillshade_works/009z000000z2000000/ . Remember when plotting that bright areas have high values. cmap='Greys' will give an apparently inverted color scheme. *cmap='gray'* has white associated with the high values, so is recommended for plotting. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((5, 5), 1.) >>> z = mg.x_of_node * np.tan(60. * np.pi / 180.) >>> mg.calc_hillshade_at_node(elevs=z, alt=30., az=210.) array([ 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625]) LLCATS: NINF SURF """ if slp is not None and asp is not None: if unit == 'degrees': (alt, az, slp, asp) = (numpy.radians(alt), numpy.radians(az), numpy.radians(slp), numpy.radians(asp)) elif unit == 'radians': if alt > numpy.pi / 2. or az > 2. * numpy.pi: six.print_( 'Assuming your solar properties are in degrees, ' 'but your slopes and aspects are in radians...') (alt, az) = (numpy.radians(alt), numpy.radians(az)) # ...because it would be super easy to specify radians, # but leave the default params alone... else: raise TypeError("unit must be 'degrees' or 'radians'") elif slp is None and asp is None: if unit == 'degrees': (alt, az) = (numpy.radians(alt), numpy.radians(az)) elif unit == 'radians': pass else: raise TypeError("unit must be 'degrees' or 'radians'") slp, slp_comps = self.calc_slope_at_node( elevs, return_components=True) asp = self.calc_aspect_at_node(slope_component_tuple=slp_comps, unit='radians') else: raise TypeError('Either both slp and asp must be set, or neither!') shaded = ( numpy.sin(alt) * numpy.cos(slp) + numpy.cos(alt) * numpy.sin(slp) * numpy.cos(az - asp) ) return shaded.clip(0.) @deprecated(use='calc_flux_div_at_node', version=1.0) def calculate_flux_divergence_at_core_nodes(self, active_link_flux, net_unit_flux=None): r"""Get array of flux divergence for core nodes. Given an array of fluxes along links, computes the net total flux within each cell, divides by cell area, and stores the result in net_unit_flux. The function works by calling calculate_flux_divergence_at_nodes, then slicing out only the values at core nodes. Therefore, it is slower than calculate_flux_divergence_at_nodes, even though it returns a shorter list of numbers. The input active_link_flux should be flux of something (e.g., mass, momentum, energy) per unit face width, positive if flowing in the same direction as its link, and negative otherwise. There should be one value per active link. Returns an array of net total flux per unit area, one value per core node (creates this array if it is not given as an argument). By convention, divergence is positive for net outflow, and negative for net outflow. That's why we *add* outgoing flux and *subtract* incoming flux. This makes net_unit_flux have the same sign and dimensions as a typical divergence term in a conservation equation. In general, for a polygonal cell with *N* sides of lengths Li and with surface area A, the net influx divided by cell area would be: .. math:: {Q_{net} \over A} = {1 \over A} \sum{q_i L_i} For a square cell, which is what we have in RasterModelGrid, the sum is over 4 sides of length dx, and :math:`A = dx^2`, so: .. math:: {Q_{net} \over A} = {1 \over dx} \sum{q_i} .. note:: The net flux is defined as positive outward, negative inward. In a diffusion problem, for example, one would use: .. math:: {du \over dt} = \text{source} - \text{fd} where *fd* is "flux divergence". Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((4, 5), 1.0) >>> u = [0., 1., 2., 3., 0., ... 1., 2., 3., 2., 3., ... 0., 1., 2., 1., 2., ... 0., 0., 2., 2., 0.] >>> u = np.array(u) >>> grad = rmg.calc_grad_at_link(u)[rmg.active_links] >>> grad array([ 1., 1., -1., 1., 1., -1., 1., -1., -1., -1., 1., 1., -1., 1., -1., 0., 1.]) >>> flux = - grad # downhill flux proportional to gradient >>> divflux = rmg.calculate_flux_divergence_at_core_nodes(flux) >>> divflux array([ 2., 4., -2., 0., 1., -4.]) If calculate_gradients_at_core_nodes is called inside a loop, you can improve speed slightly by creating an array outside the loop. For example, do this once, before the loop: >>> divflux = np.zeros(rmg.number_of_core_cells) # outside loop Then do this inside the loop: >>> divflux = rmg.calculate_flux_divergence_at_core_nodes( ... flux, divflux) In this case, the function will not have to create the divflux array. Note this method is untested with looped boundary conditions. LLCATS: DEPR NINF GRAD """ if self._DEBUG_TRACK_METHODS: six.print_('ModelGrid.calculate_flux_divergence_at_core_nodes') assert (len(active_link_flux) == self.number_of_active_links), \ "incorrect length of active_link_flux array" # If needed, create net_unit_flux array if net_unit_flux is None: net_unit_flux = numpy.zeros(self.number_of_core_nodes) else: net_unit_flux[:] = 0. assert (len(net_unit_flux)) == self.number_of_core_nodes node_net_unit_flux = self.calculate_flux_divergence_at_nodes( active_link_flux) node_at_core_cell = self.node_at_cell[self.core_cells] net_unit_flux = node_net_unit_flux[node_at_core_cell] return net_unit_flux @deprecated(use='calc_flux_div_at_node', version=1.0) def calculate_flux_divergence_at_nodes(self, active_link_flux, out=None): """Flux divergence at nodes. Same as calculate_flux_divergence_at_active_cells, but works with and returns a list of net unit fluxes that corresponds to all nodes, rather than just active cells. Note that we don't compute net unit fluxes at boundary nodes (which don't have active cells associated with them, and often don't have cells of any kind, because they are on the perimeter), but simply return zeros for these entries. The advantage is that the caller can work with node-based arrays instead of active-cell-based arrays. This method is untested with looped boundary conditions. LLCATS: DEPR NINF GRAD """ return gfuncs.calculate_flux_divergence_at_nodes(self, active_link_flux, out=out) @property @make_return_array_immutable def cell_area_at_node(self): """Cell areas in a nnodes-long array. Zeros are entered at all perimeter nodes, which lack cells. Returns ------- ndarray Cell areas as an n_nodes-long array. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5), spacing=(3, 4)) >>> grid.status_at_node[7] = CLOSED_BOUNDARY >>> grid.cell_area_at_node array([ 0., 0., 0., 0., 0., 0., 12., 12., 12., 0., 0., 12., 12., 12., 0., 0., 0., 0., 0., 0.]) LLCATS: CINF NINF CONN """ try: return self._cell_area_at_node except AttributeError: return self._create_cell_areas_array_force_inactive() @property @deprecated(use='width_of_face', version=1.0) def face_width(self): """ LLCATS: DEPR FINF MEAS """ return self.width_of_face @property @make_return_array_immutable def width_of_face(self): """Width of grid faces. Examples -------- >>> from landlab import RasterModelGrid, HexModelGrid >>> mg = RasterModelGrid((3, 4), (1., 2.)) >>> mg.width_of_face array([ 2., 2., 2., 1., 1., 1., 1.]) >>> mg = HexModelGrid(3, 3) >>> np.allclose(mg.width_of_face, 0.57735027) True LLCATS: FINF MEAS """ try: return self._face_width except AttributeError: return self._create_face_width() def _create_face_at_link(self): """Set up face_at_link array. Examples -------- >>> from landlab import HexModelGrid, BAD_INDEX_VALUE >>> hg = HexModelGrid(3, 3) >>> face_at_link = hg.face_at_link.copy() >>> face_at_link[face_at_link == BAD_INDEX_VALUE] = -1 >>> face_at_link # doctest: +NORMALIZE_WHITESPACE array([-1, -1, -1, 0, 1, 2, 3, -1, 4, 5, 6, -1, 7, 8, 9, 10, -1, -1, -1]) """ self._face_at_link = numpy.full(self.number_of_links, BAD_INDEX_VALUE, dtype=int) face_id = 0 for link in range(self.number_of_links): tc = self.cell_at_node[self.node_at_link_tail[link]] hc = self.cell_at_node[self.node_at_link_head[link]] if tc != BAD_INDEX_VALUE or hc != BAD_INDEX_VALUE: self._face_at_link[link] = face_id face_id += 1 return self._face_at_link def _create_link_at_face(self): """Set up link_at_face array. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg.link_at_face array([ 3, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15]) """ num_faces = len(self.width_of_face) self._link_at_face = numpy.empty(num_faces, dtype=int) face_id = 0 for link in range(self.number_of_links): tc = self.cell_at_node[self.node_at_link_tail[link]] hc = self.cell_at_node[self.node_at_link_head[link]] if tc != BAD_INDEX_VALUE or hc != BAD_INDEX_VALUE: self._link_at_face[face_id] = link face_id += 1 return self._link_at_face def _create_cell_areas_array_force_inactive(self): """Set up an array of cell areas that is n_nodes long. Sets up an array of cell areas that is nnodes long. Nodes that have cells receive the area of that cell. Nodes which do not, receive zeros. """ _cell_area_at_node_zero = numpy.zeros(self.number_of_nodes, dtype=float) _cell_area_at_node_zero[self.node_at_cell] = self.area_of_cell self._cell_area_at_node = _cell_area_at_node_zero return self._cell_area_at_node @deprecated(use='no replacement', version=1.0) def active_link_connecting_node_pair(self, node1, node2): """Get the active link that connects a pair of nodes. Returns the ID number of the active link that connects the given pair of nodes, or BAD_INDEX_VALUE if not found. This method is slow, and can only take single ints as *node1* and *node2*. It should ideally be overridden for optimal functionality in more specialized grid modules (e.g., raster). Examples -------- >>> import landlab as ll >>> rmg = ll.RasterModelGrid((4, 5)) >>> rmg.active_link_connecting_node_pair(8, 3) array([2]) LLCATS: DEPR LINF NINF CONN """ active_link = BAD_INDEX_VALUE for alink in range(0, self.number_of_active_links): link_connects_nodes = ( (self._activelink_fromnode[alink] == node1 and self._activelink_tonode[alink] == node2) or (self._activelink_tonode[alink] == node1 and self._activelink_fromnode[alink] == node2)) if link_connects_nodes: active_link = alink break return numpy.array([active_link]) @property @make_return_array_immutable def area_of_cell(self): """Get areas of grid cells. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5), spacing=(2, 3)) >>> grid.area_of_cell # doctest: +NORMALIZE_WHITESPACE array([ 6., 6., 6., 6., 6., 6.]) LLCATS: CINF MEAS """ return self._area_of_cell @property @deprecated(use='length_of_link', version=1.0) def link_length(self): """ LLCATS: DEPR LINF MEAS """ return self.length_of_link @property def length_of_link(self): """Get lengths of links. Returns ------- ndarray Lengths of all links, in ID order. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.length_of_link array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) >>> len(grid.length_of_link) == grid.number_of_links True LLCATS: LINF MEAS """ if self._link_length is None: return self._create_length_of_link() else: return self._link_length @property def _length_of_link_with_diagonals(self): """A dummy function, equivalent to `length_of_link` for the base class. This method is required to maintain grid class generality in several of the flow routing and stream power components. It is overridden in RasterModelGrid only. This method will be removed when LL's handling of diagonal links is modernized. """ return self.length_of_link def _create_length_of_link(self): """Get array of the lengths of all links. Calculates, returns, and stores as a property of the grid the lengths of all the links in the grid. """ if self._link_length is None: self._link_length = self.empty(at='link', dtype=float) diff_x = (self.node_x[self.node_at_link_tail] - self.node_x[self.node_at_link_head]) diff_y = (self.node_y[self.node_at_link_tail] - self.node_y[self.node_at_link_head]) numpy.sqrt(diff_x ** 2 + diff_y ** 2, out=self._link_length) return self._link_length @deprecated(use='map_max_of_link_nodes_to_link', version=1.0) def _assign_upslope_vals_to_active_links(self, u, v=None): """Assign upslope node value to link. Assigns to each active link the value of *u* at whichever of its neighbors has a higher value of *v*. If *v* is omitted, uses *u* for both. The order of the link values is by link ID. Parameters ---------- u : array-like Node values to assign to links. v : array-like, optional Node values to test for upslope-ness. Returns ------- ndarray Values at active links. Examples -------- >>> from landlab import RasterModelGrid >>> import numpy as np >>> grid = RasterModelGrid((3, 3)) >>> u = np.arange(9.) >>> grid._assign_upslope_vals_to_active_links(u) array([ 4., 4., 5., 7.]) LLCATS: DEPR NINF LINF CONN """ if v is None: v = numpy.array((0., )) fv = numpy.zeros(self.number_of_active_links) if len(v) < len(u): for i in range(0, self.number_of_active_links): fv[i] = max(u[self._activelink_fromnode[i]], u[self._activelink_tonode[i]]) else: for i in range(0, self.number_of_active_links): if (v[self._activelink_fromnode[i]] > v[self._activelink_tonode[i]]): fv[i] = u[self._activelink_fromnode[i]] else: fv[i] = u[self._activelink_tonode[i]] return fv def _reset_link_status_list(self): """Create of reset a list of links statuses. Creates or resets a list of link statuses. We do this by sweeping through the given lists of from and to nodes, and checking the status of these as given in the node_status list. A link is active if both its nodes are core, or if one is core and the other is fixed value. A link is inactive if either node is closed. A link is fixed if either node is fixed gradient. Note that by default, any link which has been previously set as fixed will remain so, and if a closed-core node pair is found at each of its ends, the closed node will be converted to a fixed gradient node. If you want to close a node which has a fixed link already connected to it, first change the link status to inactive. A further test is performed to ensure that the final maps of node and link status are internally consistent. """ if self._DEBUG_TRACK_METHODS: six.print_('ModelGrid._reset_link_status_list') try: already_fixed = self._status_at_link == FIXED_LINK except AttributeError: already_fixed = numpy.zeros(self.number_of_links, dtype=bool) fromnode_status = self._node_status[self.node_at_link_tail] tonode_status = self._node_status[self.node_at_link_head] if not numpy.all((fromnode_status[already_fixed] == FIXED_GRADIENT_BOUNDARY) | (tonode_status[already_fixed] == FIXED_GRADIENT_BOUNDARY)): assert numpy.all(np.logical_not((fromnode_status[already_fixed] == CLOSED_BOUNDARY) & (tonode_status[already_fixed] == CLOSED_BOUNDARY))) fromnode_status[already_fixed] = numpy.where( (fromnode_status[already_fixed] == CLOSED_BOUNDARY) & (tonode_status[already_fixed] == CORE_NODE), FIXED_GRADIENT_BOUNDARY, fromnode_status[already_fixed]) tonode_status[already_fixed] = numpy.where( (tonode_status[already_fixed] == CLOSED_BOUNDARY) & (fromnode_status[already_fixed] == CORE_NODE), FIXED_GRADIENT_BOUNDARY, tonode_status[already_fixed]) warnings.warn(""" Remember, fixed_links are dominant over node statuses. Your grid may have had an incompatibility between fixed_links and closed nodes, which has been resolved by converting the closed nodes to fixed gradient nodes. If you were trying to deliberately close a node which had once been set to fixed gradient, you need to open the links before changing the node statuses. If you were setting a node to fixed_value, you can ignore this message. """) active_links = (((fromnode_status == CORE_NODE) & ~ (tonode_status == CLOSED_BOUNDARY)) | ((tonode_status == CORE_NODE) & ~ (fromnode_status == CLOSED_BOUNDARY))) # ...this still includes things that will become fixed_link fixed_links = ((((fromnode_status == FIXED_GRADIENT_BOUNDARY) & (tonode_status == CORE_NODE)) | ((tonode_status == FIXED_GRADIENT_BOUNDARY) & (fromnode_status == CORE_NODE))) | already_fixed) fixed_link_fixed_val = (((fromnode_status == FIXED_VALUE_BOUNDARY) | (tonode_status == FIXED_VALUE_BOUNDARY)) & already_fixed) # these are the "special cases", where the user is probably trying to # adjust an individual fixed_link back to fixed value. We'll allow it: fixed_links[fixed_link_fixed_val] = False try: self._status_at_link.fill(INACTIVE_LINK) except AttributeError: self._status_at_link = numpy.empty(self.number_of_links, dtype=int) self._status_at_link.fill(INACTIVE_LINK) self._status_at_link[active_links] = ACTIVE_LINK self._status_at_link[fixed_links] = FIXED_LINK active_links = self._status_at_link == ACTIVE_LINK # now it's correct (self._active_links, ) = numpy.where(active_links) (self._fixed_links, ) = numpy.where(fixed_links) self._active_links = as_id_array(self._active_links) self._fixed_links = as_id_array(self._fixed_links) self._activelink_fromnode = self.node_at_link_tail[active_links] self._activelink_tonode = self.node_at_link_head[active_links] # Set up active inlink and outlink matrices self._setup_active_inlink_and_outlink_matrices() #self._create_links_and_link_dirs_at_node() def _reset_lists_of_nodes_cells(self): """Create of reset lists of nodes and cells based on their status. Creates or resets various lists of nodes and cells based on their statuses. Call this function whenever you make changes to the boundary conditions in the grid. The updated attributes and arrays are: * activecell_node * * corecell_node * * core_cells * _boundary_nodes Examples -------- >>> import landlab >>> grid = landlab.RasterModelGrid((4, 5)) >>> grid.status_at_node[7] = landlab.CLOSED_BOUNDARY >>> grid.core_cells array([0, 2, 3, 4, 5]) """ (self._core_nodes, ) = numpy.where(self._node_status == CORE_NODE) self._core_cells = self.cell_at_node[self._core_nodes] self._boundary_nodes = as_id_array( numpy.where(self._node_status != CORE_NODE)[0]) def _update_links_nodes_cells_to_new_BCs(self): """Update grid element connectivity, status. This method updates all of the various lists and attributes governed by node status (e.g., core nodes, active links, etc) when you change node statuses. Call it if your method or driver makes changes to the boundary conditions of nodes in the grid. """ self._reset_link_status_list() self._reset_lists_of_nodes_cells() self._create_active_faces() self._active_link_dirs_at_node[:] = self._link_dirs_at_node[:] inactive_links = (self.status_at_link[self.links_at_node] == INACTIVE_LINK) inactive_links[self.link_dirs_at_node == 0] = False self._active_link_dirs_at_node[inactive_links] = 0 try: if self.diagonal_list_created: self.diagonal_list_created = False except AttributeError: pass try: if self.neighbor_list_created: self.neighbor_list_created = False except AttributeError: pass try: self._fixed_grad_links_created except AttributeError: pass else: self._gradient_boundary_node_links() self._create_fixed_gradient_boundary_node_anchor_node() try: if self._patches_created: self._reset_patch_status() except AttributeError: pass try: self.bc_set_code += 1 except AttributeError: self.bc_set_code = 0 @deprecated(use='set_nodata_nodes_to_closed', version='0.2') def set_nodata_nodes_to_inactive(self, node_data, nodata_value): """Make no-data nodes inactive. Set the status to CLOSED_BOUNDARY for all nodes whose value of node_data is equal to the nodata_value. Parameters ---------- node_data : ndarray Data values. nodata_value : float Value that indicates an invalid value. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4), 1.0) >>> mg.status_at_node array([1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8) >>> h = np.array([-9999, -9999, -9999, -9999, ... -9999, -9999, 12345., 0., ... -9999, 0., 0., 0.]) >>> mg.set_nodata_nodes_to_inactive(h, -9999) >>> mg.status_at_node array([4, 4, 4, 4, 4, 4, 0, 1, 4, 1, 1, 1], dtype=int8) LLCATS: DEPR NINF BC """ self.set_nodata_nodes_to_closed(node_data, nodata_value) def set_nodata_nodes_to_closed(self, node_data, nodata_value): """Make no-data nodes closed boundaries. Sets node status to :any:`CLOSED_BOUNDARY` for all nodes whose value of *node_data* is equal to the *nodata_value*. Any links connected to :any:`CLOSED_BOUNDARY` nodes are automatically set to :any:`INACTIVE_LINK` boundary. Parameters ---------- node_data : ndarray Data values. nodata_value : float Value that indicates an invalid value. Examples -------- The following example uses the following grid:: *--I--->o------>o------>o ^ ^ ^ ^ I I | | | | | | *--I--->*--I--->o------>o ^ ^ ^ ^ I I I I | | | | *--I--->*--I--->*--I--->* .. note:: Links set to :any:`ACTIVE_LINK` are not shown in this diagram. ``*`` indicates the nodes that are set to :any:`CLOSED_BOUNDARY` ``o`` indicates the nodes that are set to :any:`CORE_NODE` ``I`` indicates the links that are set to :any:`INACTIVE_LINK` >>> import numpy as np >>> import landlab as ll >>> mg = ll.RasterModelGrid((3, 4), 1.0) >>> mg.status_at_node array([1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8) >>> h = np.array([-9999, -9999, -9999, -9999, -9999, -9999, 12345., ... 0., -9999, 0., 0., 0.]) >>> mg.set_nodata_nodes_to_closed(h, -9999) >>> mg.status_at_node array([4, 4, 4, 4, 4, 4, 0, 1, 4, 1, 1, 1], dtype=int8) LLCATS: BC NINF """ # Find locations where value equals the NODATA code and set these nodes # as inactive boundaries. nodata_locations = numpy.nonzero(node_data == nodata_value) self._node_status[nodata_locations] = CLOSED_BOUNDARY # Recreate the list of active cell IDs self._update_links_nodes_cells_to_new_BCs() def set_nodata_nodes_to_fixed_gradient(self, node_data, nodata_value): """Make no-data nodes fixed gradient boundaries. Set node status to :any:`FIXED_GRADIENT_BOUNDARY` for all nodes whose value of *node_data* is equal to *nodata_value*. Any links between :any:`FIXED_GRADIENT_BOUNDARY` nodes and :any:`CORE_NODES` are automatically set to :any:`FIXED_LINK` boundary status. Parameters ---------- node_data : ndarray Data values. nodata_value : float Value that indicates an invalid value. Examples -------- The following examples use this grid:: *--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->* ^ ^ ^ ^ ^ ^ ^ ^ ^ I I I X X X X X I | | | | | | | | | *--I--->*--I--->*--X--->o o o o o--X--->* ^ ^ ^ ^ ^ ^ ^ ^ ^ I I I | | | | | I | | | | | | | | | *--I--->*--I--->*--X--->o o o o o--X--->* ^ ^ ^ ^ ^ ^ ^ ^ ^ I I I X X X X X I | | | | | | | | | *--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->* .. note:: Links set to :any:`ACTIVE_LINK` are not shown in this diagram. ``X`` indicates the links that are set to :any:`FIXED_LINK` ``I`` indicates the links that are set to :any:`INACTIVE_LINK` ``o`` indicates the nodes that are set to :any:`CORE_NODE` ``*`` indicates the nodes that are set to :any:`FIXED_GRADIENT_BOUNDARY` >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((4, 9)) >>> rmg.status_at_node # doctest: +NORMALIZE_WHITESPACE array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int8) >>> z = rmg.zeros(at='node') >>> z = np.array([ ... -99., -99., -99., -99., -99., -99., -99., -99., -99., ... -99., -99., -99., 0., 0., 0., 0., 0., -99., ... -99., -99., -99., 0., 0., 0., 0., 0., -99., ... -99., -99., -99., -99., -99., -99., -99., -99., -99.]) >>> rmg.set_nodata_nodes_to_fixed_gradient(z, -99) >>> rmg.status_at_node # doctest: +NORMALIZE_WHITESPACE array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int8) >>> rmg.status_at_link # doctest: +NORMALIZE_WHITESPACE array([4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 4, 4, 4, 2, 0, 0, 0, 0, 2, 4, 4, 4, 0, 0, 0, 0, 0, 4, 4, 4, 2, 0, 0, 0, 0, 2, 4, 4, 4, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4]) LLCATS: BC NINF """ # Find locations where value equals the NODATA code and set these nodes # as inactive boundaries. nodata_locations = numpy.nonzero(node_data == nodata_value) self._node_status[nodata_locations] = FIXED_GRADIENT_BOUNDARY # Recreate the list of active cell IDs self._update_links_nodes_cells_to_new_BCs() @deprecated(use='map_max_of_link_nodes_to_link', version=1.0) def max_of_link_end_node_values(self, node_data): """Maximum value at the end of links. For each active link, finds and returns the maximum value of node_data at either of the two ends. Use this, for example, if you want to find the maximum value of water depth at linked pairs of nodes (by passing in an array of water depth values at nodes). Parameters ---------- node_data : ndarray Values at grid nodes. Returns ------- ndarray : Maximum values whose length is the number of active links. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4), spacing=(1., 1.)) >>> h = np.array([ 2., 2., 8., 0., ... 8., 0., 3., 0., ... 5., 6., 8., 3.]) >>> grid.max_of_link_end_node_values(h) array([ 2., 8., 8., 3., 3., 6., 8.]) Note that this method is *deprecatd*. The alternative is to use ``map_max_of_link_nodes_to_link``. >>> vals = grid.map_max_of_link_nodes_to_link(h) >>> vals[grid.active_links] array([ 2., 8., 8., 3., 3., 6., 8.]) LLCATS: DEPR LINF NINF CONN """ return numpy.maximum(node_data[self._activelink_fromnode], node_data[self._activelink_tonode]) def _calc_numbers_of_node_neighbors(self): """Number of neighbor nodes. Calculates the number of neighboring nodes for each node, and returns the result as a 1D numpy array. Used to find the maximum number of neighbors, so that inlink and outlink matrices can be dimensioned accordingly. Assumes that self.number_of_nodes, self.node_at_link_tail, and self.node_at_link_head have already been set up. Algorithm works by simply looping through all links; for each, the endpoints are neighbors of one another, so we increment the number of neighbors for both the endpoint nodes. """ num_nbrs = numpy.zeros(self.number_of_nodes, dtype=int) for link in range(self.number_of_links): num_nbrs[self.node_at_link_tail[link]] += 1 num_nbrs[self.node_at_link_head[link]] += 1 return num_nbrs def _create_active_faces(self): self._active_faces = self.face_at_link[self.active_links] return self._active_faces @deprecated(use='no replacement', version=1.0) def _setup_inlink_and_outlink_matrices(self): """Create data structured for number of inlinks and outlinks. Creates data structures to record the numbers of inlinks and outlinks for each node. An inlink of a node is simply a link that has the node as its "to" node, and an outlink is a link that has the node as its "from". We store the inlinks in an NM-row by num_nodes-column matrix called _node_inlink_matrix. NM is the maximum number of neighbors for any node. We also keep track of the total number of inlinks and outlinks at each node in the num_inlinks and num_outlinks arrays. The inlink and outlink matrices are useful in numerical calculations. Each row of each matrix contains one inlink or outlink per node. So, if you have a corresponding "flux" matrix, you can map incoming or outgoing fluxes onto the appropriate nodes. More information on this is in the various calculate_flux_divergence... functions. What happens if a given node does not have two inlinks or outlinks? We simply put the default value -1 in this case. This allows us to use a cute little trick when computing inflows and outflows. We make our "flux" array one element longer than the number of links, with the last element containing the value 0. Thus, any time we add an influx from link number -1, Python takes the value of the last element in the array, which is zero. By doing it this way, we maintain the efficiency that comes with the use of numpy. Again, more info can be found in the description of the flux divergence functions. """ # Find the maximum number of neighbors for any node num_nbrs = self._calc_numbers_of_node_neighbors() self.max_num_nbrs = numpy.amax(num_nbrs) # Create active in-link and out-link matrices. self._node_inlink_matrix = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) self._node_outlink_matrix = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) # Set up the inlink arrays tonodes = self.node_at_link_head self._node_numinlink = numpy.bincount(tonodes, minlength=self.number_of_nodes) counts = count_repeated_values(self.node_at_link_head) for (count, (tonodes, link_ids)) in enumerate(counts): self._node_inlink_matrix[count][tonodes] = link_ids # Set up the outlink arrays fromnodes = self.node_at_link_tail self._node_numoutlink = numpy.bincount(fromnodes, minlength=self.number_of_nodes) counts = count_repeated_values(self.node_at_link_tail) for (count, (fromnodes, link_ids)) in enumerate(counts): self._node_outlink_matrix[count][fromnodes] = link_ids @deprecated(use='no replacement', version=1.0) def _setup_active_inlink_and_outlink_matrices(self): """Create data structures for number of active inlinks and outlinks. Creates data structures to record the numbers of active inlinks and active outlinks for each node. These data structures are equivalent to the "regular" inlink and outlink matrices, except that it uses the IDs of active links (only). Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 2) >>> hg._node_numactiveinlink array([0, 0, 0, 3, 1, 1, 1]) >>> hg._node_active_inlink_matrix2 array([[-1, -1, -1, 2, 6, 8, 9], [-1, -1, -1, 3, -1, -1, -1], [-1, -1, -1, 5, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]]) >>> hg._node_numactiveoutlink array([1, 1, 1, 3, 0, 0, 0]) >>> hg._node_active_outlink_matrix2 array([[ 2, 3, 5, 6, -1, -1, -1], [-1, -1, -1, 8, -1, -1, -1], [-1, -1, -1, 9, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]]) """ # Create active in-link and out-link matrices. self._node_active_inlink_matrix = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) self._node_active_outlink_matrix = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) # Set up the inlink arrays tonodes = self._activelink_tonode self._node_numactiveinlink = as_id_array(numpy.bincount( tonodes, minlength=self.number_of_nodes)) counts = count_repeated_values(self._activelink_tonode) for (count, (tonodes, active_link_ids)) in enumerate(counts): self._node_active_inlink_matrix[count][tonodes] = active_link_ids # Set up the outlink arrays fromnodes = self._activelink_fromnode self._node_numactiveoutlink = as_id_array(numpy.bincount( fromnodes, minlength=self.number_of_nodes)) counts = count_repeated_values(self._activelink_fromnode) for (count, (fromnodes, active_link_ids)) in enumerate(counts): self._node_active_outlink_matrix[count][fromnodes] = active_link_ids # THE FOLLOWING IS MEANT TO REPLACE THE ABOVE CODE, USING LINK IDS # FOR ACTIVE LINKS (ONLY), INSTEAD OF "ACTIVE LINK IDS". THE POINT IS # TO HAVE JUST ONE ID/NUMBERING SYSTEM FOR LINKS, RATHER THAN A # SEPARATE NUMBERING SYSTEM FOR ACTIVE LINKS # GT JUNE 2015 # TODO: CLEAN THIS UP # Create AN ALTERNATIVE VERSION OF active in-link and out-link # matrices, WHICH WILL EVENTUALLY REPLACE THE ONE ABOVE (AND BE # RENAMED TO GET RID OF THE "2") # TODO: MAKE THIS CHANGE ONCE CODE THAT USES IT HAS BEEN PREPPED self._node_active_inlink_matrix2 = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) self._node_active_outlink_matrix2 = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) # Set up the inlink arrays tonodes = self.node_at_link_head[self.active_links] self._node_numactiveinlink = as_id_array(numpy.bincount( tonodes, minlength=self.number_of_nodes)) # OK, HERE WE HAVE TO MAKE A CHANGE, BECAUSE THE INDICES RETURNED BY # count_repeated_values ARE "ACTIVE LINK INDICES", WHICH WE ARE NO # LONGER USING. HAVE TO TURN THESE BACK INTO LINK IDS. I THINK WE CAN # DO THIS BY CHANGING active_link_ids TO # self.active_links[active_link_ids] BUT HAVEN'T MADE THIS CHANGE YET. # NEED TO WORK THROUGH EXAMPLE 3,2 HMG counts = count_repeated_values( self.node_at_link_head[self.active_links]) for (count, (tonodes, active_link_ids)) in enumerate(counts): self._node_active_inlink_matrix2[count][ tonodes] = self.active_links[active_link_ids] # Set up the outlink arrays fromnodes = self.node_at_link_tail[self.active_links] self._node_numactiveoutlink = as_id_array(numpy.bincount( fromnodes, minlength=self.number_of_nodes)) counts = count_repeated_values(self._activelink_fromnode) for (count, (fromnodes, active_link_ids)) in enumerate(counts): self._node_active_outlink_matrix2[count][ fromnodes] = self.active_links[active_link_ids] def _create_link_unit_vectors(self): """Make arrays to store the unit vectors associated with each link. Creates self.link_unit_vec_x and self.link_unit_vec_y. These contain, for each link, the x and y components of the link's unit vector (that is, the link's x and y dimensions if it were shrunk to unit length but retained its orientation). The length of these arrays is the number of links plus one. The last entry in each array is set to zero, and is used to handle references to "link -1" (meaning, a non-existent link, whose unit vector is (0,0)). Also builds arrays to store the unit-vector component sums for each node: node_unit_vector_sum_x and node_unit_vector_sum_y. These are designed to be used when mapping link vector values to nodes (one takes the average of the x- and y-components of all connected links). Notes ----- Creates the following: * ``self.link_unit_vec_x``, ``self.link_unit_vec_y`` : ndarray x and y components of unit vectors at each link (extra 0 entries @ end) * ``self.node_vector_sum_x``, ``self.node_vector_sum_y`` : ndarray Sums of x & y unit vector components for each node. Sum is over all links connected to a given node. Examples -------- The example below is a seven-node hexagonal grid, with six nodes around the perimeter and one node (#3) in the interior. There are four horizontal links with unit vector (1,0), and 8 diagonal links with unit vector (+/-0.5, +/-sqrt(3)/2) (note: sqrt(3)/2 ~ 0.866). .. note:: This example assumes that the triangulation places links in a certain order. Because the order is arbitrary, this might break on different platforms. If that happens, the example needs to be made generic somehow ... >>> import landlab as ll >>> hmg = ll.HexModelGrid(3, 2, 2.0) >>> hmg.link_unit_vec_x # doctest: +NORMALIZE_WHITESPACE array([ 1. , -0.5, 0.5, -0.5, 0.5, 1. , 1. , 0.5, -0.5, 0.5, -0.5, 1. , 0. ]) >>> hmg.link_unit_vec_y array([ 0. , 0.8660254, 0.8660254, 0.8660254, 0.8660254, 0. , 0. , 0.8660254, 0.8660254, 0.8660254, 0.8660254, 0. , 0. ]) >>> hmg.node_unit_vector_sum_x array([ 2., 2., 2., 4., 2., 2., 2.]) >>> hmg.node_unit_vector_sum_y array([ 1.73205081, 1.73205081, 1.73205081, 3.46410162, 1.73205081, 1.73205081, 1.73205081]) """ nodes_at_link = ((self.node_at_link_tail, self.node_at_link_head), ) unit_vec_at_link = np.zeros((self.number_of_links + 1, 2), dtype=float) unit_vec_at_link[:-1, 0] = np.diff(self.x_of_node[nodes_at_link], axis=0) / self.length_of_link unit_vec_at_link[:-1, 1] = np.diff(self.y_of_node[nodes_at_link], axis=0) / self.length_of_link # unit_vec_at_link[:-1] /= self.length_of_link.reshape((-1, 1)) self._unit_vec_at_node = np.abs(unit_vec_at_link[self.links_at_node]).sum(axis=1) self._node_unit_vector_sum_x = self._unit_vec_at_node[:, 0] self._node_unit_vector_sum_y = self._unit_vec_at_node[:, 1] self._link_unit_vec_x = unit_vec_at_link[:, 0] self._link_unit_vec_y = unit_vec_at_link[:, 1] @property def unit_vector_xcomponent_at_link(self): """Get array of x-component of unit vector for links. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> len(grid.unit_vector_xcomponent_at_link) == grid.number_of_links + 1 True >>> grid.unit_vector_xcomponent_at_link # doctest: +NORMALIZE_WHITESPACE array([ 1., 1., 0., 0., 0., 1., 1., 0., 0., 0., 1., 1., 0.]) LLCATS: LINF MEAS """ if self._link_unit_vec_x is None: self._create_link_unit_vectors() return self._link_unit_vec_x @property @deprecated(use='unit_vector_xcomponent_at_link', version='0.5') def link_unit_vec_x(self): """ LLCATS: DEPR LINF MEAS """ return self.unit_vector_xcomponent_at_link @property def unit_vector_ycomponent_at_link(self): """Get array of y-component of unit vector for links. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> len(grid.unit_vector_ycomponent_at_link) == grid.number_of_links + 1 True >>> grid.unit_vector_ycomponent_at_link # doctest: +NORMALIZE_WHITESPACE array([ 0., 0., 1., 1., 1., 0., 0., 1., 1., 1., 0., 0., 0.]) LLCATS: LINF MEAS """ if self._link_unit_vec_y is None: self._create_link_unit_vectors() return self._link_unit_vec_y @property @deprecated(use='unit_vector_xcomponent_at_link', version='0.5') def link_unit_vec_y(self): """ LLCATS: DEPR LINF MEAS """ return self.unit_vector_ycomponent_at_link @property def unit_vector_sum_xcomponent_at_node(self): """Get array of x-component of unit vector sums at each node. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> len(grid.unit_vector_sum_xcomponent_at_node) == grid.number_of_nodes True >>> grid.unit_vector_sum_xcomponent_at_node array([ 1., 2., 1., 1., 2., 1., 1., 2., 1.]) LLCATS: NINF MEAS """ if self._node_unit_vector_sum_x is None: self._create_link_unit_vectors() return self._node_unit_vector_sum_x @property @deprecated(use='unit_vector_sum_xcomponent_at_node', version='0.5') def node_unit_vector_sum_x(self): """ LLCATS: DEPR NINF MEAS """ return self.unit_vector_sum_xcomponent_at_node @property def unit_vector_sum_ycomponent_at_node(self): """Get array of y-component of unit vector sums at each node. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> len(grid.unit_vector_sum_ycomponent_at_node) == grid.number_of_nodes True >>> grid.unit_vector_sum_ycomponent_at_node array([ 1., 1., 1., 2., 2., 2., 1., 1., 1.]) LLCATS: NINF MEAS """ if self._node_unit_vector_sum_y is None: self._create_link_unit_vectors() return self._node_unit_vector_sum_y @property @deprecated(use='unit_vector_sum_ycomponent_at_node', version='0.5') def node_unit_vector_sum_y(self): """ LLCATS: DEPR NINF MEAS """ return self.unit_vector_sum_ycomponent_at_node def map_link_vector_to_nodes(self, q): r"""Map data defined on links to nodes. Given a variable defined on links, breaks it into x and y components and assigns values to nodes by averaging each node's attached links. Parameters ---------- q : ndarray of floats (1D, length = number of links in grid) Variable defined on links Returns ------- ndarray, ndarray x and y components of variable mapped to nodes (1D, length = number of nodes) See Also -------- _create_link_unit_vectors : sets up unit vectors at links and unit-vector sums at nodes Notes ----- THIS ALGORITHM IS NOT CORRECT AND NEEDS TO BE CHANGED! The concept here is that q contains a vector variable that is defined at each link. The magnitude is given by the value of q, and the direction is given by the orientation of the link, as described by its unit vector. To map the link-vector values to the nodes, we break the values into x- and y-components according to each link's unit vector. The x-component of q at a node is a weighted sum of the x-components of the links that are attached to that node. A good way to appreciate this is by example. Consider a 3x4 raster grid:: 8--14---9--15--10--16--11 | | | | 4 5 6 7 | | | | 4--11---5---12--6---13--7 | | | | 0 1 2 3 | | | | 0---8---1---9---2--10---3 Imagine that for each node, we were to add up the unit vector components for each connected link; in other words, add up all the x components of the unit vectors associated with each link, and add up all the y components. Here's what that would look like for the above grid ("vsx" and "vsy" stand for "vector sum x" and "vector sum y"): * Corner nodes (0, 3, 8, 11): vsx = 1, vsy = 1 * Bottom and top nodes (1-2, 9-10): vsx = 2, vsy = 1 * Left and right nodes (4, 7): vsx = 1, vsy = 2 * All others: vsx = 2, vsy = 2 The process of creating unit-vector sums at nodes is handled by ModelGrid._create_link_unit_vectors() (and, for raster grids, by the overriding method RasterModelGrid._create_link_unit_vectors()). The node unit-vector sums are then stored in self.node_unit_vector_sum_x and self.node_unit_vector_sum_y. How would you use this? Suppose you have a vector variable q defined at links. What's the average at the nodes? We'll define the average as follows. The terminology here is: :math:`q = (u,v)` represents the vector quantity defined at links, :math:`Q = (U,V)` represents its definition at nodes, :math:`(m,n)` represents the unit vector components at a link, and :math:`(S_x,S_y)` represents the unit-vector sum at a given node. .. math:: U_i = \sum_{j=1}^{L_i} q_j m_j / S_{xi} V_i = \sum_{j=1}^{L_i} q_j n_j / S_{yi} Suppose that the vector q is uniform and equal to one. Then, at node 0 in the above grid, this works out to:: U_0 = (q_0 m_0) / 1 + (q_8 m_8) / 1 = (1 0)/ 1 + (1 1)/1 = 1 V_0 = (q_0 n_0) / 1 + (q_8 n_8) / 1 = (1 1) / 1 + (1 0) / 1 = 1 At node 1, in the bottom row but not a corner, we add up the values of **q** associated with THREE links. The x-vector sum of these links is 2 because there are two horizontal links, each with an x- unit vector value of unity. The y-vector sum is 1 because only one of the three (link #1) has a non-zero y component (equal to one). Here is how the numbers work out:: U_1 = (q_1 m_1) / 2 + (q_8 m_8) / 2 + (q_9 m_9) / 2 = (1 0) / 2 + (1 1) / 2 + (1 1) / 2 = 1 V_1 = (q_1 n_1) / 1 + (q_8 n_8) / 1 + (q_9 n_9) / 1 = (1 1) / 1 + (1 0) / 1 + (1 0) / 1 = 1 At node 5, in the interior, there are four connected links (two in-links and two out-links; two horizontal and two vertical). So, we add up the q values associated with all four:: U_5 = (q_1 m_1) / 2 + (q_5 m_5) / 2 + (q_11 m_11) / 2 + (q_12 m_12) / 2 = (1 0) / 2 + (1 0) / 2 + (1 1) / 2 + (1 1) / 2 = 1 V_5 = (q_1 n_1) / 2 + (q_5 n_5) / 2 + (q_11 n_11) / 2 + (q_12 n_12) / 2 = (1 1) / 2 + (1 1) / 2 + (1 0) / 2 + (1 0) / 2 = 1 To do this calculation efficiently, we use the following algorithm:: FOR each row in _node_inlink_matrix (representing one inlink @ each node) Multiply the link's q value by its unit x component ... ... divide by node's unit vector sum in x ... ... and add it to the node's total q_x Multiply the link's q value by its unit y component ... ... divide by node's unit vector sum in y ... ... and add it to the node's total q_y Examples -------- **Example 1** q[:] = 1. Vector magnitude is :math:`\sqrt{2}`, direction is :math:`(1,1)`. >>> import numpy as np >>> import landlab as ll >>> rmg = ll.RasterModelGrid((3, 4), spacing=(2., 2.)) >>> rmg.node_unit_vector_sum_x array([ 1., 2., 2., 1., 1., 2., 2., 1., 1., 2., 2., 1.]) >>> rmg.node_unit_vector_sum_y array([ 1., 1., 1., 1., 2., 2., 2., 2., 1., 1., 1., 1.]) >>> q = np.ones(rmg.number_of_links) >>> nvx, nvy = rmg.map_link_vector_to_nodes(q) >>> nvx array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) >>> nvy array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) **Example 2** Vector magnitude is 5, angle is 30 degrees from horizontal, forming a 3-4-5 triangle. >>> q = np.array([4., 4., 4., 3., 3., 3., 3., ... 4., 4., 4., 3., 3., 3., 3., ... 4., 4., 4]) >>> nvx, nvy = rmg.map_link_vector_to_nodes(q) >>> nvx array([ 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4.]) >>> nvy array([ 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]) ..todo:: Fix and finish example 3 below. Example 3: Hexagonal grid with vector as above. Here, q is pre-calculated to have the right values to represent a uniform vector with magnitude 5 and orientation 30 degrees counter-clockwise from horizontal. LLCATS: NINF LINF CONN MAP """ # Create the arrays to hold the node-based values of the x and y # components of the vector (q) node_vec_x = numpy.zeros(self.number_of_nodes) node_vec_y = numpy.zeros(self.number_of_nodes) # Break the link-based vector input variable, q, into x- and # y-components. # Notes: # 1) We make the arrays 1 element longer than the number of links, # so that references to -1 in the node-link matrices will refer # to the last element of these two arrays, which will contain # zeros. (Same trick as in the flux divergence functions) # 2) This requires memory allocation. Because this function might be # called repeatedly, it would be good to find a way to # pre-allocate to improve speed. qx = numpy.zeros(self.number_of_links + 1) qy = numpy.zeros(self.number_of_links + 1) qx[:self.number_of_links] = q * \ self.link_unit_vec_x[:self.number_of_links] qy[:self.number_of_links] = q * \ self.link_unit_vec_y[:self.number_of_links] # Loop over each row in the _node_inlink_matrix and _node_outlink_matrix. # This isn't a big loop! In a raster grid, these have only two rows # each; in an unstructured grid, it depends on the grid geometry; # for a hex grid, there are up to 6 rows. n_matrix_rows = numpy.size(self._node_inlink_matrix, 0) for i in range(n_matrix_rows): node_vec_x += qx[self._node_inlink_matrix[i, :]] node_vec_x += qx[self._node_outlink_matrix[i, :]] node_vec_y += qy[self._node_inlink_matrix[i, :]] node_vec_y += qy[self._node_outlink_matrix[i, :]] node_vec_x /= self.node_unit_vector_sum_x node_vec_y /= self.node_unit_vector_sum_y return node_vec_x, node_vec_y @deprecated(use='plot.imshow_grid', version=1.0) def display_grid(self, draw_voronoi=False): """Display the grid. LLCATS: DEPR GINF """ import matplotlib.pyplot as plt # Plot nodes, colored by boundary vs interior plt.plot(self.node_x[self.core_nodes], self.node_y[self.core_nodes], 'go') plt.plot(self.node_x[self.boundary_nodes], self.node_y[self.boundary_nodes], 'ro') # Draw links for i in range(self.number_of_links): plt.plot([self.node_x[self.node_at_link_tail[i]], self.node_x[self.node_at_link_head[i]]], [self.node_y[self.node_at_link_tail[i]], self.node_y[self.node_at_link_head[i]]], 'k-') # Draw active links for link in self._active_links: plt.plot([self.node_x[self.node_at_link_tail[link]], self.node_x[self.node_at_link_head[link]]], [self.node_y[self.node_at_link_tail[link]], self.node_y[self.node_at_link_head[link]]], 'g-') # If caller asked for a voronoi diagram, draw that too if draw_voronoi: from scipy.spatial import Voronoi, voronoi_plot_2d pts = numpy.zeros((self.number_of_nodes, 2)) pts[:, 0] = self.node_x pts[:, 1] = self.node_y vor = Voronoi(pts) voronoi_plot_2d(vor) plt.show() @deprecated(use='node_is_boundary', version=1.0) def is_boundary(self, ids, boundary_flag=None): """ LLCATS: DEPR NINF BC """ return self.node_is_boundary(ids, boundary_flag=boundary_flag) def node_is_boundary(self, ids, boundary_flag=None): """Check if nodes are boundary nodes. Check if nodes at given *ids* are boundary nodes. Use the *boundary_flag* to specify a particular boundary type status flag. Parameters ---------- ids : ndarray Node IDs to check. boundary_flag : int, optional A boundary type to check for. Returns ------- ndarray Array of booleans indicating if nodes are boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5)) >>> mg.node_is_boundary([0, 6]) array([ True, False], dtype=bool) >>> mg.node_is_boundary([0, 6], boundary_flag=CLOSED_BOUNDARY) array([False, False], dtype=bool) LLCATS: NINF BC """ if boundary_flag is None: return ~ (self._node_status[ids] == CORE_NODE) else: return self._node_status[ids] == boundary_flag def _assign_boundary_nodes_to_grid_sides(self): """Assign boundary nodes to a quadrant. For each boundary node, determines whether it belongs to the left, right, top or bottom of the grid, based on its distance from the grid's centerpoint (mean (x,y) position). Returns lists of nodes on each of the four grid sides. Assumes self.status_at_node, self.number_of_nodes, self.boundary_nodes, self._node_x, and self._node_y have been initialized. Returns ------- tuple of array_like Tuple of nodes in each coordinate. Nodes are grouped as (*east*, *north*, *west*, *south*). Examples -------- >>> import landlab as ll >>> m = ll.HexModelGrid(5, 3, 1.0) >>> [r,t,l,b] = m._assign_boundary_nodes_to_grid_sides() >>> l array([ 7, 12, 3]) >>> r array([11, 15, 6]) >>> t array([16, 18, 17]) >>> b array([0, 2, 1]) """ # Calculate x and y distance from centerpoint diff_x = self.node_x[self.boundary_nodes] - numpy.mean(self.node_x) diff_y = self.node_y[self.boundary_nodes] - numpy.mean(self.node_y) return _sort_points_into_quadrants(diff_x, diff_y, self.boundary_nodes) @deprecated(use='status_at_node', version=1.0) def set_closed_nodes(self, nodes): """Make nodes closed boundaries. Sets the given nodes' boundary condition statuses to CLOSED_BOUNDARY (==4), and resets the list of active links to reflect any changes. LLCATS: DEPR NINF BC """ self._node_status[nodes] = CLOSED_BOUNDARY self._update_links_nodes_cells_to_new_BCs() def calc_distances_of_nodes_to_point(self, coord, get_az=None, node_subset=None, out_distance=None, out_azimuth=None): """Get distances for nodes to a given point. Returns an array of distances for each node to a provided point. If "get_az" is set to 'angles', returns both the distance array and an array of azimuths from up/north. If it is set to 'displacements', it returns the azimuths as a 2xnnodes array of x and y displacements. If it is not set, returns just the distance array. If "node_subset" is set as an ID, or list/array/etc of IDs method returns just the distance (and optionally azimuth) for that node. Point is provided as a tuple (x,y). If out_distance (& out_azimuth) are provided, these arrays are used to store the outputs. This is recommended for memory management reasons if you are working with node subsets. .. note:: Angles are returned in radians but measured clockwise from north. Parameters ---------- coord : tuple of float Coodinates of point as (x, y). get_az: {None, 'angles', 'displacements'}, optional Optionally calculate azimuths as either angles or displacements. The calculated values will be returned along with the distances as the second item of a tuple. node_subset : array_like, optional Calculate distances on a subset of grid nodes. The default is to calculate distances from the provided points to all nodes. out_distance : array_like, optional If provided, put the calculated distances here. Otherwise, create a new array. out_azimuth : array_like, optional If provided, put the calculated distances here. Otherwise, create a new array. Returns ------- ndarray or tuple of ndarray If *get_az* is ``None`` return the array of distances. Otherwise, return a tuple of distances and azimuths. Notes ----- Once you start working with node subsets in Landlab, which can change size between loops, it's quite possible for Python's internal memory management to crap out after large numbers of loops (~>10k). This is to do with the way it block allocates memory for arrays of differing lengths, then cannot free this memory effectively. The solution - as implemented here - is to pre-allocate all arrays as nnodes long, then only work with the first [len_subset] entries by slicing (in a pseudo-C-style). Care has to be taken not to "accidentally" allow Python to allocate a new array you don't have control over. Then, to maintain efficient memory allocation, we create some "dummy" nnode-long arrays to store intermediate parts of the solution in. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) Calculate distances from point at (2., 1.) to a subset of nodes on the grid. >>> grid.calc_distances_of_nodes_to_point((2, 1), ... node_subset=(2, 6, 7, 8, 12)) array([ 1., 1., 0., 1., 1.]) Calculate distances from a point to all nodes on the grid. >>> dist = grid.calc_distances_of_nodes_to_point((2, 1)) >>> dist.shape == (grid.number_of_nodes, ) True >>> dist.take((2, 6, 7, 8, 12)) array([ 1., 1., 0., 1., 1.]) Put the distances into a buffer. >>> out = np.empty(grid.number_of_nodes, dtype=float) >>> dist = grid.calc_distances_of_nodes_to_point((2, 1), ... out_distance=out) >>> out is dist True >>> out.take((2, 6, 7, 8, 12)) array([ 1., 1., 0., 1., 1.]) Calculate azimuths along with distances. The azimuths are calculated in radians but measured clockwise from north. >>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1), ... get_az='angles') >>> azim.take((2, 6, 7, 8, 12)) * 180. / np.pi array([ 180., 270., 0., 90., 0.]) >>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1), ... get_az='angles', node_subset=(1, 3, 11, 13)) >>> azim * 180. / np.pi array([ 225., 135., 315., 45.]) When calculating displacements, the first row contains displacements in x and the second displacements in y. >>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1), ... get_az='displacements', node_subset=(2, 6, 7, 8, 12)) >>> azim array([[ 0., -1., 0., 1., 0.], [-1., 0., 0., 0., 1.]]) LLCATS: NINF MEAS """ if len(coord) != 2: raise ValueError('coordinate must iterable of length 2') if get_az not in (None, 'displacements', 'angles'): raise ValueError('get_az not understood') if node_subset is not None and numpy.any(numpy.isnan(node_subset)): node_subset = None if node_subset is not None: if not isinstance(node_subset, numpy.ndarray): node_subset = numpy.array(node_subset) node_subset = node_subset.reshape((-1, )) len_subset = node_subset.size else: len_subset = self.number_of_nodes if out_distance is None: out_distance = numpy.empty(len_subset, dtype=numpy.float) if out_distance.size != len_subset: raise ValueError('output array size mismatch for distances') if get_az is not None: if get_az == 'displacements': az_shape = (2, len_subset) else: az_shape = (len_subset, ) if out_azimuth is None: out_azimuth = numpy.empty(az_shape, dtype=numpy.float) if out_azimuth.shape != az_shape: raise ValueError('output array mismatch for azimuths') azimuths_as_displacements = numpy.empty((2, self.number_of_nodes)) dummy_nodes_1 = numpy.empty(self.number_of_nodes) dummy_nodes_2 = numpy.empty(self.number_of_nodes) dummy_nodes_3 = numpy.empty(self.number_of_nodes) if node_subset is None: azimuths_as_displacements[0] = (self.node_x - coord[0]) azimuths_as_displacements[1] = (self.node_y - coord[1]) else: azimuths_as_displacements[0, :len_subset] = ( self.node_x[node_subset] - coord[0]) azimuths_as_displacements[1, :len_subset] = ( self.node_y[node_subset] - coord[1]) numpy.square(azimuths_as_displacements[0, :len_subset], out=dummy_nodes_1[:len_subset]) numpy.square(azimuths_as_displacements[1, :len_subset], out=dummy_nodes_2[:len_subset]) numpy.add(dummy_nodes_1[:len_subset], dummy_nodes_2[:len_subset], out=dummy_nodes_3[:len_subset]) numpy.sqrt(dummy_nodes_3[:len_subset], out=out_distance) if get_az: if get_az == 'displacements': out_azimuth[:] = azimuths_as_displacements[:, :len_subset] elif get_az == 'angles': numpy.arctan2( azimuths_as_displacements[0, :len_subset], azimuths_as_displacements[1, :len_subset], out=out_azimuth[:len_subset]) less_than_zero = numpy.empty(self.number_of_nodes, dtype=bool) numpy.less(out_azimuth, 0., out=less_than_zero[:len_subset]) out_azimuth[less_than_zero[:len_subset]] += 2. * numpy.pi return out_distance, out_azimuth else: return out_distance @property def all_node_distances_map(self): """Get distances from every node to every other node. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> distances = grid.all_node_distances_map The shape of the array is ``number_of_nodes`` by ``number_of_nodes`` and distance from a node to itself is zero. >>> distances.shape == (grid.number_of_nodes, grid.number_of_nodes) True >>> distances.diagonal() array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) The distances from the first node to all nodes in its row and all the nodes in its column. >>> distances[0, :4] array([ 0., 1., 2., 3.]) >>> distances[0, ::4] array([ 0., 1., 2.]) LLCATS: NINF MEAS """ if self._all_node_distances_map is None: self._create_all_node_distances_azimuths_maps() return self._all_node_distances_map @property def all_node_azimuths_map(self): """Get azimuths from every node to every other node. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> angles = grid.all_node_azimuths_map The shape of the array is ``number_of_nodes`` by ``number_of_nodes`` and azimuth from a node to itself is zero. >>> angles.shape == (grid.number_of_nodes, grid.number_of_nodes) True >>> angles.diagonal() array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) Angles are measured in radians and increase clockwise starting at north. >>> angles *= 180. / np.pi >>> angles[0, :4] array([ 0., 90., 90., 90.]) >>> angles[0, ::4] array([ 0., 0., 0.]) >>> angles[0, ::5] array([ 0., 45., 45.]) LLCATS: NINF MEAS """ if self._all_node_azimuths_map is None: self._create_all_node_distances_azimuths_maps() return self._all_node_azimuths_map def _create_all_node_distances_azimuths_maps(self): """Build distance-azimuth maps. This function creates and stores in the grid field two ``nnodes`` by ``nnodes`` arrays that map the distances and azimuths of all nodes in the grid to all nodes in the grid. This is useful if your module needs to make repeated lookups of distances between the same nodes, but does potentially use up a lot of memory so should be used with caution. The map is symmetrical, so it does not matter whether rows are "from" or "to". The arrays are called: - ``self.all_node_distances_map`` - ``self.all_node_azimuths_map`` Returns ------- tuple of ndarrays Tuple of (distances, azimuths) """ self._all_node_distances_map = numpy.empty((self.number_of_nodes, self.number_of_nodes)) self._all_node_azimuths_map = numpy.empty((self.number_of_nodes, self.number_of_nodes)) node_coords = numpy.empty((self.number_of_nodes, 2)) node_coords[:, 0] = self.node_x node_coords[:, 1] = self.node_y for i in range(self.number_of_nodes): (self._all_node_distances_map[i, :], self._all_node_azimuths_map[i, :]) = ( self.calc_distances_of_nodes_to_point( (node_coords[i, 0], node_coords[i, 1]), get_az='angles')) assert numpy.all(self._all_node_distances_map >= 0.) return self._all_node_distances_map, self._all_node_azimuths_map def _sort_links_by_midpoint(self): """Sort links in order first by midpoint x coordinate, then y. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg._sort_links_by_midpoint() """ pts = np.zeros((self.number_of_links, 2)) pts[:, 0] = (self.node_x[self.node_at_link_tail] + self.node_x[self.node_at_link_head]) / 2 pts[:, 1] = (self.node_y[self.node_at_link_tail] + self.node_y[self.node_at_link_head]) / 2 indices = argsort_points_by_x_then_y(pts) self.node_at_link_tail[:] = self.node_at_link_tail[indices] self.node_at_link_head[:] = self.node_at_link_head[indices] def move_origin(self, origin): """Changes the x, y values of all nodes. Initially a grid will have an origin of 0,0, and all x,y values will be relative to 0,0. This will add origin[0] to all x values and origin[1] to all y values. Note this is most likely useful when importing a DEM that has an absolute location, however it can be used generally. Parameters ---------- origin : list of two float values, can be negative. [x,y], where x is the value to add to all x values and y is the value to add to all y values Examples -------- >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((4, 3), 1.0) # rows, columns, spacing >>> rmg.node_x array([ 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.]) >>> rmg.node_y array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 3., 3., 3.]) >>> rmg.move_origin((5,1.5)) >>> rmg.node_x array([ 5., 6., 7., 5., 6., 7., 5., 6., 7., 5., 6., 7.]) >>> rmg.node_y array([ 1.5, 1.5, 1.5, 2.5, 2.5, 2.5, 3.5, 3.5, 3.5, 4.5, 4.5, 4.5]) LLCATS: GINF MEAS """ self._node_x += origin[0] self._node_y += origin[1] add_module_functions_to_class(ModelGrid, 'mappers.py', pattern='map_*') # add_module_functions_to_class(ModelGrid, 'gradients.py', # pattern='calculate_*') add_module_functions_to_class(ModelGrid, 'gradients.py', pattern='calc_*') add_module_functions_to_class(ModelGrid, 'divergence.py', pattern='calc_*') if __name__ == '__main__': import doctest doctest.testmod() Remove unused ModelGrid._active_links_at_node. #! /usr/env/python """ Python implementation of ModelGrid, a base class used to create and manage grids for 2D numerical models. Do NOT add new documentation here. Grid documentation is now built in a semi- automated fashion. To modify the text seen on the web, edit the files `docs/text_for_[gridfile].py.txt`. """ import numpy import numpy as np import warnings from time import time import six from six.moves import range from landlab.testing.decorators import track_this_method from landlab.utils import count_repeated_values from landlab.core.utils import argsort_points_by_x_then_y from landlab.utils.decorators import make_return_array_immutable, deprecated from landlab.field import ModelDataFields, ModelDataFieldsMixIn from landlab.field.scalar_data_fields import FieldError from . import grid_funcs as gfuncs from ..core.utils import as_id_array from ..core.utils import add_module_functions_to_class from .decorators import (override_array_setitem_and_reset, return_id_array, return_readonly_id_array) #: Indicates an index is, in some way, *bad*. BAD_INDEX_VALUE = -1 # DEJH thinks the user should be able to override this value if they want # Map names grid elements to the ModelGrid attribute that contains the count # of that element in the grid. _ARRAY_LENGTH_ATTRIBUTES = { 'node': 'number_of_nodes', 'patch': 'number_of_patches', 'link': 'number_of_links', 'corner': 'number_of_corners', 'face': 'number_of_faces', 'cell': 'number_of_cells', 'active_link': 'number_of_active_links', 'active_face': 'number_of_active_faces', 'core_node': 'number_of_core_nodes', 'core_cell': 'number_of_core_cells', } # Fields whose sizes can not change. _SIZED_FIELDS = {'node', 'link', 'patch', 'corner', 'face', 'cell', } # Define the boundary-type codes #: Indicates a node is *core*. CORE_NODE = 0 #: Indicates a boundary node is has a fixed values. FIXED_VALUE_BOUNDARY = 1 #: Indicates a boundary node is has a fixed gradient. FIXED_GRADIENT_BOUNDARY = 2 #: Indicates a boundary node is wrap-around. LOOPED_BOUNDARY = 3 #: Indicates a boundary node is closed CLOSED_BOUNDARY = 4 # Define the link types #: Indicates a link is *active*, and can carry flux ACTIVE_LINK = 0 #: Indicates a link has a fixed (gradient) value, & behaves as a boundary FIXED_LINK = 2 #: Indicates a link is *inactive*, and cannot carry flux INACTIVE_LINK = 4 BOUNDARY_STATUS_FLAGS_LIST = [ FIXED_VALUE_BOUNDARY, FIXED_GRADIENT_BOUNDARY, LOOPED_BOUNDARY, CLOSED_BOUNDARY, ] BOUNDARY_STATUS_FLAGS = set(BOUNDARY_STATUS_FLAGS_LIST) LINK_STATUS_FLAGS_LIST = [ ACTIVE_LINK, FIXED_LINK, INACTIVE_LINK, ] LINK_STATUS_FLAGS = set(LINK_STATUS_FLAGS_LIST) def _sort_points_into_quadrants(x, y, nodes): """Divide x, y points into quadrants. Divide points with locations given in the *x*, and *y* arrays into north, south, east, and west quadrants. Returns nodes contained in quadrants (west, east, north, south). Parameters ---------- x : array_like X-coordinates of points. y : array_like Y-coordinates of points. nodes : array_like Nodes associated with points. Returns ------- tuple of array_like Tuple of nodes in each coordinate. Nodes are grouped as (*east*, *north*, *west*, *south*). Examples -------- >>> import numpy as np >>> from landlab.grid.base import _sort_points_into_quadrants >>> x = np.array([0, 1, 0, -1]) >>> y = np.array([1, 0, -1, 0]) >>> nodes = np.array([1, 2, 3, 4]) >>> _sort_points_into_quadrants(x, y, nodes) (array([2]), array([1]), array([4]), array([3])) """ above_x_axis = y > 0 right_of_y_axis = x > 0 closer_to_y_axis = numpy.abs(y) >= numpy.abs(x) north_nodes = nodes[above_x_axis & closer_to_y_axis] south_nodes = nodes[(~ above_x_axis) & closer_to_y_axis] east_nodes = nodes[right_of_y_axis & (~ closer_to_y_axis)] west_nodes = nodes[(~ right_of_y_axis) & (~ closer_to_y_axis)] return (east_nodes, north_nodes, west_nodes, south_nodes) def _default_axis_names(n_dims): """Name of each axis. Parameters ---------- n_dims : int Number of spatial dimensions. Returns ------- tuple of str Name of each axis. Examples -------- >>> from landlab.grid.base import _default_axis_names >>> _default_axis_names(1) ('x',) >>> _default_axis_names(2) ('y', 'x') >>> _default_axis_names(3) ('z', 'y', 'x') """ _DEFAULT_NAMES = ('z', 'y', 'x') return _DEFAULT_NAMES[- n_dims:] def _default_axis_units(n_dims): """Unit names for each axis. Parameters ---------- n_dims : int Number of spatial dimensions. Returns ------- tuple of str Units of each axis. Examples -------- >>> from landlab.grid.base import _default_axis_units >>> _default_axis_units(1) ('-',) >>> _default_axis_units(2) ('-', '-') >>> _default_axis_units(3) ('-', '-', '-') """ return ('-', ) * n_dims def find_true_vector_from_link_vector_pair(L1, L2, b1x, b1y, b2x, b2y): r"""Separate a pair of links with vector values into x and y components. The concept here is that a pair of adjacent links attached to a node are projections of a 'true' but unknown vector. This function finds and returns the x and y components of this true vector. The trivial case is the situation in which the two links are orthogonal and aligned with the grid axes, in which case the vectors of these two links *are* the x and y components. Parameters ---------- L1, L2 : float Values (magnitudes) associated with the two links b1x, b1y, b2x, b2y : float Unit vectors of the two links Returns ------- ax, ay : float x and y components of the 'true' vector Notes ----- The function does an inverse vector projection. Suppose we have a given 'true' vector :math:`a`, and we want to project it onto two other lines with unit vectors (b1x,b1y) and (b2x,b2y). In the context of Landlab, the 'true' vector is some unknown vector quantity, which might for example represent the local water flow velocity. The lines represent two adjacent links in the grid. Let :math:`\mathbf{a}` be the true vector, :math:`\mathbf{B}` be a different vector with unit vector :math:`\mathbf{b}`, and :math:`L` be the scalar projection of *a* onto *B*. Then, ..math:: L = \mathbf{a} \dot \mathbf{b} = a_x b_x + a_y b_y, where :math:`(a_x,a_y)` are the components of **a** and :math:`(b_x,b_y)` are the components of the unit vector **b**. In this case, we know *b* (the link unit vector), and we want to know the *x* and *y* components of **a**. The problem is that we have one equation and two unknowns (:math:`a_x` and :math:`a_y`). But we can solve this if we have *two* vectors, both of which are projections of **a**. Using the subscripts 1 and 2 to denote the two vectors, we can obtain equations for both :math:`a_x` and :math:`a_y`: ..math:: a_x = L_1 / b_{1x} - a_y b_{1y} / b_{1x} a_y = L_2 / b_{2y} - a_x b_{2x} / b_{2y} Substituting the second into the first, ..math:: a_x = [L_1/b_{1x}-L_2 b_{1y}/(b_{1x} b_{2y})] / [1-b_{1y} b_{2x}/(b_{1x} b_{2y})] Hence, we find the original vector :math:`(a_x,a_y)` from two links with unit vectors :math:`(b_{1x},b_{1y})` and :math:`(b_{2x},b_{2y})` and associated values :math:`L_1` and :math:`L_2`. Note that the above equations require that :math:`b_{1x}>0` and :math:`b_{2y}>0`. If this isn't the case, we invert the order of the two links, which requires :math:`b_{2x}>0` and :math:`b_{1y}>0`. If none of these conditions is met, then we have a degenerate case. Examples -------- The following example represents the active links in a 7-node hexagonal grid, with just one core node. The 'true' vector has a magnitude of 5 units and an orientation of 30 degrees, pointing up and to the right (i.e., the postive-x and postive-y quadrant), so that its vector components are 4 (x) and 3 (y) (in other words, it is a 3-4-5 triangle). The values assigned to L below are the projection of that true vector onto the six link vectors. The algorithm should recover the correct vector component values of 4 and 3. The FOR loop examines each pair of links in turn. >>> import numpy as np >>> from landlab.grid.base import find_true_vector_from_link_vector_pair >>> bx = np.array([0.5, -0.5, -1., -0.5, 1., 0.5]) >>> by = np.array([0.866, 0.866, 0., -0.866, 0., -0.866]) >>> L = np.array([4.6, 0.6, -4., -4.6, 4., -0.6]) >>> for i in range(5): ... ax, ay = find_true_vector_from_link_vector_pair( ... L[i], L[i+1], bx[i], by[i], bx[i+1], by[i+1]) ... round(ax,1), round(ay,1) (4.0, 3.0) (4.0, 3.0) (4.0, 3.0) (4.0, 3.0) (4.0, 3.0) """ assert ((b1x != 0 and b2y != 0) or (b2x != 0 and b1y != 0)), \ 'Improper unit vectors' if b1x != 0. and b2y != 0.: ax = (L1 / b1x - L2 * (b1y / (b1x * b2y))) / \ (1. - (b1y * b2x) / (b1x * b2y)) ay = L2 / b2y - ax * (b2x / b2y) elif b2x != 0. and b1y != 0.: ax = (L2 / b2x - L1 * (b2y / (b2x * b1y))) / \ (1. - (b2y * b1x) / (b2x * b1y)) ay = L1 / b1y - ax * (b1x / b1y) return ax, ay class ModelGrid(ModelDataFieldsMixIn): """Base class for 2D structured or unstructured grids for numerical models. The idea is to have at least two inherited classes, RasterModelGrid and DelaunayModelGrid, that can create and manage grids. To this might be added a GenericModelGrid, which would be an unstructured polygonal grid that doesn't necessarily obey or understand the Delaunay triangulation, but rather simply accepts an input grid from the user. Also a :class:`~.HexModelGrid` for hexagonal. Attributes ---------- at_node : dict-like Values at nodes. at_cell : dict-like Values at cells. at_link : dict-like Values at links. at_face : dict-like Values at faces. at_grid: dict-like Global values Other Parameters ---------------- axis_name : tuple, optional Name of axes axis_units : tuple, optional Units of coordinates """ # Debugging flags (if True, activates some output statements) _DEBUG_VERBOSE = False _DEBUG_TRACK_METHODS = False at_node = {} # : Values defined at nodes at_link = {} # : Values defined at links at_patch = {} # : Values defined at patches at_corner = {} # : Values defined at corners at_face = {} # : Values defined at faces at_cell = {} # : Values defined at cells # : Nodes on the other end of links pointing into a node. _node_inlink_matrix = numpy.array([], dtype=numpy.int32) # : Nodes on the other end of links pointing out of a node. _node_outlink_matrix = numpy.array([], dtype=numpy.int32) def __init__(self, **kwds): super(ModelGrid, self).__init__() self.axis_name = kwds.get('axis_name', _default_axis_names(self.ndim)) self.axis_units = kwds.get( 'axis_units', _default_axis_units(self.ndim)) self._link_length = None self._all_node_distances_map = None self._all_node_azimuths_map = None self._node_unit_vector_sum_x = None self._node_unit_vector_sum_y = None self._link_unit_vec_x = None self._link_unit_vec_y = None self.bc_set_code = 0 # Sort links according to the x and y coordinates of their midpoints. # Assumes 1) node_at_link_tail and node_at_link_head have been # created, and 2) so have node_x and node_y. # self._sort_links_by_midpoint() for loc in _SIZED_FIELDS: size = self.number_of_elements(loc) ModelDataFields.new_field_location(self, loc, size=size) ModelDataFields.new_field_location(self, 'grid', size=1) # for loc in _UNSIZED_FIELDS: # ModelDataFields.new_field_location(self, loc, size=None) ModelDataFields.set_default_group(self, 'node') def _create_link_face_coords(self): """Create x, y coordinates for link-face intersections. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4), 1.) >>> mg.x_of_link array([ 0.5, 1.5, 2.5, 0. , 1. , 2. , 3. , 0.5, 1.5, 2.5, 0. , 1. , 2. , 3. , 0.5, 1.5, 2.5]) >>> mg.y_of_link array([ 0. , 0. , 0. , 0.5, 0.5, 0.5, 0.5, 1. , 1. , 1. , 1.5, 1.5, 1.5, 1.5, 2. , 2. , 2. ]) >>> np.all(mg.x_of_link[mg.link_at_face] == mg.x_of_face) True >>> np.all(mg.y_of_link[mg.link_at_face] == mg.y_of_face) True """ self._link_x = (self.x_of_node[self.node_at_link_head] + self.x_of_node[self.node_at_link_tail])/2. self._link_y = (self.y_of_node[self.node_at_link_head] + self.y_of_node[self.node_at_link_tail])/2. def _create_neighbor_list(self, **kwds): """Create list of neighbor node IDs. Creates a list of IDs of neighbor nodes for each node, as a 2D array. Only record neighbor nodes that are on the other end of an *active* link. Nodes attached to *inactive* links or neighbor nodes that would be outside of the grid are given an ID of :const:`~landlab.grid.base.BAD_INDEX_VALUE`. Neighbors are ordered as [*right*, *top*, *left*, *bottom*]. """ self._active_neighbor_nodes = self.neighbors_at_node.copy() self._active_neighbor_nodes[ self.active_link_dirs_at_node == 0] = BAD_INDEX_VALUE self.neighbor_list_created = True return self._active_neighbor_nodes @classmethod def from_file(cls, file_like): params = load_params(file_like) return cls.from_dict(params) @classmethod def from_dict(cls, params): raise NotImplementedError('from_dict') def _initialize(self): raise NotImplementedError('_initialize') @property def ndim(self): """Number of spatial dimensions of the grid. LLCATS: GINF """ return 2 def _setup_nodes(self): """Set up the node id array.""" self._nodes = np.arange(self.number_of_nodes, dtype=int) return self._nodes @property @make_return_array_immutable def nodes(self): """Get node ids for the grid. Examples -------- >>> from landlab import RadialModelGrid >>> mg = RadialModelGrid(num_shells=1) >>> mg.nodes array([0, 1, 2, 3, 4, 5, 6]) LLCATS: NINF """ try: return self._nodes except AttributeError: return self._setup_nodes() @property @override_array_setitem_and_reset('_update_links_nodes_cells_to_new_BCs') def status_at_node(self): """Get array of the boundary status for each node. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> from landlab import FIXED_GRADIENT_BOUNDARY, FIXED_LINK >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node.reshape((4, 5)) array([[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]], dtype=int8) >>> np.any(mg.status_at_link == FIXED_LINK) False >>> mg.status_at_node[mg.nodes_at_left_edge] = FIXED_GRADIENT_BOUNDARY >>> mg.status_at_node.reshape((4, 5)) array([[2, 1, 1, 1, 1], [2, 0, 0, 0, 1], [2, 0, 0, 0, 1], [2, 1, 1, 1, 1]], dtype=int8) >>> np.any(mg.status_at_link == FIXED_LINK) # links auto-update True LLCATS: NINF BC """ return self._node_status @status_at_node.setter def status_at_node(self, new_status): """Set the array of node boundary statuses.""" self._node_status[:] = new_status[:] self._update_links_nodes_cells_to_new_BCs() @property @make_return_array_immutable def neighbors_at_node(self): """Get neighboring nodes. Examples -------- >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> grid = RasterModelGrid((4, 3)) >>> neighbors = grid.neighbors_at_node.copy() >>> neighbors[neighbors == BAD_INDEX_VALUE] = -1 >>> neighbors # doctest: +NORMALIZE_WHITESPACE array([[ 1, 3, -1, -1], [ 2, 4, 0, -1], [-1, 5, 1, -1], [ 4, 6, -1, 0], [ 5, 7, 3, 1], [-1, 8, 4, 2], [ 7, 9, -1, 3], [ 8, 10, 6, 4], [-1, 11, 7, 5], [10, -1, -1, 6], [11, -1, 9, 7], [-1, -1, 10, 8]]) LLCATS: NINF CONN """ return self._neighbors_at_node @property @return_readonly_id_array def active_neighbors_at_node(self): """Get list of neighbor node IDs. Return lists of neighbor nodes, where the neighbor is connected by an active link. For each node, the list gives neighbor ids as [right, top, left, bottom]. Nodes at the end of inactive links or nodes in missing positions get BAD_INDEX_VALUE. Examples -------- >>> from landlab.grid.base import BAD_INDEX_VALUE as X >>> from landlab import RasterModelGrid, HexModelGrid, CLOSED_BOUNDARY >>> rmg = RasterModelGrid((4, 5)) >>> np.array_equal(rmg.active_neighbors_at_node[[-1, 6, 2]], ... [[X, X, X, X], [ 7, 11, 5, 1], [X, 7, X, X]]) True >>> rmg.active_neighbors_at_node[7] array([ 8, 12, 6, 2]) >>> rmg.active_neighbors_at_node[2] array([-1, 7, -1, -1]) >>> hmg = HexModelGrid(3, 2) >>> hmg.status_at_node[0] = CLOSED_BOUNDARY >>> hmg.active_neighbors_at_node array([[-1, -1, -1, -1, -1, -1], [-1, 3, -1, -1, -1, -1], [ 3, -1, -1, -1, -1, -1], [ 4, 6, 5, 2, -1, 1], [-1, 3, -1, -1, -1, -1], [-1, -1, 3, -1, -1, -1], [-1, 3, -1, -1, -1, -1]]) LLCATS: NINF CONN BC """ try: return self._active_neighbor_nodes except AttributeError: self._active_neighbor_nodes = self._create_neighbor_list() return self._active_neighbor_nodes @property @make_return_array_immutable def links_at_node(self): """Get links of nodes. Returns ------- (NODES, LINKS) ndarray of int Link for the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. Order is anticlockwise from east. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 3)) >>> grid.links_at_node # doctest: +NORMALIZE_WHITESPACE array([[ 0, 2, -1, -1], [ 1, 3, 0, -1], [-1, 4, 1, -1], [ 5, 7, -1, 2], [ 6, 8, 5, 3], [-1, 9, 6, 4], [10, 12, -1, 7], [11, 13, 10, 8], [-1, 14, 11, 9], [15, -1, -1, 12], [16, -1, 15, 13], [-1, -1, 16, 14]]) >>> grid.links_at_node[4] array([6, 8, 5, 3]) >>> grid.links_at_node[(4, 7), :] array([[ 6, 8, 5, 3], [11, 13, 10, 8]]) LLCATS: NINF LINF CONN """ return self._links_at_node @property @make_return_array_immutable def link_dirs_at_node(self): """Link directions at each node: 1=incoming, -1=outgoing, 0=none. Returns ------- (NODES, LINKS) ndarray of int Link directions relative to the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. A zero indicates no link at this position. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 3)) >>> grid.link_dirs_at_node # doctest: +NORMALIZE_WHITESPACE array([[-1, -1, 0, 0], [-1, -1, 1, 0], [ 0, -1, 1, 0], [-1, -1, 0, 1], [-1, -1, 1, 1], [ 0, -1, 1, 1], [-1, -1, 0, 1], [-1, -1, 1, 1], [ 0, -1, 1, 1], [-1, 0, 0, 1], [-1, 0, 1, 1], [ 0, 0, 1, 1]], dtype=int8) >>> grid.link_dirs_at_node[4] array([-1, -1, 1, 1], dtype=int8) >>> grid.link_dirs_at_node[(4, 7), :] array([[-1, -1, 1, 1], [-1, -1, 1, 1]], dtype=int8) LLCATS: NINF LINF CONN """ return self._link_dirs_at_node @property @make_return_array_immutable def active_link_dirs_at_node(self): """ Link flux directions at each node: 1=incoming flux, -1=outgoing flux, 0=no flux. Note that inactive links receive zero, but active and fixed links are both reported normally. Returns ------- (NODES, LINKS) ndarray of int Link directions relative to the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. A zero indicates no link at this position. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> grid = RasterModelGrid((4, 3)) >>> grid.status_at_node[grid.nodes_at_left_edge] = CLOSED_BOUNDARY >>> grid.active_link_dirs_at_node # doctest: +NORMALIZE_WHITESPACE array([[ 0, 0, 0, 0], [ 0, -1, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [-1, -1, 0, 1], [ 0, 0, 1, 0], [ 0, 0, 0, 0], [-1, -1, 0, 1], [ 0, 0, 1, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 1], [ 0, 0, 0, 0]], dtype=int8) LLCATS: NINF LINF CONN """ return self._active_link_dirs_at_node @property def node_at_cell(self): """Node ID associated with grid cells. Examples -------- >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> grid = RasterModelGrid((4, 5)) >>> grid.node_at_cell # doctest: +NORMALIZE_WHITESPACE array([ 6, 7, 8, 11, 12, 13]) LLCATS: NINF CINF CONN """ return self._node_at_cell @property def cell_at_node(self): """Node ID associated with grid cells. Examples -------- >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> grid = RasterModelGrid((4, 5)) >>> ids = grid.cell_at_node >>> ids[ids == BAD_INDEX_VALUE] = -1 >>> ids # doctest: +NORMALIZE_WHITESPACE array([-1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, 3, 4, 5, -1, -1, -1, -1, -1, -1]) LLCATS: CINF NINF CONN """ return self._cell_at_node @property @return_readonly_id_array def core_nodes(self): """Get array of core nodes. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.core_nodes array([ 6, 7, 8, 11, 12, 13]) LLCATS: NINF BC """ try: return self._core_nodes except AttributeError: (core_node_ids, ) = numpy.where(self._node_status == CORE_NODE) return core_node_ids @property @return_readonly_id_array def boundary_nodes(self): """Get array of boundary nodes. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.boundary_nodes array([ 0, 1, 2, 3, 4, 5, 9, 10, 14, 15, 16, 17, 18, 19]) LLCATS: NINF BC """ try: return self._boundary_nodes except: (boundary_node_ids, ) = numpy.where(self._node_status != CORE_NODE) return boundary_node_ids @property @return_readonly_id_array def open_boundary_nodes(self): """Get array of open boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge, ... mg.nodes_at_bottom_edge): ... mg.status_at_node[edge] = CLOSED_BOUNDARY >>> mg.open_boundary_nodes array([16, 17, 18]) LLCATS: NINF BC """ (open_boundary_node_ids, ) = numpy.where( (self._node_status != CLOSED_BOUNDARY) & (self._node_status != CORE_NODE)) return open_boundary_node_ids @property @return_readonly_id_array def closed_boundary_nodes(self): """Get array of closed boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.closed_boundary_nodes array([15, 16, 17, 18, 19]) LLCATS: NINF BC """ (closed_boundary_node_ids, ) = numpy.where( self._node_status == CLOSED_BOUNDARY) return closed_boundary_node_ids @property @return_readonly_id_array def fixed_gradient_boundary_nodes(self): """Get array of fixed gradient boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[mg.nodes_at_top_edge] = FIXED_GRADIENT_BOUNDARY >>> mg.fixed_gradient_boundary_nodes array([15, 16, 17, 18, 19]) LLCATS: NINF BC """ (fixed_gradient_boundary_node_ids, ) = numpy.where( self._node_status == FIXED_GRADIENT_BOUNDARY) return fixed_gradient_boundary_node_ids @property @return_readonly_id_array def fixed_gradient_boundary_node_fixed_link(self): """ An array of the fixed_links connected to fixed gradient boundary nodes. Note that on a raster, some nodes (notably the corners) can be FIXED_GRADIENT_BOUNDARY, but not have a true FIXED_LINK neighboring link. In such cases, the link returned will be a closed link joining the corner node to a neighboring FIXED_GRADIENT_BOUNDARY node (see example). An AssertionError will be raised if for some reason a FIXED_GRADIENT_BOUNDARY node exists which has neither a FIXED_GRADIENT_BOUNDARY neighbor, or a FIXED_LINK. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab import FIXED_GRADIENT_BOUNDARY >>> grid = RasterModelGrid((3, 4)) >>> leftedge = grid.nodes_at_left_edge >>> grid.status_at_node[leftedge] = FIXED_GRADIENT_BOUNDARY >>> grid.fixed_gradient_boundary_nodes array([0, 4, 8]) >>> grid.fixed_gradient_boundary_node_fixed_link array([ 3, 7, 10]) """ try: return self._fixed_gradient_boundary_node_links except AttributeError: self._create_fixed_gradient_boundary_node_links() return self._fixed_gradient_boundary_node_links @property @return_readonly_id_array def fixed_gradient_boundary_node_anchor_node(self): """ Returns the node at the other end of the fixed link for a fixed gradient boundary node. Degenerate FIXED_GRADIENT_BOUNDARY nodes (e.g., corners) are handled as in :func:`fixed_gradient_boundary_node_fixed_link`, by pointing to a neighboring FIXED_GRADIENT_BOUNDARY node. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab import FIXED_GRADIENT_BOUNDARY >>> grid = RasterModelGrid((3, 4)) >>> leftedge = grid.nodes_at_left_edge >>> grid.status_at_node[leftedge] = FIXED_GRADIENT_BOUNDARY >>> grid.fixed_gradient_boundary_nodes array([0, 4, 8]) >>> grid.fixed_gradient_boundary_node_fixed_link array([ 3, 7, 10]) >>> grid.fixed_gradient_boundary_node_anchor_node array([4, 5, 4]) """ try: return self._fixed_gradient_boundary_node_anchor_node except AttributeError: self._create_fixed_gradient_boundary_node_anchor_node() return self._fixed_gradient_boundary_node_anchor_node def _create_fixed_gradient_boundary_node_links(self): """ Builds a data structure to hold the fixed_links which control the values of any FIXED_GRADIENT_BOUNDARY nodes in the grid. An AssertionError will be raised if for some reason a FIXED_GRADIENT_BOUNDARY node exists which has neither a FIXED_GRADIENT_BOUNDARY neighbor, or a FIXED_LINK. """ self._fixed_grad_links_created = True self._fixed_gradient_boundary_node_links = np.empty_like( self.fixed_gradient_boundary_nodes, dtype=int) fix_nodes = self.fixed_gradient_boundary_nodes neighbor_links = self.links_at_node[fix_nodes] # -1s boundary_exists = self.link_dirs_at_node[fix_nodes] # next line retains -1 indexes link_stat_badind = self.status_at_link[neighbor_links] == FIXED_LINK true_connection = np.logical_and(link_stat_badind, boundary_exists) true_fix_nodes = true_connection.sum(axis=1).astype(bool) self._fixed_gradient_boundary_node_links[true_fix_nodes] = ( neighbor_links[true_connection]) # resolve any corner nodes neighbor_nodes = self.neighbors_at_node[fix_nodes] # BAD_INDEX_VALUEs neighbor_nodes[neighbor_nodes == BAD_INDEX_VALUE] = -1 fixed_grad_neighbor = np.logical_and((self.status_at_node[ neighbor_nodes] == FIXED_GRADIENT_BOUNDARY), boundary_exists) # ^True when FIXED_GRADIENT_BOUNDARY for real # winnow it down to only one possibility for fixed_grad neighbor: which_neighbor = np.argmax(fixed_grad_neighbor, axis=1) indexing_range = np.arange(fixed_grad_neighbor.shape[0]) a_link_to_fixed_grad = neighbor_links[indexing_range, which_neighbor] corners = np.logical_not(true_fix_nodes) assert np.all( fixed_grad_neighbor[indexing_range, which_neighbor][corners]) self._fixed_gradient_boundary_node_links[ corners] = a_link_to_fixed_grad[corners] def _create_fixed_gradient_boundary_node_anchor_node(self): """ Builds a data structure to hold the nodes which anchor the values of any FIXED_GRADIENT_BOUNDARY nodes in the grid, i.e., those at the other ends of the FIXED_LINKS. An AssertionError will be raised if for some reason a FIXED_GRADIENT_BOUNDARY node exists which has neither a FIXED_GRADIENT_BOUNDARY neighbor, or a FIXED_LINK. """ self._fixed_grad_links_created = True fix_grad_nodes = self.fixed_gradient_boundary_nodes self._fixed_gradient_boundary_node_anchor_node = np.empty_like( fix_grad_nodes) heads_and_tails = np.empty((fix_grad_nodes.size, 2)) which_one = np.empty_like(heads_and_tails, dtype=bool) heads_and_tails[:, 0] = self.node_at_link_head[ self.fixed_gradient_boundary_node_fixed_link] heads_and_tails[:, 1] = self.node_at_link_tail[ self.fixed_gradient_boundary_node_fixed_link] which_one[:, 0] = heads_and_tails[:, 0] == fix_grad_nodes which_one[:, 1] = heads_and_tails[:, 1] == fix_grad_nodes assert np.all(which_one.sum(axis=1) == 1) self._fixed_gradient_boundary_node_anchor_node = heads_and_tails[ np.logical_not(which_one)] @property @return_readonly_id_array def fixed_value_boundary_nodes(self): """Get array of fixed value boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge, ... mg.nodes_at_bottom_edge): ... mg.status_at_node[edge] = CLOSED_BOUNDARY >>> mg.fixed_value_boundary_nodes array([16, 17, 18]) LLCATS: NINF BC """ (fixed_value_boundary_node_ids, ) = numpy.where( self._node_status == FIXED_VALUE_BOUNDARY) return fixed_value_boundary_node_ids @property @return_readonly_id_array def active_faces(self): """Get array of active faces. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.active_faces array([0, 1, 2, 3, 4, 5, 6]) >>> from landlab import CLOSED_BOUNDARY >>> grid.status_at_node[6] = CLOSED_BOUNDARY >>> grid.active_faces array([0, 2, 5]) LLCATS: FINF BC """ try: return self._active_faces except AttributeError: self._create_active_faces() return self._active_faces @property @return_readonly_id_array def active_links(self): """Get array of active links. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.active_links array([ 4, 5, 7, 8, 9, 11, 12]) LLCATS: LINF BC """ try: return self._active_links except AttributeError: self._reset_link_status_list() return self._active_links @property @return_readonly_id_array def fixed_links(self): """Get array of fixed links. Examples -------- >>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY >>> grid = RasterModelGrid((3, 4)) >>> grid.status_at_node # doctest: +NORMALIZE_WHITESPACE array([1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8) >>> grid.fixed_links.size 0 >>> grid.status_at_node[:4] = FIXED_GRADIENT_BOUNDARY >>> grid.status_at_node # doctest: +NORMALIZE_WHITESPACE array([2, 2, 2, 2, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8) >>> grid.fixed_links array([4, 5]) LLCATS: LINF BC """ try: return self._fixed_links except AttributeError: self._reset_link_status_list() return self._fixed_links @property @return_readonly_id_array def node_at_core_cell(self): """Get array of nodes associated with core cells. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[8] = CLOSED_BOUNDARY >>> mg.node_at_core_cell array([ 6, 7, 11, 12, 13]) LLCATS: NINF CINF BC CONN """ (core_cell_ids, ) = numpy.where(self._node_status == CORE_NODE) return core_cell_ids @property def core_cells(self): """Get array of core cells. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[8] = CLOSED_BOUNDARY >>> mg.core_cells array([0, 1, 3, 4, 5]) LLCATS: CINF BC """ return self._core_cells @property def node_at_link_head(self): """Get array of the node at each link head (*to-node*). Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.node_at_link_head[:5] array([1, 2, 3, 4, 5]) LLCATS: NINF LINF CONN """ return self._node_at_link_head @property def node_at_link_tail(self): """Get array of the node at each link tail (*from-node*). Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.node_at_link_tail[:5] array([0, 1, 2, 3, 0]) LLCATS: NINF LINF CONN """ return self._node_at_link_tail @property def face_at_link(self): """Get array of faces associated with links. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.face_at_link[5:7] array([0, 1]) >>> np.all(mg.face_at_link[:5]==BAD_INDEX_VALUE) True LLCATS: FINF LINF CONN """ try: return self._face_at_link except AttributeError: return self._create_face_at_link() @property def link_at_face(self): """Get array of links associated with faces. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.link_at_face[0:3] array([5, 6, 7]) LLCATS: LINF FINF CONN """ try: return self._link_at_face except AttributeError: return self._create_link_at_face() @property def number_of_nodes(self): """Total number of nodes. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_nodes 20 LLCATS: NINF """ return len(self._cell_at_node) @property def number_of_corners(self): """Total number of corners. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_corners 12 LLCATS: CNINF """ return self.number_of_patches @property def number_of_cells(self): """Total number of cells. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_cells 6 LLCATS: CINF """ return len(self._node_at_cell) @property def number_of_links(self): """Total number of links. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.number_of_links 17 LLCATS: LINF """ return self._status_at_link.size @property def number_of_faces(self): """Total number of faces. Returns ------- int Total number of faces in the grid. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.number_of_faces 7 LLCATS: FINF """ return len(self.link_at_face) @property def number_of_active_faces(self): """Total number of active faces. Returns ------- int Total number of active faces in the grid. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> grid.number_of_active_faces 7 The number of active faces is updated when a node status changes. >>> from landlab import CLOSED_BOUNDARY >>> grid.status_at_node[6] = CLOSED_BOUNDARY >>> grid.number_of_active_faces 3 LLCATS: FINF BC """ return self.active_faces.size @property def number_of_core_nodes(self): """Number of core nodes. The number of core nodes on the grid (i.e., excluding all boundary nodes). Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_core_nodes 6 >>> grid.status_at_node[7] = CLOSED_BOUNDARY >>> grid.number_of_core_nodes 5 LLCATS: NINF BC """ return self._core_nodes.size @property def number_of_core_cells(self): """Number of core cells. A core cell excludes all boundary cells. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> grid = RasterModelGrid((4, 5)) >>> grid.number_of_core_cells 6 >>> grid.status_at_node[7] = CLOSED_BOUNDARY >>> grid.number_of_core_cells 5 LLCATS: CINF BC """ return self._core_cells.size @property def number_of_active_links(self): """Number of active links. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.number_of_active_links 17 >>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge, ... mg.nodes_at_bottom_edge): ... mg.status_at_node[edge] = CLOSED_BOUNDARY >>> mg.number_of_active_links 10 LLCATS: LINF BC """ return self.active_links.size @property def number_of_fixed_links(self): """Number of fixed links. Examples -------- >>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.number_of_fixed_links 0 >>> mg.status_at_node[mg.nodes_at_top_edge] = FIXED_GRADIENT_BOUNDARY >>> mg.number_of_fixed_links 3 LLCATS: LINF BC """ try: return self._fixed_links.size except AttributeError: self._reset_link_status_list() return self._fixed_links.size def number_of_elements(self, name): """Number of instances of an element. Get the number of instances of a grid element in a grid. Parameters ---------- name : {'node', 'cell', 'link', 'face', 'core_node', 'core_cell', 'active_link', 'active_face'} Name of the grid element. Returns ------- int Number of elements in the grid. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.number_of_elements('node') 20 >>> mg.number_of_elements('core_cell') 6 >>> mg.number_of_elements('link') 31 >>> mg.number_of_elements('active_link') 17 >>> mg.status_at_node[8] = CLOSED_BOUNDARY >>> mg.number_of_elements('link') 31 >>> mg.number_of_elements('active_link') 13 LLCATS: GINF """ try: return getattr(self, _ARRAY_LENGTH_ATTRIBUTES[name]) except KeyError: raise TypeError( '{name}: element name not understood'.format(name=name)) @property @make_return_array_immutable def node_x(self): """Get array of the x-coordinates of nodes. See also -------- x_of_node Exquivalent method. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.node_x.reshape((4, 5)) array([[ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.]]) LLCATS: NINF MEAS """ return self._node_x @property @make_return_array_immutable def node_y(self): """Get array of the y-coordinates of nodes. See also -------- y_of_node Exquivalent method. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.node_y.reshape((4, 5)) array([[ 0., 0., 0., 0., 0.], [ 2., 2., 2., 2., 2.], [ 4., 4., 4., 4., 4.], [ 6., 6., 6., 6., 6.]]) LLCATS: NINF MEAS """ return self._node_y @property @make_return_array_immutable def x_of_node(self): """Get array of the x-coordinates of nodes. See also -------- node_x Exquivalent method. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.x_of_node.reshape((4, 5)) array([[ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.], [ 0., 3., 6., 9., 12.]]) LLCATS: NINF MEAS """ return self._node_x @property @make_return_array_immutable def y_of_node(self): """Get array of the y-coordinates of nodes. See also -------- node_y Exquivalent method. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.y_of_node.reshape((4, 5)) array([[ 0., 0., 0., 0., 0.], [ 2., 2., 2., 2., 2.], [ 4., 4., 4., 4., 4.], [ 6., 6., 6., 6., 6.]]) LLCATS: NINF MEAS """ return self._node_y @property @make_return_array_immutable def x_of_cell(self): """Get array of the x-coordinates of nodes at cells. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.x_of_cell.reshape((2, 3)) array([[ 3., 6., 9.], [ 3., 6., 9.]]) LLCATS: CINF MEAS """ return self._node_x[self.node_at_cell] @property @make_return_array_immutable def y_of_cell(self): """Get array of the y-coordinates of nodes at cells. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.y_of_cell.reshape((2, 3)) array([[ 2., 2., 2.], [ 4., 4., 4.]]) LLCATS: CINF MEAS """ return self._node_y[self.node_at_cell] @property @make_return_array_immutable def x_of_link(self): """Get array of the x-coordinates of link midpoints. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.x_of_link # doctest: +NORMALIZE_WHITESPACE array([ 1.5, 4.5, 7.5, 10.5, 0. , 3. , 6. , 9. , 12. , 1.5, 4.5, 7.5, 10.5, 0. , 3. , 6. , 9. , 12. , 1.5, 4.5, 7.5, 10.5, 0. , 3. , 6. , 9. , 12. , 1.5, 4.5, 7.5, 10.5]) LLCATS: LINF MEAS """ try: return self._link_x except AttributeError: self._create_link_face_coords() return self._link_x @property @make_return_array_immutable def y_of_link(self): """Get array of the y-coordinates of link midpoints. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.y_of_link # doctest: +NORMALIZE_WHITESPACE array([ 0., 0., 0., 0., 1., 1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3., 3., 4., 4., 4., 4., 5., 5., 5., 5., 5., 6., 6., 6., 6.]) LLCATS: LINF MEAS """ try: return self._link_y except AttributeError: self._create_link_face_coords() return self._link_y @property @make_return_array_immutable def x_of_face(self): """Get array of the x-coordinates of face midpoints. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.x_of_face # doctest: +NORMALIZE_WHITESPACE array([ 3. , 6. , 9. , 1.5, 4.5, 7.5, 10.5, 3. , 6. , 9. , 1.5, 4.5, 7.5, 10.5, 3. , 6. , 9. ]) LLCATS: FINF MEAS """ try: return self._link_x[self.link_at_face] except AttributeError: self._create_link_face_coords() return self._link_x[self.link_at_face] @property @make_return_array_immutable def y_of_face(self): """Get array of the y-coordinates of face midpoints. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.y_of_face # doctest: +NORMALIZE_WHITESPACE array([ 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 4., 4., 4., 4., 5., 5., 5.]) LLCATS: FINF MEAS """ try: return self._link_y[self.link_at_face] except AttributeError: self._create_link_face_coords() return self._link_y[self.link_at_face] @make_return_array_immutable def node_axis_coordinates(self, axis=0): """Get the coordinates of nodes along a particular axis. Return node coordinates from a given *axis* (defaulting to 0). Axis numbering is the same as that for numpy arrays. That is, the zeroth axis is along the rows, and the first along the columns. Parameters ---------- axis : int, optional Coordinate axis. Returns ------- ndarray Coordinates of nodes for a given axis. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.node_axis_coordinates(0) # doctest: +NORMALIZE_WHITESPACE array([ 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 3., 3., 3., 3., 3.]) >>> grid.node_axis_coordinates(1) # doctest: +NORMALIZE_WHITESPACE array([ 0., 1., 2., 3., 4., 0., 1., 2., 3., 4., 0., 1., 2., 3., 4., 0., 1., 2., 3., 4.]) LLCATS: GINF NINF MEAS """ AXES = ('node_y', 'node_x') try: return getattr(self, AXES[axis]) except IndexError: raise ValueError("'axis' entry is out of bounds") @property def axis_units(self): """Get units for each axis. Returns ------- tuple of str The units (as a string) for each of a grid's coordinates. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((4, 5), (2., 3.)) >>> mg.axis_units ('-', '-') >>> mg.axis_units = ('km', 'km') >>> mg.axis_units ('km', 'km') LLCATS: GINF """ return self._axis_units @axis_units.setter def axis_units(self, new_units): """Set the units for each coordinate axis.""" if len(new_units) != self.ndim: raise ValueError('length of units does not match grid dimension') self._axis_units = tuple(new_units) @property def axis_name(self): """Get the name of each coordinate axis. Returns ------- tuple of str The names of each axis. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.axis_name ('y', 'x') >>> grid.axis_name = ('lon', 'lat') >>> grid.axis_name ('lon', 'lat') LLCATS: GINF """ return self._axis_name @axis_name.setter def axis_name(self, new_names): """Set the names of a grid's coordinate axes. Raises ------ ValueError If the number of dimension do not match. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.axis_name = ('lon', 'lat') >>> grid.axis_name ('lon', 'lat') """ if len(new_names) != self.ndim: raise ValueError('length of names does not match grid dimension') self._axis_name = tuple(new_names) @property @make_return_array_immutable def status_at_link(self): """Get array of the status of all links. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab import CLOSED_BOUNDARY, FIXED_GRADIENT_BOUNDARY >>> mg = RasterModelGrid((4, 5), 1.) >>> mg.status_at_node[mg.nodes_at_left_edge] = CLOSED_BOUNDARY >>> mg.status_at_node[mg.nodes_at_right_edge] = FIXED_GRADIENT_BOUNDARY >>> mg.status_at_link # doctest: +NORMALIZE_WHITESPACE array([4, 4, 4, 4, 4, 0, 0, 0, 4, 4, 0, 0, 2, 4, 0, 0, 0, 4, 4, 0, 0, 2, 4, 0, 0, 0, 4, 4, 4, 4, 4]) LLCATS: BC LINF """ return self._status_at_link @property @return_readonly_id_array def link_at_face(self): """Get links associated with faces. Returns an array of the link IDs for the links that intersect faces. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4)) >>> mg.link_at_face array([ 4, 5, 7, 8, 9, 11, 12]) LLCATS: LINF FINF MEAS """ try: return self._link_at_face except AttributeError: return self._create_link_at_face() def _create_number_of_links_at_node(self): """Find and record how many links are attached to each node. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4)) >>> mg.number_of_links_at_node array([2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2]) """ self._number_of_links_at_node = np.zeros(self.number_of_nodes, dtype=np.int) for ln in range(self.number_of_links): self._number_of_links_at_node[self.node_at_link_tail[ln]] += 1 self._number_of_links_at_node[self.node_at_link_head[ln]] += 1 @property def number_of_links_at_node(self): """Number of links connected to each node. Examples -------- >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4)) >>> mg.number_of_links_at_node array([2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2]) LLCATS: LINF NINF CONN """ try: return self._number_of_links_at_node except AttributeError: self._create_number_of_links_at_node() return self._number_of_links_at_node def _create_links_and_link_dirs_at_node(self): """Make arrays with links and link directions at each node. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg.links_at_node array([[ 0, 3, 2, -1, -1, -1], [ 1, 5, 4, 0, -1, -1], [ 7, 6, 1, -1, -1, -1], [ 8, 11, 2, -1, -1, -1], [ 9, 13, 12, 8, 3, 4], [10, 15, 14, 9, 5, 6], [16, 10, 7, -1, -1, -1], [17, 11, 12, -1, -1, -1], [18, 17, 13, 14, -1, -1], [18, 15, 16, -1, -1, -1]]) >>> hg.link_dirs_at_node array([[-1, -1, -1, 0, 0, 0], [-1, -1, -1, 1, 0, 0], [-1, -1, 1, 0, 0, 0], [-1, -1, 1, 0, 0, 0], [-1, -1, -1, 1, 1, 1], [-1, -1, -1, 1, 1, 1], [-1, 1, 1, 0, 0, 0], [-1, 1, 1, 0, 0, 0], [-1, 1, 1, 1, 0, 0], [ 1, 1, 1, 0, 0, 0]], dtype=int8) """ # Find maximum number of links per node nlpn = self.number_of_links_at_node # ^this fn should become member and property max_num_links = np.amax(nlpn) nlpn[:] = 0 # we'll zero it out, then rebuild it # Create arrays for link-at-node information self._links_at_node = - np.ones((self.number_of_nodes, max_num_links), dtype=int) self._link_dirs_at_node = np.zeros((self.number_of_nodes, max_num_links), dtype=np.int8) # Sweep over all links for lk in range(self.number_of_links): # Find the IDs of the tail and head nodes t = self.node_at_link_tail[lk] h = self.node_at_link_head[lk] # Add this link to the list for this node, set the direction # (outgoing, indicated by -1), and increment the number found so # far self._links_at_node[t][nlpn[t]] = lk self._links_at_node[h][nlpn[h]] = lk self._link_dirs_at_node[t][nlpn[t]] = -1 self._link_dirs_at_node[h][nlpn[h]] = 1 nlpn[t] += 1 nlpn[h] += 1 # Sort the links at each node by angle, counter-clockwise from +x self._sort_links_at_node_by_angle() # setup the active link equivalent self._active_link_dirs_at_node = self._link_dirs_at_node.copy() inactive_links = (self.status_at_link[self.links_at_node] == INACTIVE_LINK) inactive_links[self.link_dirs_at_node == 0] = False self._active_link_dirs_at_node[inactive_links] = 0 @property @make_return_array_immutable def angle_of_link(self): """Find and return the angle of a link about the node at the link tail. Examples -------- >>> from landlab import HexModelGrid >>> mg = HexModelGrid(3, 2) >>> mg.angle_of_link / np.pi * 3. # 60 degree segments array([ 0., 2., 1., 2., 1., 0., 0., 1., 2., 1., 2., 0.]) LLCATS: LINF MEAS """ try: if not self._angle_of_link_created: self._create_angle_of_link() except AttributeError: self._create_angle_of_link() return self._angle_of_link_bothends[-1] @property @make_return_array_immutable def angle_of_link_about_head(self): """Find and return the angle of a link about the node at the link head. Because links have direction, their angle can be specified as an angle about either the node at the link head, or the node at the link tail. The default behaviour of `angle_of_link` is to return the angle about the link tail, but this method gives the angle about the link head. Examples -------- >>> from landlab import HexModelGrid >>> mg = HexModelGrid(3, 2) >>> mg.angle_of_link_about_head[:3] / np.pi * 3. # 60 deg segments array([ 3., 5., 4.]) LLCATS: LINF MEAS """ try: if not self._angle_of_link_created: self._create_angle_of_link() except AttributeError: self._create_angle_of_link() return self._angle_of_link_bothends[1] def _create_angle_of_link(self): """ Build a dict with keys (-1, 1) that contains the angles of the links about both the link heads (1) and link tails (-1). Notes ----- dx and dy are the x and y differences between the link endpoints. Multiplying this by dirs orients these offsets correctly (i.e., the correct node is the origin). The call to arctan2 calculates the angle in radians. Angles in the lower two quadrants will be negative and clockwise from the positive x axis. We want them counter-clockwise, which is what the last couple of lines before the return statement do. LLCATS: LINF MEAS """ self._angle_of_link_bothends = {} for dirs in (-1, 1): dx = -dirs * (self.node_x[self.node_at_link_head] - self.node_x[self.node_at_link_tail]) dy = -dirs * (self.node_y[self.node_at_link_head] - self.node_y[self.node_at_link_tail]) ang = np.arctan2(dy, dx) (lower_two_quads, ) = np.where(ang < 0.0) ang[lower_two_quads] = (2 * np.pi) + ang[lower_two_quads] (no_link, ) = np.where(dirs == 0) ang[no_link] = 2*np.pi self._angle_of_link_bothends[dirs] = ang.copy() self._angle_of_link_created = True def _sort_links_at_node_by_angle(self): """Sort the links_at_node and link_dirs_at_node arrays by angle. """ ang = self.angle_of_link[self.links_at_node] linkhead_at_node = self.link_dirs_at_node == 1 ang[linkhead_at_node] = self.angle_of_link_about_head[ self.links_at_node[linkhead_at_node]] ang[self.link_dirs_at_node == 0] = 100. argsorted = np.argsort(ang, axis=1) indices = np.indices(ang.shape)[0] * ang.shape[1] + argsorted self._links_at_node.flat = self._links_at_node.flat[indices.flatten()] self._link_dirs_at_node.flat = self._link_dirs_at_node.flat[ indices.flatten()] def resolve_values_on_links(self, link_values, out=None): """Resolve the xy-components of links. Resolves values provided defined on links into the x and y directions. Returns values_along_x, values_along_y LLCATS: LINF """ return gfuncs.resolve_values_on_links(self, link_values, out=out) @deprecated(use='no replacement', version=1.0) def resolve_values_on_active_links(self, link_values, out=None): """Resolve the xy-components of active links. Resolves values provided defined on active links into the x and y directions. Returns values_along_x, values_along_y LLCATS: LINF """ return gfuncs.resolve_values_on_active_links(self, link_values, out=out) def link_at_node_is_upwind(self, values, out=None): """ Return a boolean the same shape as :func:`links_at_node` which flags links which are upwind of the node as True. link_at_node_is_upwind iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node. It then return a boolean array the same shape as links_at_node flagging these links. e.g., for a raster, the returned array will be shape (nnodes, 4). Parameters ---------- values : str or array Name of variable field defined at links, or array of values at links. out : ndarray, optional Buffer to place mapped values into or `None` to create a new array. Must be correct shape and boolean dtype. Returns ------- ndarray Boolean of which links are upwind at nodes. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((3, 4)) >>> rmg.at_link['grad'] = np.array([-1., -2., -1., ... -2., -3., -4., -5., ... -1., -2., -1., ... -1., -2., -3., -4., ... -1., -2., -1.]) >>> rmg.link_at_node_is_upwind('grad') array([[False, False, False, False], [False, False, True, False], [False, False, True, False], [False, False, True, False], [False, False, False, True], [False, False, True, True], [False, False, True, True], [False, False, True, True], [False, False, False, True], [False, False, True, True], [False, False, True, True], [False, False, True, True]], dtype=bool) LLCATS: LINF NINF CONN """ if out is None: out = np.empty_like(self.links_at_node, dtype=bool) else: assert out.shape is self.links_at_node.shape assert out.dtype is bool if type(values) is str: vals = self.at_link[values] else: assert len(values) == self.number_of_links vals = values values_at_links = vals[self.links_at_node] * self.link_dirs_at_node # this procedure makes incoming links NEGATIVE np.less(values_at_links, 0., out=out) return out def link_at_node_is_downwind(self, values, out=None): """ Return a boolean the same shape as :func:`links_at_node` which flags links which are downwind of the node as True. link_at_node_is_downwind iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node. It then return a boolean array the same shape as links_at_node flagging these links. e.g., for a raster, the returned array will be shape (nnodes, 4). Parameters ---------- values : str or array Name of variable field defined at links, or array of values at links. out : ndarray, optional Buffer to place mapped values into or `None` to create a new array. Must be correct shape and boolean dtype. Returns ------- ndarray Boolean of which links are downwind at nodes. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((3, 4)) >>> rmg.at_link['grad'] = np.array([-1., -2., -1., ... -2., -3., -4., -5., ... -1., -2., -1., ... -1., -2., -3., -4., ... -1., -2., -1.]) >>> rmg.link_at_node_is_downwind('grad') array([[ True, True, False, False], [ True, True, False, False], [ True, True, False, False], [False, True, False, False], [ True, True, False, False], [ True, True, False, False], [ True, True, False, False], [False, True, False, False], [ True, False, False, False], [ True, False, False, False], [ True, False, False, False], [False, False, False, False]], dtype=bool) LLCATS: LINF NINF CONN """ if out is None: out = np.empty_like(self.links_at_node, dtype=bool) else: assert out.shape is self.links_at_node.shape assert out.dtype is bool if type(values) is str: vals = self.at_link[values] else: assert len(values) == self.number_of_links vals = values values_at_links = vals[self.links_at_node] * self.link_dirs_at_node # this procedure makes incoming links NEGATIVE np.greater(values_at_links, 0., out=out) return out def upwind_links_at_node(self, values, bad_index=-1): """ Return an (nnodes, X) shape array of link IDs of which links are upwind of each node, according to *values* (field or array). X is the maximum upwind links at any node. Nodes with fewer upwind links than this have additional slots filled with *bad_index*. Links are ordered anticlockwise from east. Parameters ---------- values : str or array Name of variable field defined at links, or array of values at links. bad_index : int Index to place in array indicating no link. Returns ------- ndarray Array of upwind link IDs Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((3, 4)) >>> rmg.at_link['grad'] = np.array([-1., -2., -1., ... -2., -3., -4., -5., ... -1., -2., -1., ... -1., -2., -3., -4., ... -1., -2., -1.]) >>> rmg.upwind_links_at_node('grad', bad_index=-1) array([[-1, -1], [ 0, -1], [ 1, -1], [ 2, -1], [ 3, -1], [ 7, 4], [ 8, 5], [ 9, 6], [10, -1], [14, 11], [15, 12], [16, 13]]) LLCATS: LINF NINF CONN """ if type(values) is str: vals = self.at_link[values] else: assert len(values) == self.number_of_links vals = values values_at_links = vals[self.links_at_node] * self.link_dirs_at_node # this procedure makes incoming links NEGATIVE unordered_IDs = np.where(values_at_links < 0., self.links_at_node, bad_index) bad_IDs = unordered_IDs == bad_index nnodes = self.number_of_nodes flat_sorter = (np.argsort(bad_IDs, axis=1) + self.links_at_node.shape[1] * np.arange(nnodes).reshape((nnodes, 1))) big_ordered_array = unordered_IDs.ravel()[flat_sorter].reshape( self.links_at_node.shape) cols_to_cut = int(bad_IDs.sum(axis=1).min()) if cols_to_cut > 0: return big_ordered_array[:, :-cols_to_cut] else: return big_ordered_array def downwind_links_at_node(self, values, bad_index=-1): """ Return an (nnodes, X) shape array of link IDs of which links are downwind of each node, according to *values* (array or field). X is the maximum downwind links at any node. Nodes with fewer downwind links than this have additional slots filled with *bad_index*. Links are ordered anticlockwise from east. Parameters ---------- values : str or array Name of variable field defined at links, or array of values at links. bad_index : int Index to place in array indicating no link. Returns ------- ndarray Array of upwind link IDs Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid, BAD_INDEX_VALUE >>> rmg = RasterModelGrid((3, 4)) >>> rmg.at_link['grad'] = np.array([-1., -2., -1., ... -2., -3., -4., -5., ... -1., -2., -1., ... -1., -2., -3., -4., ... -1., -2., -1.]) >>> rmg.downwind_links_at_node('grad', bad_index=BAD_INDEX_VALUE) array([[ 0, 3], [ 1, 4], [ 2, 5], [ 6, -1], [ 7, 10], [ 8, 11], [ 9, 12], [13, -1], [14, -1], [15, -1], [16, -1], [-1, -1]]) LLCATS: LINF NINF CONN """ if type(values) is str: vals = self.at_link[values] else: assert len(values) == self.number_of_links vals = values values_at_links = vals[self.links_at_node] * self.link_dirs_at_node # this procedure makes incoming links NEGATIVE unordered_IDs = np.where(values_at_links > 0., self.links_at_node, bad_index) bad_IDs = unordered_IDs == bad_index nnodes = self.number_of_nodes flat_sorter = (np.argsort(bad_IDs, axis=1) + self.links_at_node.shape[1] * np.arange(nnodes).reshape((nnodes, 1))) big_ordered_array = unordered_IDs.ravel()[flat_sorter].reshape( self.links_at_node.shape) cols_to_cut = int(bad_IDs.sum(axis=1).min()) if cols_to_cut > 0: return big_ordered_array[:, :-cols_to_cut] else: return big_ordered_array @property def faces_at_cell(self): """Return array containing face IDs at each cell. Creates array if it doesn't already exist. Examples -------- >>> from landlab import HexModelGrid, RasterModelGrid >>> mg = RasterModelGrid((4, 5)) >>> mg.faces_at_cell array([[ 4, 7, 3, 0], [ 5, 8, 4, 1], [ 6, 9, 5, 2], [11, 14, 10, 7], [12, 15, 11, 8], [13, 16, 12, 9]]) >>> mg = HexModelGrid(3, 4) >>> mg.faces_at_cell array([[ 7, 11, 10, 6, 0, 1], [ 8, 13, 12, 7, 2, 3], [ 9, 15, 14, 8, 4, 5]]) LLCATS: FINF CINF CONN """ try: return self._faces_at_cell except AttributeError: self._create_faces_at_cell() return self._faces_at_cell def number_of_faces_at_cell(self): """Number of faces attached to each cell. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg.number_of_faces_at_cell() array([6, 6]) LLCATS: FINF CINF CONN """ num_faces_at_cell = np.zeros(self.number_of_cells, dtype=np.int) for ln in range(self.number_of_links): cell = self.cell_at_node[self.node_at_link_tail[ln]] if cell != BAD_INDEX_VALUE: num_faces_at_cell[cell] += 1 cell = self.cell_at_node[self.node_at_link_head[ln]] if cell != BAD_INDEX_VALUE: num_faces_at_cell[cell] += 1 return num_faces_at_cell def _sort_faces_at_cell_by_angle(self): """Sort the faces_at_cell array by angle. Assumes links_at_node and link_dirs_at_node created. """ for cell in range(self.number_of_cells): sorted_links = self.links_at_node[self.node_at_cell[cell], :] sorted_faces = self._faces_at_cell[cell, :] = self.face_at_link[ sorted_links] self._faces_at_cell[cell, :] = sorted_faces def _create_faces_at_cell(self): """Construct faces_at_cell array. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg._create_faces_at_cell() >>> hg._faces_at_cell array([[ 5, 8, 7, 4, 0, 1], [ 6, 10, 9, 5, 2, 3]]) """ num_faces = self.number_of_faces_at_cell() self._faces_at_cell = np.zeros((self.number_of_cells, np.amax(num_faces)), dtype=int) num_faces[:] = 0 # Zero out and count again, to use as index for ln in range(self.number_of_links): cell = self.cell_at_node[self.node_at_link_tail[ln]] if cell != BAD_INDEX_VALUE: self._faces_at_cell[cell, num_faces[cell]] = \ self.face_at_link[ln] num_faces[cell] += 1 cell = self.cell_at_node[self.node_at_link_head[ln]] if cell != BAD_INDEX_VALUE: self._faces_at_cell[cell, num_faces[cell]] = \ self.face_at_link[ln] num_faces[cell] += 1 self._sort_faces_at_cell_by_angle() @property @make_return_array_immutable def patches_present_at_node(self): """ A boolean array, False where a patch has a closed node or is missing. The array is the same shape as :func:`patches_at_node`, and is designed to mask it. Note that in cases where patches may have more than 3 nodes (e.g., rasters), a patch is considered still present as long as at least 3 open nodes are present. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((3, 3)) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.patches_at_node array([[ 0, -1, -1, -1], [ 1, 0, -1, -1], [-1, 1, -1, -1], [ 2, -1, -1, 0], [ 3, 2, 0, 1], [-1, 3, 1, -1], [-1, -1, -1, 2], [-1, -1, 2, 3], [-1, -1, 3, -1]]) >>> mg.patches_present_at_node array([[ True, False, False, False], [ True, True, False, False], [False, True, False, False], [False, False, False, True], [False, False, True, True], [False, False, True, False], [False, False, False, False], [False, False, False, False], [False, False, False, False]], dtype=bool) >>> 1 in mg.patches_at_node * mg.patches_present_at_node True >>> 2 in mg.patches_at_node * mg.patches_present_at_node False LLCATS: PINF NINF """ try: return self._patches_present_mask except AttributeError: self.patches_at_node self._reset_patch_status() return self._patches_present_mask @property @make_return_array_immutable def patches_present_at_link(self): """ A boolean array, False where a patch has a closed node or is missing. The array is the same shape as :func:`patches_at_link`, and is designed to mask it. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((3, 3)) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.patches_at_link array([[ 0, -1], [ 1, -1], [ 0, -1], [ 0, 1], [ 1, -1], [ 0, 2], [ 1, 3], [ 2, -1], [ 2, 3], [ 3, -1], [ 2, -1], [ 3, -1]]) >>> mg.patches_present_at_link array([[ True, False], [ True, False], [ True, False], [ True, True], [ True, False], [ True, False], [ True, False], [False, False], [False, False], [False, False], [False, False], [False, False]], dtype=bool) >>> 1 in mg.patches_at_link * mg.patches_present_at_link True >>> 2 in mg.patches_at_link * mg.patches_present_at_link False LLCATS: PINF LINF """ try: return self._patches_present_link_mask except AttributeError: self.patches_at_node self._reset_patch_status() return self._patches_present_link_mask @property @make_return_array_immutable def number_of_patches_present_at_node(self): """Return the number of patches at a node without a closed node. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((3, 3)) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.patches_present_at_node array([[ True, False, False, False], [ True, True, False, False], [False, True, False, False], [False, False, False, True], [False, False, True, True], [False, False, True, False], [False, False, False, False], [False, False, False, False], [False, False, False, False]], dtype=bool) >>> mg.number_of_patches_present_at_node array([1, 2, 1, 1, 2, 1, 0, 0, 0]) LLCATS: PINF NINF BC """ try: return self._number_of_patches_present_at_node except AttributeError: self.patches_at_node self._reset_patch_status() return self._number_of_patches_present_at_node @property @make_return_array_immutable def number_of_patches_present_at_link(self): """Return the number of patches at a link without a closed node. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((3, 3)) >>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY >>> mg.patches_present_at_link array([[ True, False], [ True, False], [ True, False], [ True, True], [ True, False], [ True, False], [ True, False], [False, False], [False, False], [False, False], [False, False], [False, False]], dtype=bool) >>> mg.number_of_patches_present_at_link array([1, 1, 1, 2, 1, 1, 1, 0, 0, 0, 0, 0]) LLCATS: PINF LINF BC """ try: return self._number_of_patches_present_at_link except AttributeError: self.patches_at_node self._reset_patch_status() return self._number_of_patches_present_at_link def _reset_patch_status(self): """ Creates the array which stores patches_present_at_node. Call whenever boundary conditions are updated on the grid. """ from landlab import RasterModelGrid, VoronoiDelaunayGrid node_status_at_patch = self.status_at_node[self.nodes_at_patch] if isinstance(self, RasterModelGrid): max_nodes_at_patch = 4 elif isinstance(self, VoronoiDelaunayGrid): max_nodes_at_patch = 3 else: max_nodes_at_patch = (self.nodes_at_patch > -1).sum(axis=1) any_node_at_patch_closed = (node_status_at_patch == CLOSED_BOUNDARY).sum(axis=1) > ( max_nodes_at_patch - 3) absent_patches = any_node_at_patch_closed[self.patches_at_node] bad_patches = numpy.logical_or(absent_patches, self.patches_at_node == -1) self._patches_present_mask = numpy.logical_not( bad_patches) self._number_of_patches_present_at_node = numpy.sum( self._patches_present_mask, axis=1) absent_patches = any_node_at_patch_closed[self.patches_at_link] bad_patches = numpy.logical_or(absent_patches, self.patches_at_link == -1) self._patches_present_link_mask = numpy.logical_not( bad_patches) self._number_of_patches_present_at_link = numpy.sum( self._patches_present_link_mask, axis=1) def calc_hillshade_at_node(self, alt=45., az=315., slp=None, asp=None, unit='degrees', elevs='topographic__elevation'): """Get array of hillshade. .. codeauthor:: Katy Barnhart <katherine.barnhart@colorado.edu> Parameters ---------- alt : float Sun altitude (from horizon) - defaults to 45 degrees az : float Sun azimuth (CW from north) - defaults to 315 degrees slp : float slope of cells at surface - optional asp : float aspect of cells at surface (from north) - optional (with slp) unit : string 'degrees' (default) or 'radians' - only needed if slp and asp are not provided If slp and asp are both not specified, 'elevs' must be provided as a grid field name (defaults to 'topographic__elevation') or an nnodes-long array of elevation values. In this case, the method will calculate local slopes and aspects internally as part of the hillshade production. Returns ------- ndarray of float Hillshade at each cell. Notes ----- code taken from GeospatialPython.com example from December 14th, 2014 DEJH found what looked like minor sign problems, and adjusted to follow the ArcGIS algorithm: http://help.arcgis.com/en/arcgisdesktop/10.0/ help/index.html#/How_Hillshade_works/009z000000z2000000/ . Remember when plotting that bright areas have high values. cmap='Greys' will give an apparently inverted color scheme. *cmap='gray'* has white associated with the high values, so is recommended for plotting. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((5, 5), 1.) >>> z = mg.x_of_node * np.tan(60. * np.pi / 180.) >>> mg.calc_hillshade_at_node(elevs=z, alt=30., az=210.) array([ 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625, 0.625]) LLCATS: NINF SURF """ if slp is not None and asp is not None: if unit == 'degrees': (alt, az, slp, asp) = (numpy.radians(alt), numpy.radians(az), numpy.radians(slp), numpy.radians(asp)) elif unit == 'radians': if alt > numpy.pi / 2. or az > 2. * numpy.pi: six.print_( 'Assuming your solar properties are in degrees, ' 'but your slopes and aspects are in radians...') (alt, az) = (numpy.radians(alt), numpy.radians(az)) # ...because it would be super easy to specify radians, # but leave the default params alone... else: raise TypeError("unit must be 'degrees' or 'radians'") elif slp is None and asp is None: if unit == 'degrees': (alt, az) = (numpy.radians(alt), numpy.radians(az)) elif unit == 'radians': pass else: raise TypeError("unit must be 'degrees' or 'radians'") slp, slp_comps = self.calc_slope_at_node( elevs, return_components=True) asp = self.calc_aspect_at_node(slope_component_tuple=slp_comps, unit='radians') else: raise TypeError('Either both slp and asp must be set, or neither!') shaded = ( numpy.sin(alt) * numpy.cos(slp) + numpy.cos(alt) * numpy.sin(slp) * numpy.cos(az - asp) ) return shaded.clip(0.) @deprecated(use='calc_flux_div_at_node', version=1.0) def calculate_flux_divergence_at_core_nodes(self, active_link_flux, net_unit_flux=None): r"""Get array of flux divergence for core nodes. Given an array of fluxes along links, computes the net total flux within each cell, divides by cell area, and stores the result in net_unit_flux. The function works by calling calculate_flux_divergence_at_nodes, then slicing out only the values at core nodes. Therefore, it is slower than calculate_flux_divergence_at_nodes, even though it returns a shorter list of numbers. The input active_link_flux should be flux of something (e.g., mass, momentum, energy) per unit face width, positive if flowing in the same direction as its link, and negative otherwise. There should be one value per active link. Returns an array of net total flux per unit area, one value per core node (creates this array if it is not given as an argument). By convention, divergence is positive for net outflow, and negative for net outflow. That's why we *add* outgoing flux and *subtract* incoming flux. This makes net_unit_flux have the same sign and dimensions as a typical divergence term in a conservation equation. In general, for a polygonal cell with *N* sides of lengths Li and with surface area A, the net influx divided by cell area would be: .. math:: {Q_{net} \over A} = {1 \over A} \sum{q_i L_i} For a square cell, which is what we have in RasterModelGrid, the sum is over 4 sides of length dx, and :math:`A = dx^2`, so: .. math:: {Q_{net} \over A} = {1 \over dx} \sum{q_i} .. note:: The net flux is defined as positive outward, negative inward. In a diffusion problem, for example, one would use: .. math:: {du \over dt} = \text{source} - \text{fd} where *fd* is "flux divergence". Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((4, 5), 1.0) >>> u = [0., 1., 2., 3., 0., ... 1., 2., 3., 2., 3., ... 0., 1., 2., 1., 2., ... 0., 0., 2., 2., 0.] >>> u = np.array(u) >>> grad = rmg.calc_grad_at_link(u)[rmg.active_links] >>> grad array([ 1., 1., -1., 1., 1., -1., 1., -1., -1., -1., 1., 1., -1., 1., -1., 0., 1.]) >>> flux = - grad # downhill flux proportional to gradient >>> divflux = rmg.calculate_flux_divergence_at_core_nodes(flux) >>> divflux array([ 2., 4., -2., 0., 1., -4.]) If calculate_gradients_at_core_nodes is called inside a loop, you can improve speed slightly by creating an array outside the loop. For example, do this once, before the loop: >>> divflux = np.zeros(rmg.number_of_core_cells) # outside loop Then do this inside the loop: >>> divflux = rmg.calculate_flux_divergence_at_core_nodes( ... flux, divflux) In this case, the function will not have to create the divflux array. Note this method is untested with looped boundary conditions. LLCATS: DEPR NINF GRAD """ if self._DEBUG_TRACK_METHODS: six.print_('ModelGrid.calculate_flux_divergence_at_core_nodes') assert (len(active_link_flux) == self.number_of_active_links), \ "incorrect length of active_link_flux array" # If needed, create net_unit_flux array if net_unit_flux is None: net_unit_flux = numpy.zeros(self.number_of_core_nodes) else: net_unit_flux[:] = 0. assert (len(net_unit_flux)) == self.number_of_core_nodes node_net_unit_flux = self.calculate_flux_divergence_at_nodes( active_link_flux) node_at_core_cell = self.node_at_cell[self.core_cells] net_unit_flux = node_net_unit_flux[node_at_core_cell] return net_unit_flux @deprecated(use='calc_flux_div_at_node', version=1.0) def calculate_flux_divergence_at_nodes(self, active_link_flux, out=None): """Flux divergence at nodes. Same as calculate_flux_divergence_at_active_cells, but works with and returns a list of net unit fluxes that corresponds to all nodes, rather than just active cells. Note that we don't compute net unit fluxes at boundary nodes (which don't have active cells associated with them, and often don't have cells of any kind, because they are on the perimeter), but simply return zeros for these entries. The advantage is that the caller can work with node-based arrays instead of active-cell-based arrays. This method is untested with looped boundary conditions. LLCATS: DEPR NINF GRAD """ return gfuncs.calculate_flux_divergence_at_nodes(self, active_link_flux, out=out) @property @make_return_array_immutable def cell_area_at_node(self): """Cell areas in a nnodes-long array. Zeros are entered at all perimeter nodes, which lack cells. Returns ------- ndarray Cell areas as an n_nodes-long array. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5), spacing=(3, 4)) >>> grid.status_at_node[7] = CLOSED_BOUNDARY >>> grid.cell_area_at_node array([ 0., 0., 0., 0., 0., 0., 12., 12., 12., 0., 0., 12., 12., 12., 0., 0., 0., 0., 0., 0.]) LLCATS: CINF NINF CONN """ try: return self._cell_area_at_node except AttributeError: return self._create_cell_areas_array_force_inactive() @property @deprecated(use='width_of_face', version=1.0) def face_width(self): """ LLCATS: DEPR FINF MEAS """ return self.width_of_face @property @make_return_array_immutable def width_of_face(self): """Width of grid faces. Examples -------- >>> from landlab import RasterModelGrid, HexModelGrid >>> mg = RasterModelGrid((3, 4), (1., 2.)) >>> mg.width_of_face array([ 2., 2., 2., 1., 1., 1., 1.]) >>> mg = HexModelGrid(3, 3) >>> np.allclose(mg.width_of_face, 0.57735027) True LLCATS: FINF MEAS """ try: return self._face_width except AttributeError: return self._create_face_width() def _create_face_at_link(self): """Set up face_at_link array. Examples -------- >>> from landlab import HexModelGrid, BAD_INDEX_VALUE >>> hg = HexModelGrid(3, 3) >>> face_at_link = hg.face_at_link.copy() >>> face_at_link[face_at_link == BAD_INDEX_VALUE] = -1 >>> face_at_link # doctest: +NORMALIZE_WHITESPACE array([-1, -1, -1, 0, 1, 2, 3, -1, 4, 5, 6, -1, 7, 8, 9, 10, -1, -1, -1]) """ self._face_at_link = numpy.full(self.number_of_links, BAD_INDEX_VALUE, dtype=int) face_id = 0 for link in range(self.number_of_links): tc = self.cell_at_node[self.node_at_link_tail[link]] hc = self.cell_at_node[self.node_at_link_head[link]] if tc != BAD_INDEX_VALUE or hc != BAD_INDEX_VALUE: self._face_at_link[link] = face_id face_id += 1 return self._face_at_link def _create_link_at_face(self): """Set up link_at_face array. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg.link_at_face array([ 3, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15]) """ num_faces = len(self.width_of_face) self._link_at_face = numpy.empty(num_faces, dtype=int) face_id = 0 for link in range(self.number_of_links): tc = self.cell_at_node[self.node_at_link_tail[link]] hc = self.cell_at_node[self.node_at_link_head[link]] if tc != BAD_INDEX_VALUE or hc != BAD_INDEX_VALUE: self._link_at_face[face_id] = link face_id += 1 return self._link_at_face def _create_cell_areas_array_force_inactive(self): """Set up an array of cell areas that is n_nodes long. Sets up an array of cell areas that is nnodes long. Nodes that have cells receive the area of that cell. Nodes which do not, receive zeros. """ _cell_area_at_node_zero = numpy.zeros(self.number_of_nodes, dtype=float) _cell_area_at_node_zero[self.node_at_cell] = self.area_of_cell self._cell_area_at_node = _cell_area_at_node_zero return self._cell_area_at_node @deprecated(use='no replacement', version=1.0) def active_link_connecting_node_pair(self, node1, node2): """Get the active link that connects a pair of nodes. Returns the ID number of the active link that connects the given pair of nodes, or BAD_INDEX_VALUE if not found. This method is slow, and can only take single ints as *node1* and *node2*. It should ideally be overridden for optimal functionality in more specialized grid modules (e.g., raster). Examples -------- >>> import landlab as ll >>> rmg = ll.RasterModelGrid((4, 5)) >>> rmg.active_link_connecting_node_pair(8, 3) array([2]) LLCATS: DEPR LINF NINF CONN """ active_link = BAD_INDEX_VALUE for alink in range(0, self.number_of_active_links): link_connects_nodes = ( (self._activelink_fromnode[alink] == node1 and self._activelink_tonode[alink] == node2) or (self._activelink_tonode[alink] == node1 and self._activelink_fromnode[alink] == node2)) if link_connects_nodes: active_link = alink break return numpy.array([active_link]) @property @make_return_array_immutable def area_of_cell(self): """Get areas of grid cells. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5), spacing=(2, 3)) >>> grid.area_of_cell # doctest: +NORMALIZE_WHITESPACE array([ 6., 6., 6., 6., 6., 6.]) LLCATS: CINF MEAS """ return self._area_of_cell @property @deprecated(use='length_of_link', version=1.0) def link_length(self): """ LLCATS: DEPR LINF MEAS """ return self.length_of_link @property def length_of_link(self): """Get lengths of links. Returns ------- ndarray Lengths of all links, in ID order. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) >>> grid.length_of_link array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) >>> len(grid.length_of_link) == grid.number_of_links True LLCATS: LINF MEAS """ if self._link_length is None: return self._create_length_of_link() else: return self._link_length @property def _length_of_link_with_diagonals(self): """A dummy function, equivalent to `length_of_link` for the base class. This method is required to maintain grid class generality in several of the flow routing and stream power components. It is overridden in RasterModelGrid only. This method will be removed when LL's handling of diagonal links is modernized. """ return self.length_of_link def _create_length_of_link(self): """Get array of the lengths of all links. Calculates, returns, and stores as a property of the grid the lengths of all the links in the grid. """ if self._link_length is None: self._link_length = self.empty(at='link', dtype=float) diff_x = (self.node_x[self.node_at_link_tail] - self.node_x[self.node_at_link_head]) diff_y = (self.node_y[self.node_at_link_tail] - self.node_y[self.node_at_link_head]) numpy.sqrt(diff_x ** 2 + diff_y ** 2, out=self._link_length) return self._link_length @deprecated(use='map_max_of_link_nodes_to_link', version=1.0) def _assign_upslope_vals_to_active_links(self, u, v=None): """Assign upslope node value to link. Assigns to each active link the value of *u* at whichever of its neighbors has a higher value of *v*. If *v* is omitted, uses *u* for both. The order of the link values is by link ID. Parameters ---------- u : array-like Node values to assign to links. v : array-like, optional Node values to test for upslope-ness. Returns ------- ndarray Values at active links. Examples -------- >>> from landlab import RasterModelGrid >>> import numpy as np >>> grid = RasterModelGrid((3, 3)) >>> u = np.arange(9.) >>> grid._assign_upslope_vals_to_active_links(u) array([ 4., 4., 5., 7.]) LLCATS: DEPR NINF LINF CONN """ if v is None: v = numpy.array((0., )) fv = numpy.zeros(self.number_of_active_links) if len(v) < len(u): for i in range(0, self.number_of_active_links): fv[i] = max(u[self._activelink_fromnode[i]], u[self._activelink_tonode[i]]) else: for i in range(0, self.number_of_active_links): if (v[self._activelink_fromnode[i]] > v[self._activelink_tonode[i]]): fv[i] = u[self._activelink_fromnode[i]] else: fv[i] = u[self._activelink_tonode[i]] return fv def _reset_link_status_list(self): """Create of reset a list of links statuses. Creates or resets a list of link statuses. We do this by sweeping through the given lists of from and to nodes, and checking the status of these as given in the node_status list. A link is active if both its nodes are core, or if one is core and the other is fixed value. A link is inactive if either node is closed. A link is fixed if either node is fixed gradient. Note that by default, any link which has been previously set as fixed will remain so, and if a closed-core node pair is found at each of its ends, the closed node will be converted to a fixed gradient node. If you want to close a node which has a fixed link already connected to it, first change the link status to inactive. A further test is performed to ensure that the final maps of node and link status are internally consistent. """ if self._DEBUG_TRACK_METHODS: six.print_('ModelGrid._reset_link_status_list') try: already_fixed = self._status_at_link == FIXED_LINK except AttributeError: already_fixed = numpy.zeros(self.number_of_links, dtype=bool) fromnode_status = self._node_status[self.node_at_link_tail] tonode_status = self._node_status[self.node_at_link_head] if not numpy.all((fromnode_status[already_fixed] == FIXED_GRADIENT_BOUNDARY) | (tonode_status[already_fixed] == FIXED_GRADIENT_BOUNDARY)): assert numpy.all(np.logical_not((fromnode_status[already_fixed] == CLOSED_BOUNDARY) & (tonode_status[already_fixed] == CLOSED_BOUNDARY))) fromnode_status[already_fixed] = numpy.where( (fromnode_status[already_fixed] == CLOSED_BOUNDARY) & (tonode_status[already_fixed] == CORE_NODE), FIXED_GRADIENT_BOUNDARY, fromnode_status[already_fixed]) tonode_status[already_fixed] = numpy.where( (tonode_status[already_fixed] == CLOSED_BOUNDARY) & (fromnode_status[already_fixed] == CORE_NODE), FIXED_GRADIENT_BOUNDARY, tonode_status[already_fixed]) warnings.warn(""" Remember, fixed_links are dominant over node statuses. Your grid may have had an incompatibility between fixed_links and closed nodes, which has been resolved by converting the closed nodes to fixed gradient nodes. If you were trying to deliberately close a node which had once been set to fixed gradient, you need to open the links before changing the node statuses. If you were setting a node to fixed_value, you can ignore this message. """) active_links = (((fromnode_status == CORE_NODE) & ~ (tonode_status == CLOSED_BOUNDARY)) | ((tonode_status == CORE_NODE) & ~ (fromnode_status == CLOSED_BOUNDARY))) # ...this still includes things that will become fixed_link fixed_links = ((((fromnode_status == FIXED_GRADIENT_BOUNDARY) & (tonode_status == CORE_NODE)) | ((tonode_status == FIXED_GRADIENT_BOUNDARY) & (fromnode_status == CORE_NODE))) | already_fixed) fixed_link_fixed_val = (((fromnode_status == FIXED_VALUE_BOUNDARY) | (tonode_status == FIXED_VALUE_BOUNDARY)) & already_fixed) # these are the "special cases", where the user is probably trying to # adjust an individual fixed_link back to fixed value. We'll allow it: fixed_links[fixed_link_fixed_val] = False try: self._status_at_link.fill(INACTIVE_LINK) except AttributeError: self._status_at_link = numpy.empty(self.number_of_links, dtype=int) self._status_at_link.fill(INACTIVE_LINK) self._status_at_link[active_links] = ACTIVE_LINK self._status_at_link[fixed_links] = FIXED_LINK active_links = self._status_at_link == ACTIVE_LINK # now it's correct (self._active_links, ) = numpy.where(active_links) (self._fixed_links, ) = numpy.where(fixed_links) self._active_links = as_id_array(self._active_links) self._fixed_links = as_id_array(self._fixed_links) self._activelink_fromnode = self.node_at_link_tail[active_links] self._activelink_tonode = self.node_at_link_head[active_links] # Set up active inlink and outlink matrices self._setup_active_inlink_and_outlink_matrices() #self._create_links_and_link_dirs_at_node() def _reset_lists_of_nodes_cells(self): """Create of reset lists of nodes and cells based on their status. Creates or resets various lists of nodes and cells based on their statuses. Call this function whenever you make changes to the boundary conditions in the grid. The updated attributes and arrays are: * activecell_node * * corecell_node * * core_cells * _boundary_nodes Examples -------- >>> import landlab >>> grid = landlab.RasterModelGrid((4, 5)) >>> grid.status_at_node[7] = landlab.CLOSED_BOUNDARY >>> grid.core_cells array([0, 2, 3, 4, 5]) """ (self._core_nodes, ) = numpy.where(self._node_status == CORE_NODE) self._core_cells = self.cell_at_node[self._core_nodes] self._boundary_nodes = as_id_array( numpy.where(self._node_status != CORE_NODE)[0]) def _update_links_nodes_cells_to_new_BCs(self): """Update grid element connectivity, status. This method updates all of the various lists and attributes governed by node status (e.g., core nodes, active links, etc) when you change node statuses. Call it if your method or driver makes changes to the boundary conditions of nodes in the grid. """ self._reset_link_status_list() self._reset_lists_of_nodes_cells() self._create_active_faces() self._active_link_dirs_at_node[:] = self._link_dirs_at_node[:] inactive_links = (self.status_at_link[self.links_at_node] == INACTIVE_LINK) inactive_links[self.link_dirs_at_node == 0] = False self._active_link_dirs_at_node[inactive_links] = 0 try: if self.diagonal_list_created: self.diagonal_list_created = False except AttributeError: pass try: if self.neighbor_list_created: self.neighbor_list_created = False except AttributeError: pass try: self._fixed_grad_links_created except AttributeError: pass else: self._gradient_boundary_node_links() self._create_fixed_gradient_boundary_node_anchor_node() try: if self._patches_created: self._reset_patch_status() except AttributeError: pass try: self.bc_set_code += 1 except AttributeError: self.bc_set_code = 0 @deprecated(use='set_nodata_nodes_to_closed', version='0.2') def set_nodata_nodes_to_inactive(self, node_data, nodata_value): """Make no-data nodes inactive. Set the status to CLOSED_BOUNDARY for all nodes whose value of node_data is equal to the nodata_value. Parameters ---------- node_data : ndarray Data values. nodata_value : float Value that indicates an invalid value. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> mg = RasterModelGrid((3, 4), 1.0) >>> mg.status_at_node array([1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8) >>> h = np.array([-9999, -9999, -9999, -9999, ... -9999, -9999, 12345., 0., ... -9999, 0., 0., 0.]) >>> mg.set_nodata_nodes_to_inactive(h, -9999) >>> mg.status_at_node array([4, 4, 4, 4, 4, 4, 0, 1, 4, 1, 1, 1], dtype=int8) LLCATS: DEPR NINF BC """ self.set_nodata_nodes_to_closed(node_data, nodata_value) def set_nodata_nodes_to_closed(self, node_data, nodata_value): """Make no-data nodes closed boundaries. Sets node status to :any:`CLOSED_BOUNDARY` for all nodes whose value of *node_data* is equal to the *nodata_value*. Any links connected to :any:`CLOSED_BOUNDARY` nodes are automatically set to :any:`INACTIVE_LINK` boundary. Parameters ---------- node_data : ndarray Data values. nodata_value : float Value that indicates an invalid value. Examples -------- The following example uses the following grid:: *--I--->o------>o------>o ^ ^ ^ ^ I I | | | | | | *--I--->*--I--->o------>o ^ ^ ^ ^ I I I I | | | | *--I--->*--I--->*--I--->* .. note:: Links set to :any:`ACTIVE_LINK` are not shown in this diagram. ``*`` indicates the nodes that are set to :any:`CLOSED_BOUNDARY` ``o`` indicates the nodes that are set to :any:`CORE_NODE` ``I`` indicates the links that are set to :any:`INACTIVE_LINK` >>> import numpy as np >>> import landlab as ll >>> mg = ll.RasterModelGrid((3, 4), 1.0) >>> mg.status_at_node array([1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8) >>> h = np.array([-9999, -9999, -9999, -9999, -9999, -9999, 12345., ... 0., -9999, 0., 0., 0.]) >>> mg.set_nodata_nodes_to_closed(h, -9999) >>> mg.status_at_node array([4, 4, 4, 4, 4, 4, 0, 1, 4, 1, 1, 1], dtype=int8) LLCATS: BC NINF """ # Find locations where value equals the NODATA code and set these nodes # as inactive boundaries. nodata_locations = numpy.nonzero(node_data == nodata_value) self._node_status[nodata_locations] = CLOSED_BOUNDARY # Recreate the list of active cell IDs self._update_links_nodes_cells_to_new_BCs() def set_nodata_nodes_to_fixed_gradient(self, node_data, nodata_value): """Make no-data nodes fixed gradient boundaries. Set node status to :any:`FIXED_GRADIENT_BOUNDARY` for all nodes whose value of *node_data* is equal to *nodata_value*. Any links between :any:`FIXED_GRADIENT_BOUNDARY` nodes and :any:`CORE_NODES` are automatically set to :any:`FIXED_LINK` boundary status. Parameters ---------- node_data : ndarray Data values. nodata_value : float Value that indicates an invalid value. Examples -------- The following examples use this grid:: *--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->* ^ ^ ^ ^ ^ ^ ^ ^ ^ I I I X X X X X I | | | | | | | | | *--I--->*--I--->*--X--->o o o o o--X--->* ^ ^ ^ ^ ^ ^ ^ ^ ^ I I I | | | | | I | | | | | | | | | *--I--->*--I--->*--X--->o o o o o--X--->* ^ ^ ^ ^ ^ ^ ^ ^ ^ I I I X X X X X I | | | | | | | | | *--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->* .. note:: Links set to :any:`ACTIVE_LINK` are not shown in this diagram. ``X`` indicates the links that are set to :any:`FIXED_LINK` ``I`` indicates the links that are set to :any:`INACTIVE_LINK` ``o`` indicates the nodes that are set to :any:`CORE_NODE` ``*`` indicates the nodes that are set to :any:`FIXED_GRADIENT_BOUNDARY` >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((4, 9)) >>> rmg.status_at_node # doctest: +NORMALIZE_WHITESPACE array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int8) >>> z = rmg.zeros(at='node') >>> z = np.array([ ... -99., -99., -99., -99., -99., -99., -99., -99., -99., ... -99., -99., -99., 0., 0., 0., 0., 0., -99., ... -99., -99., -99., 0., 0., 0., 0., 0., -99., ... -99., -99., -99., -99., -99., -99., -99., -99., -99.]) >>> rmg.set_nodata_nodes_to_fixed_gradient(z, -99) >>> rmg.status_at_node # doctest: +NORMALIZE_WHITESPACE array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int8) >>> rmg.status_at_link # doctest: +NORMALIZE_WHITESPACE array([4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 4, 4, 4, 2, 0, 0, 0, 0, 2, 4, 4, 4, 0, 0, 0, 0, 0, 4, 4, 4, 2, 0, 0, 0, 0, 2, 4, 4, 4, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4]) LLCATS: BC NINF """ # Find locations where value equals the NODATA code and set these nodes # as inactive boundaries. nodata_locations = numpy.nonzero(node_data == nodata_value) self._node_status[nodata_locations] = FIXED_GRADIENT_BOUNDARY # Recreate the list of active cell IDs self._update_links_nodes_cells_to_new_BCs() @deprecated(use='map_max_of_link_nodes_to_link', version=1.0) def max_of_link_end_node_values(self, node_data): """Maximum value at the end of links. For each active link, finds and returns the maximum value of node_data at either of the two ends. Use this, for example, if you want to find the maximum value of water depth at linked pairs of nodes (by passing in an array of water depth values at nodes). Parameters ---------- node_data : ndarray Values at grid nodes. Returns ------- ndarray : Maximum values whose length is the number of active links. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4), spacing=(1., 1.)) >>> h = np.array([ 2., 2., 8., 0., ... 8., 0., 3., 0., ... 5., 6., 8., 3.]) >>> grid.max_of_link_end_node_values(h) array([ 2., 8., 8., 3., 3., 6., 8.]) Note that this method is *deprecatd*. The alternative is to use ``map_max_of_link_nodes_to_link``. >>> vals = grid.map_max_of_link_nodes_to_link(h) >>> vals[grid.active_links] array([ 2., 8., 8., 3., 3., 6., 8.]) LLCATS: DEPR LINF NINF CONN """ return numpy.maximum(node_data[self._activelink_fromnode], node_data[self._activelink_tonode]) def _calc_numbers_of_node_neighbors(self): """Number of neighbor nodes. Calculates the number of neighboring nodes for each node, and returns the result as a 1D numpy array. Used to find the maximum number of neighbors, so that inlink and outlink matrices can be dimensioned accordingly. Assumes that self.number_of_nodes, self.node_at_link_tail, and self.node_at_link_head have already been set up. Algorithm works by simply looping through all links; for each, the endpoints are neighbors of one another, so we increment the number of neighbors for both the endpoint nodes. """ num_nbrs = numpy.zeros(self.number_of_nodes, dtype=int) for link in range(self.number_of_links): num_nbrs[self.node_at_link_tail[link]] += 1 num_nbrs[self.node_at_link_head[link]] += 1 return num_nbrs def _create_active_faces(self): self._active_faces = self.face_at_link[self.active_links] return self._active_faces @deprecated(use='no replacement', version=1.0) def _setup_inlink_and_outlink_matrices(self): """Create data structured for number of inlinks and outlinks. Creates data structures to record the numbers of inlinks and outlinks for each node. An inlink of a node is simply a link that has the node as its "to" node, and an outlink is a link that has the node as its "from". We store the inlinks in an NM-row by num_nodes-column matrix called _node_inlink_matrix. NM is the maximum number of neighbors for any node. We also keep track of the total number of inlinks and outlinks at each node in the num_inlinks and num_outlinks arrays. The inlink and outlink matrices are useful in numerical calculations. Each row of each matrix contains one inlink or outlink per node. So, if you have a corresponding "flux" matrix, you can map incoming or outgoing fluxes onto the appropriate nodes. More information on this is in the various calculate_flux_divergence... functions. What happens if a given node does not have two inlinks or outlinks? We simply put the default value -1 in this case. This allows us to use a cute little trick when computing inflows and outflows. We make our "flux" array one element longer than the number of links, with the last element containing the value 0. Thus, any time we add an influx from link number -1, Python takes the value of the last element in the array, which is zero. By doing it this way, we maintain the efficiency that comes with the use of numpy. Again, more info can be found in the description of the flux divergence functions. """ # Find the maximum number of neighbors for any node num_nbrs = self._calc_numbers_of_node_neighbors() self.max_num_nbrs = numpy.amax(num_nbrs) # Create active in-link and out-link matrices. self._node_inlink_matrix = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) self._node_outlink_matrix = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) # Set up the inlink arrays tonodes = self.node_at_link_head self._node_numinlink = numpy.bincount(tonodes, minlength=self.number_of_nodes) counts = count_repeated_values(self.node_at_link_head) for (count, (tonodes, link_ids)) in enumerate(counts): self._node_inlink_matrix[count][tonodes] = link_ids # Set up the outlink arrays fromnodes = self.node_at_link_tail self._node_numoutlink = numpy.bincount(fromnodes, minlength=self.number_of_nodes) counts = count_repeated_values(self.node_at_link_tail) for (count, (fromnodes, link_ids)) in enumerate(counts): self._node_outlink_matrix[count][fromnodes] = link_ids @deprecated(use='no replacement', version=1.0) def _setup_active_inlink_and_outlink_matrices(self): """Create data structures for number of active inlinks and outlinks. Creates data structures to record the numbers of active inlinks and active outlinks for each node. These data structures are equivalent to the "regular" inlink and outlink matrices, except that it uses the IDs of active links (only). Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 2) >>> hg._node_numactiveinlink array([0, 0, 0, 3, 1, 1, 1]) >>> hg._node_active_inlink_matrix2 array([[-1, -1, -1, 2, 6, 8, 9], [-1, -1, -1, 3, -1, -1, -1], [-1, -1, -1, 5, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]]) >>> hg._node_numactiveoutlink array([1, 1, 1, 3, 0, 0, 0]) >>> hg._node_active_outlink_matrix2 array([[ 2, 3, 5, 6, -1, -1, -1], [-1, -1, -1, 8, -1, -1, -1], [-1, -1, -1, 9, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]]) """ # Create active in-link and out-link matrices. self._node_active_inlink_matrix = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) self._node_active_outlink_matrix = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) # Set up the inlink arrays tonodes = self._activelink_tonode self._node_numactiveinlink = as_id_array(numpy.bincount( tonodes, minlength=self.number_of_nodes)) counts = count_repeated_values(self._activelink_tonode) for (count, (tonodes, active_link_ids)) in enumerate(counts): self._node_active_inlink_matrix[count][tonodes] = active_link_ids # Set up the outlink arrays fromnodes = self._activelink_fromnode self._node_numactiveoutlink = as_id_array(numpy.bincount( fromnodes, minlength=self.number_of_nodes)) counts = count_repeated_values(self._activelink_fromnode) for (count, (fromnodes, active_link_ids)) in enumerate(counts): self._node_active_outlink_matrix[count][fromnodes] = active_link_ids # THE FOLLOWING IS MEANT TO REPLACE THE ABOVE CODE, USING LINK IDS # FOR ACTIVE LINKS (ONLY), INSTEAD OF "ACTIVE LINK IDS". THE POINT IS # TO HAVE JUST ONE ID/NUMBERING SYSTEM FOR LINKS, RATHER THAN A # SEPARATE NUMBERING SYSTEM FOR ACTIVE LINKS # GT JUNE 2015 # TODO: CLEAN THIS UP # Create AN ALTERNATIVE VERSION OF active in-link and out-link # matrices, WHICH WILL EVENTUALLY REPLACE THE ONE ABOVE (AND BE # RENAMED TO GET RID OF THE "2") # TODO: MAKE THIS CHANGE ONCE CODE THAT USES IT HAS BEEN PREPPED self._node_active_inlink_matrix2 = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) self._node_active_outlink_matrix2 = - numpy.ones( (self.max_num_nbrs, self.number_of_nodes), dtype=numpy.int) # Set up the inlink arrays tonodes = self.node_at_link_head[self.active_links] self._node_numactiveinlink = as_id_array(numpy.bincount( tonodes, minlength=self.number_of_nodes)) # OK, HERE WE HAVE TO MAKE A CHANGE, BECAUSE THE INDICES RETURNED BY # count_repeated_values ARE "ACTIVE LINK INDICES", WHICH WE ARE NO # LONGER USING. HAVE TO TURN THESE BACK INTO LINK IDS. I THINK WE CAN # DO THIS BY CHANGING active_link_ids TO # self.active_links[active_link_ids] BUT HAVEN'T MADE THIS CHANGE YET. # NEED TO WORK THROUGH EXAMPLE 3,2 HMG counts = count_repeated_values( self.node_at_link_head[self.active_links]) for (count, (tonodes, active_link_ids)) in enumerate(counts): self._node_active_inlink_matrix2[count][ tonodes] = self.active_links[active_link_ids] # Set up the outlink arrays fromnodes = self.node_at_link_tail[self.active_links] self._node_numactiveoutlink = as_id_array(numpy.bincount( fromnodes, minlength=self.number_of_nodes)) counts = count_repeated_values(self._activelink_fromnode) for (count, (fromnodes, active_link_ids)) in enumerate(counts): self._node_active_outlink_matrix2[count][ fromnodes] = self.active_links[active_link_ids] def _create_link_unit_vectors(self): """Make arrays to store the unit vectors associated with each link. Creates self.link_unit_vec_x and self.link_unit_vec_y. These contain, for each link, the x and y components of the link's unit vector (that is, the link's x and y dimensions if it were shrunk to unit length but retained its orientation). The length of these arrays is the number of links plus one. The last entry in each array is set to zero, and is used to handle references to "link -1" (meaning, a non-existent link, whose unit vector is (0,0)). Also builds arrays to store the unit-vector component sums for each node: node_unit_vector_sum_x and node_unit_vector_sum_y. These are designed to be used when mapping link vector values to nodes (one takes the average of the x- and y-components of all connected links). Notes ----- Creates the following: * ``self.link_unit_vec_x``, ``self.link_unit_vec_y`` : ndarray x and y components of unit vectors at each link (extra 0 entries @ end) * ``self.node_vector_sum_x``, ``self.node_vector_sum_y`` : ndarray Sums of x & y unit vector components for each node. Sum is over all links connected to a given node. Examples -------- The example below is a seven-node hexagonal grid, with six nodes around the perimeter and one node (#3) in the interior. There are four horizontal links with unit vector (1,0), and 8 diagonal links with unit vector (+/-0.5, +/-sqrt(3)/2) (note: sqrt(3)/2 ~ 0.866). .. note:: This example assumes that the triangulation places links in a certain order. Because the order is arbitrary, this might break on different platforms. If that happens, the example needs to be made generic somehow ... >>> import landlab as ll >>> hmg = ll.HexModelGrid(3, 2, 2.0) >>> hmg.link_unit_vec_x # doctest: +NORMALIZE_WHITESPACE array([ 1. , -0.5, 0.5, -0.5, 0.5, 1. , 1. , 0.5, -0.5, 0.5, -0.5, 1. , 0. ]) >>> hmg.link_unit_vec_y array([ 0. , 0.8660254, 0.8660254, 0.8660254, 0.8660254, 0. , 0. , 0.8660254, 0.8660254, 0.8660254, 0.8660254, 0. , 0. ]) >>> hmg.node_unit_vector_sum_x array([ 2., 2., 2., 4., 2., 2., 2.]) >>> hmg.node_unit_vector_sum_y array([ 1.73205081, 1.73205081, 1.73205081, 3.46410162, 1.73205081, 1.73205081, 1.73205081]) """ nodes_at_link = ((self.node_at_link_tail, self.node_at_link_head), ) unit_vec_at_link = np.zeros((self.number_of_links + 1, 2), dtype=float) unit_vec_at_link[:-1, 0] = np.diff(self.x_of_node[nodes_at_link], axis=0) / self.length_of_link unit_vec_at_link[:-1, 1] = np.diff(self.y_of_node[nodes_at_link], axis=0) / self.length_of_link # unit_vec_at_link[:-1] /= self.length_of_link.reshape((-1, 1)) self._unit_vec_at_node = np.abs(unit_vec_at_link[self.links_at_node]).sum(axis=1) self._node_unit_vector_sum_x = self._unit_vec_at_node[:, 0] self._node_unit_vector_sum_y = self._unit_vec_at_node[:, 1] self._link_unit_vec_x = unit_vec_at_link[:, 0] self._link_unit_vec_y = unit_vec_at_link[:, 1] @property def unit_vector_xcomponent_at_link(self): """Get array of x-component of unit vector for links. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> len(grid.unit_vector_xcomponent_at_link) == grid.number_of_links + 1 True >>> grid.unit_vector_xcomponent_at_link # doctest: +NORMALIZE_WHITESPACE array([ 1., 1., 0., 0., 0., 1., 1., 0., 0., 0., 1., 1., 0.]) LLCATS: LINF MEAS """ if self._link_unit_vec_x is None: self._create_link_unit_vectors() return self._link_unit_vec_x @property @deprecated(use='unit_vector_xcomponent_at_link', version='0.5') def link_unit_vec_x(self): """ LLCATS: DEPR LINF MEAS """ return self.unit_vector_xcomponent_at_link @property def unit_vector_ycomponent_at_link(self): """Get array of y-component of unit vector for links. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> len(grid.unit_vector_ycomponent_at_link) == grid.number_of_links + 1 True >>> grid.unit_vector_ycomponent_at_link # doctest: +NORMALIZE_WHITESPACE array([ 0., 0., 1., 1., 1., 0., 0., 1., 1., 1., 0., 0., 0.]) LLCATS: LINF MEAS """ if self._link_unit_vec_y is None: self._create_link_unit_vectors() return self._link_unit_vec_y @property @deprecated(use='unit_vector_xcomponent_at_link', version='0.5') def link_unit_vec_y(self): """ LLCATS: DEPR LINF MEAS """ return self.unit_vector_ycomponent_at_link @property def unit_vector_sum_xcomponent_at_node(self): """Get array of x-component of unit vector sums at each node. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> len(grid.unit_vector_sum_xcomponent_at_node) == grid.number_of_nodes True >>> grid.unit_vector_sum_xcomponent_at_node array([ 1., 2., 1., 1., 2., 1., 1., 2., 1.]) LLCATS: NINF MEAS """ if self._node_unit_vector_sum_x is None: self._create_link_unit_vectors() return self._node_unit_vector_sum_x @property @deprecated(use='unit_vector_sum_xcomponent_at_node', version='0.5') def node_unit_vector_sum_x(self): """ LLCATS: DEPR NINF MEAS """ return self.unit_vector_sum_xcomponent_at_node @property def unit_vector_sum_ycomponent_at_node(self): """Get array of y-component of unit vector sums at each node. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 3)) >>> len(grid.unit_vector_sum_ycomponent_at_node) == grid.number_of_nodes True >>> grid.unit_vector_sum_ycomponent_at_node array([ 1., 1., 1., 2., 2., 2., 1., 1., 1.]) LLCATS: NINF MEAS """ if self._node_unit_vector_sum_y is None: self._create_link_unit_vectors() return self._node_unit_vector_sum_y @property @deprecated(use='unit_vector_sum_ycomponent_at_node', version='0.5') def node_unit_vector_sum_y(self): """ LLCATS: DEPR NINF MEAS """ return self.unit_vector_sum_ycomponent_at_node def map_link_vector_to_nodes(self, q): r"""Map data defined on links to nodes. Given a variable defined on links, breaks it into x and y components and assigns values to nodes by averaging each node's attached links. Parameters ---------- q : ndarray of floats (1D, length = number of links in grid) Variable defined on links Returns ------- ndarray, ndarray x and y components of variable mapped to nodes (1D, length = number of nodes) See Also -------- _create_link_unit_vectors : sets up unit vectors at links and unit-vector sums at nodes Notes ----- THIS ALGORITHM IS NOT CORRECT AND NEEDS TO BE CHANGED! The concept here is that q contains a vector variable that is defined at each link. The magnitude is given by the value of q, and the direction is given by the orientation of the link, as described by its unit vector. To map the link-vector values to the nodes, we break the values into x- and y-components according to each link's unit vector. The x-component of q at a node is a weighted sum of the x-components of the links that are attached to that node. A good way to appreciate this is by example. Consider a 3x4 raster grid:: 8--14---9--15--10--16--11 | | | | 4 5 6 7 | | | | 4--11---5---12--6---13--7 | | | | 0 1 2 3 | | | | 0---8---1---9---2--10---3 Imagine that for each node, we were to add up the unit vector components for each connected link; in other words, add up all the x components of the unit vectors associated with each link, and add up all the y components. Here's what that would look like for the above grid ("vsx" and "vsy" stand for "vector sum x" and "vector sum y"): * Corner nodes (0, 3, 8, 11): vsx = 1, vsy = 1 * Bottom and top nodes (1-2, 9-10): vsx = 2, vsy = 1 * Left and right nodes (4, 7): vsx = 1, vsy = 2 * All others: vsx = 2, vsy = 2 The process of creating unit-vector sums at nodes is handled by ModelGrid._create_link_unit_vectors() (and, for raster grids, by the overriding method RasterModelGrid._create_link_unit_vectors()). The node unit-vector sums are then stored in self.node_unit_vector_sum_x and self.node_unit_vector_sum_y. How would you use this? Suppose you have a vector variable q defined at links. What's the average at the nodes? We'll define the average as follows. The terminology here is: :math:`q = (u,v)` represents the vector quantity defined at links, :math:`Q = (U,V)` represents its definition at nodes, :math:`(m,n)` represents the unit vector components at a link, and :math:`(S_x,S_y)` represents the unit-vector sum at a given node. .. math:: U_i = \sum_{j=1}^{L_i} q_j m_j / S_{xi} V_i = \sum_{j=1}^{L_i} q_j n_j / S_{yi} Suppose that the vector q is uniform and equal to one. Then, at node 0 in the above grid, this works out to:: U_0 = (q_0 m_0) / 1 + (q_8 m_8) / 1 = (1 0)/ 1 + (1 1)/1 = 1 V_0 = (q_0 n_0) / 1 + (q_8 n_8) / 1 = (1 1) / 1 + (1 0) / 1 = 1 At node 1, in the bottom row but not a corner, we add up the values of **q** associated with THREE links. The x-vector sum of these links is 2 because there are two horizontal links, each with an x- unit vector value of unity. The y-vector sum is 1 because only one of the three (link #1) has a non-zero y component (equal to one). Here is how the numbers work out:: U_1 = (q_1 m_1) / 2 + (q_8 m_8) / 2 + (q_9 m_9) / 2 = (1 0) / 2 + (1 1) / 2 + (1 1) / 2 = 1 V_1 = (q_1 n_1) / 1 + (q_8 n_8) / 1 + (q_9 n_9) / 1 = (1 1) / 1 + (1 0) / 1 + (1 0) / 1 = 1 At node 5, in the interior, there are four connected links (two in-links and two out-links; two horizontal and two vertical). So, we add up the q values associated with all four:: U_5 = (q_1 m_1) / 2 + (q_5 m_5) / 2 + (q_11 m_11) / 2 + (q_12 m_12) / 2 = (1 0) / 2 + (1 0) / 2 + (1 1) / 2 + (1 1) / 2 = 1 V_5 = (q_1 n_1) / 2 + (q_5 n_5) / 2 + (q_11 n_11) / 2 + (q_12 n_12) / 2 = (1 1) / 2 + (1 1) / 2 + (1 0) / 2 + (1 0) / 2 = 1 To do this calculation efficiently, we use the following algorithm:: FOR each row in _node_inlink_matrix (representing one inlink @ each node) Multiply the link's q value by its unit x component ... ... divide by node's unit vector sum in x ... ... and add it to the node's total q_x Multiply the link's q value by its unit y component ... ... divide by node's unit vector sum in y ... ... and add it to the node's total q_y Examples -------- **Example 1** q[:] = 1. Vector magnitude is :math:`\sqrt{2}`, direction is :math:`(1,1)`. >>> import numpy as np >>> import landlab as ll >>> rmg = ll.RasterModelGrid((3, 4), spacing=(2., 2.)) >>> rmg.node_unit_vector_sum_x array([ 1., 2., 2., 1., 1., 2., 2., 1., 1., 2., 2., 1.]) >>> rmg.node_unit_vector_sum_y array([ 1., 1., 1., 1., 2., 2., 2., 2., 1., 1., 1., 1.]) >>> q = np.ones(rmg.number_of_links) >>> nvx, nvy = rmg.map_link_vector_to_nodes(q) >>> nvx array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) >>> nvy array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) **Example 2** Vector magnitude is 5, angle is 30 degrees from horizontal, forming a 3-4-5 triangle. >>> q = np.array([4., 4., 4., 3., 3., 3., 3., ... 4., 4., 4., 3., 3., 3., 3., ... 4., 4., 4]) >>> nvx, nvy = rmg.map_link_vector_to_nodes(q) >>> nvx array([ 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4.]) >>> nvy array([ 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.]) ..todo:: Fix and finish example 3 below. Example 3: Hexagonal grid with vector as above. Here, q is pre-calculated to have the right values to represent a uniform vector with magnitude 5 and orientation 30 degrees counter-clockwise from horizontal. LLCATS: NINF LINF CONN MAP """ # Create the arrays to hold the node-based values of the x and y # components of the vector (q) node_vec_x = numpy.zeros(self.number_of_nodes) node_vec_y = numpy.zeros(self.number_of_nodes) # Break the link-based vector input variable, q, into x- and # y-components. # Notes: # 1) We make the arrays 1 element longer than the number of links, # so that references to -1 in the node-link matrices will refer # to the last element of these two arrays, which will contain # zeros. (Same trick as in the flux divergence functions) # 2) This requires memory allocation. Because this function might be # called repeatedly, it would be good to find a way to # pre-allocate to improve speed. qx = numpy.zeros(self.number_of_links + 1) qy = numpy.zeros(self.number_of_links + 1) qx[:self.number_of_links] = q * \ self.link_unit_vec_x[:self.number_of_links] qy[:self.number_of_links] = q * \ self.link_unit_vec_y[:self.number_of_links] # Loop over each row in the _node_inlink_matrix and _node_outlink_matrix. # This isn't a big loop! In a raster grid, these have only two rows # each; in an unstructured grid, it depends on the grid geometry; # for a hex grid, there are up to 6 rows. n_matrix_rows = numpy.size(self._node_inlink_matrix, 0) for i in range(n_matrix_rows): node_vec_x += qx[self._node_inlink_matrix[i, :]] node_vec_x += qx[self._node_outlink_matrix[i, :]] node_vec_y += qy[self._node_inlink_matrix[i, :]] node_vec_y += qy[self._node_outlink_matrix[i, :]] node_vec_x /= self.node_unit_vector_sum_x node_vec_y /= self.node_unit_vector_sum_y return node_vec_x, node_vec_y @deprecated(use='plot.imshow_grid', version=1.0) def display_grid(self, draw_voronoi=False): """Display the grid. LLCATS: DEPR GINF """ import matplotlib.pyplot as plt # Plot nodes, colored by boundary vs interior plt.plot(self.node_x[self.core_nodes], self.node_y[self.core_nodes], 'go') plt.plot(self.node_x[self.boundary_nodes], self.node_y[self.boundary_nodes], 'ro') # Draw links for i in range(self.number_of_links): plt.plot([self.node_x[self.node_at_link_tail[i]], self.node_x[self.node_at_link_head[i]]], [self.node_y[self.node_at_link_tail[i]], self.node_y[self.node_at_link_head[i]]], 'k-') # Draw active links for link in self._active_links: plt.plot([self.node_x[self.node_at_link_tail[link]], self.node_x[self.node_at_link_head[link]]], [self.node_y[self.node_at_link_tail[link]], self.node_y[self.node_at_link_head[link]]], 'g-') # If caller asked for a voronoi diagram, draw that too if draw_voronoi: from scipy.spatial import Voronoi, voronoi_plot_2d pts = numpy.zeros((self.number_of_nodes, 2)) pts[:, 0] = self.node_x pts[:, 1] = self.node_y vor = Voronoi(pts) voronoi_plot_2d(vor) plt.show() @deprecated(use='node_is_boundary', version=1.0) def is_boundary(self, ids, boundary_flag=None): """ LLCATS: DEPR NINF BC """ return self.node_is_boundary(ids, boundary_flag=boundary_flag) def node_is_boundary(self, ids, boundary_flag=None): """Check if nodes are boundary nodes. Check if nodes at given *ids* are boundary nodes. Use the *boundary_flag* to specify a particular boundary type status flag. Parameters ---------- ids : ndarray Node IDs to check. boundary_flag : int, optional A boundary type to check for. Returns ------- ndarray Array of booleans indicating if nodes are boundary nodes. Examples -------- >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY >>> mg = RasterModelGrid((4, 5)) >>> mg.node_is_boundary([0, 6]) array([ True, False], dtype=bool) >>> mg.node_is_boundary([0, 6], boundary_flag=CLOSED_BOUNDARY) array([False, False], dtype=bool) LLCATS: NINF BC """ if boundary_flag is None: return ~ (self._node_status[ids] == CORE_NODE) else: return self._node_status[ids] == boundary_flag def _assign_boundary_nodes_to_grid_sides(self): """Assign boundary nodes to a quadrant. For each boundary node, determines whether it belongs to the left, right, top or bottom of the grid, based on its distance from the grid's centerpoint (mean (x,y) position). Returns lists of nodes on each of the four grid sides. Assumes self.status_at_node, self.number_of_nodes, self.boundary_nodes, self._node_x, and self._node_y have been initialized. Returns ------- tuple of array_like Tuple of nodes in each coordinate. Nodes are grouped as (*east*, *north*, *west*, *south*). Examples -------- >>> import landlab as ll >>> m = ll.HexModelGrid(5, 3, 1.0) >>> [r,t,l,b] = m._assign_boundary_nodes_to_grid_sides() >>> l array([ 7, 12, 3]) >>> r array([11, 15, 6]) >>> t array([16, 18, 17]) >>> b array([0, 2, 1]) """ # Calculate x and y distance from centerpoint diff_x = self.node_x[self.boundary_nodes] - numpy.mean(self.node_x) diff_y = self.node_y[self.boundary_nodes] - numpy.mean(self.node_y) return _sort_points_into_quadrants(diff_x, diff_y, self.boundary_nodes) @deprecated(use='status_at_node', version=1.0) def set_closed_nodes(self, nodes): """Make nodes closed boundaries. Sets the given nodes' boundary condition statuses to CLOSED_BOUNDARY (==4), and resets the list of active links to reflect any changes. LLCATS: DEPR NINF BC """ self._node_status[nodes] = CLOSED_BOUNDARY self._update_links_nodes_cells_to_new_BCs() def calc_distances_of_nodes_to_point(self, coord, get_az=None, node_subset=None, out_distance=None, out_azimuth=None): """Get distances for nodes to a given point. Returns an array of distances for each node to a provided point. If "get_az" is set to 'angles', returns both the distance array and an array of azimuths from up/north. If it is set to 'displacements', it returns the azimuths as a 2xnnodes array of x and y displacements. If it is not set, returns just the distance array. If "node_subset" is set as an ID, or list/array/etc of IDs method returns just the distance (and optionally azimuth) for that node. Point is provided as a tuple (x,y). If out_distance (& out_azimuth) are provided, these arrays are used to store the outputs. This is recommended for memory management reasons if you are working with node subsets. .. note:: Angles are returned in radians but measured clockwise from north. Parameters ---------- coord : tuple of float Coodinates of point as (x, y). get_az: {None, 'angles', 'displacements'}, optional Optionally calculate azimuths as either angles or displacements. The calculated values will be returned along with the distances as the second item of a tuple. node_subset : array_like, optional Calculate distances on a subset of grid nodes. The default is to calculate distances from the provided points to all nodes. out_distance : array_like, optional If provided, put the calculated distances here. Otherwise, create a new array. out_azimuth : array_like, optional If provided, put the calculated distances here. Otherwise, create a new array. Returns ------- ndarray or tuple of ndarray If *get_az* is ``None`` return the array of distances. Otherwise, return a tuple of distances and azimuths. Notes ----- Once you start working with node subsets in Landlab, which can change size between loops, it's quite possible for Python's internal memory management to crap out after large numbers of loops (~>10k). This is to do with the way it block allocates memory for arrays of differing lengths, then cannot free this memory effectively. The solution - as implemented here - is to pre-allocate all arrays as nnodes long, then only work with the first [len_subset] entries by slicing (in a pseudo-C-style). Care has to be taken not to "accidentally" allow Python to allocate a new array you don't have control over. Then, to maintain efficient memory allocation, we create some "dummy" nnode-long arrays to store intermediate parts of the solution in. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((4, 5)) Calculate distances from point at (2., 1.) to a subset of nodes on the grid. >>> grid.calc_distances_of_nodes_to_point((2, 1), ... node_subset=(2, 6, 7, 8, 12)) array([ 1., 1., 0., 1., 1.]) Calculate distances from a point to all nodes on the grid. >>> dist = grid.calc_distances_of_nodes_to_point((2, 1)) >>> dist.shape == (grid.number_of_nodes, ) True >>> dist.take((2, 6, 7, 8, 12)) array([ 1., 1., 0., 1., 1.]) Put the distances into a buffer. >>> out = np.empty(grid.number_of_nodes, dtype=float) >>> dist = grid.calc_distances_of_nodes_to_point((2, 1), ... out_distance=out) >>> out is dist True >>> out.take((2, 6, 7, 8, 12)) array([ 1., 1., 0., 1., 1.]) Calculate azimuths along with distances. The azimuths are calculated in radians but measured clockwise from north. >>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1), ... get_az='angles') >>> azim.take((2, 6, 7, 8, 12)) * 180. / np.pi array([ 180., 270., 0., 90., 0.]) >>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1), ... get_az='angles', node_subset=(1, 3, 11, 13)) >>> azim * 180. / np.pi array([ 225., 135., 315., 45.]) When calculating displacements, the first row contains displacements in x and the second displacements in y. >>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1), ... get_az='displacements', node_subset=(2, 6, 7, 8, 12)) >>> azim array([[ 0., -1., 0., 1., 0.], [-1., 0., 0., 0., 1.]]) LLCATS: NINF MEAS """ if len(coord) != 2: raise ValueError('coordinate must iterable of length 2') if get_az not in (None, 'displacements', 'angles'): raise ValueError('get_az not understood') if node_subset is not None and numpy.any(numpy.isnan(node_subset)): node_subset = None if node_subset is not None: if not isinstance(node_subset, numpy.ndarray): node_subset = numpy.array(node_subset) node_subset = node_subset.reshape((-1, )) len_subset = node_subset.size else: len_subset = self.number_of_nodes if out_distance is None: out_distance = numpy.empty(len_subset, dtype=numpy.float) if out_distance.size != len_subset: raise ValueError('output array size mismatch for distances') if get_az is not None: if get_az == 'displacements': az_shape = (2, len_subset) else: az_shape = (len_subset, ) if out_azimuth is None: out_azimuth = numpy.empty(az_shape, dtype=numpy.float) if out_azimuth.shape != az_shape: raise ValueError('output array mismatch for azimuths') azimuths_as_displacements = numpy.empty((2, self.number_of_nodes)) dummy_nodes_1 = numpy.empty(self.number_of_nodes) dummy_nodes_2 = numpy.empty(self.number_of_nodes) dummy_nodes_3 = numpy.empty(self.number_of_nodes) if node_subset is None: azimuths_as_displacements[0] = (self.node_x - coord[0]) azimuths_as_displacements[1] = (self.node_y - coord[1]) else: azimuths_as_displacements[0, :len_subset] = ( self.node_x[node_subset] - coord[0]) azimuths_as_displacements[1, :len_subset] = ( self.node_y[node_subset] - coord[1]) numpy.square(azimuths_as_displacements[0, :len_subset], out=dummy_nodes_1[:len_subset]) numpy.square(azimuths_as_displacements[1, :len_subset], out=dummy_nodes_2[:len_subset]) numpy.add(dummy_nodes_1[:len_subset], dummy_nodes_2[:len_subset], out=dummy_nodes_3[:len_subset]) numpy.sqrt(dummy_nodes_3[:len_subset], out=out_distance) if get_az: if get_az == 'displacements': out_azimuth[:] = azimuths_as_displacements[:, :len_subset] elif get_az == 'angles': numpy.arctan2( azimuths_as_displacements[0, :len_subset], azimuths_as_displacements[1, :len_subset], out=out_azimuth[:len_subset]) less_than_zero = numpy.empty(self.number_of_nodes, dtype=bool) numpy.less(out_azimuth, 0., out=less_than_zero[:len_subset]) out_azimuth[less_than_zero[:len_subset]] += 2. * numpy.pi return out_distance, out_azimuth else: return out_distance @property def all_node_distances_map(self): """Get distances from every node to every other node. Examples -------- >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> distances = grid.all_node_distances_map The shape of the array is ``number_of_nodes`` by ``number_of_nodes`` and distance from a node to itself is zero. >>> distances.shape == (grid.number_of_nodes, grid.number_of_nodes) True >>> distances.diagonal() array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) The distances from the first node to all nodes in its row and all the nodes in its column. >>> distances[0, :4] array([ 0., 1., 2., 3.]) >>> distances[0, ::4] array([ 0., 1., 2.]) LLCATS: NINF MEAS """ if self._all_node_distances_map is None: self._create_all_node_distances_azimuths_maps() return self._all_node_distances_map @property def all_node_azimuths_map(self): """Get azimuths from every node to every other node. Examples -------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> grid = RasterModelGrid((3, 4)) >>> angles = grid.all_node_azimuths_map The shape of the array is ``number_of_nodes`` by ``number_of_nodes`` and azimuth from a node to itself is zero. >>> angles.shape == (grid.number_of_nodes, grid.number_of_nodes) True >>> angles.diagonal() array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) Angles are measured in radians and increase clockwise starting at north. >>> angles *= 180. / np.pi >>> angles[0, :4] array([ 0., 90., 90., 90.]) >>> angles[0, ::4] array([ 0., 0., 0.]) >>> angles[0, ::5] array([ 0., 45., 45.]) LLCATS: NINF MEAS """ if self._all_node_azimuths_map is None: self._create_all_node_distances_azimuths_maps() return self._all_node_azimuths_map def _create_all_node_distances_azimuths_maps(self): """Build distance-azimuth maps. This function creates and stores in the grid field two ``nnodes`` by ``nnodes`` arrays that map the distances and azimuths of all nodes in the grid to all nodes in the grid. This is useful if your module needs to make repeated lookups of distances between the same nodes, but does potentially use up a lot of memory so should be used with caution. The map is symmetrical, so it does not matter whether rows are "from" or "to". The arrays are called: - ``self.all_node_distances_map`` - ``self.all_node_azimuths_map`` Returns ------- tuple of ndarrays Tuple of (distances, azimuths) """ self._all_node_distances_map = numpy.empty((self.number_of_nodes, self.number_of_nodes)) self._all_node_azimuths_map = numpy.empty((self.number_of_nodes, self.number_of_nodes)) node_coords = numpy.empty((self.number_of_nodes, 2)) node_coords[:, 0] = self.node_x node_coords[:, 1] = self.node_y for i in range(self.number_of_nodes): (self._all_node_distances_map[i, :], self._all_node_azimuths_map[i, :]) = ( self.calc_distances_of_nodes_to_point( (node_coords[i, 0], node_coords[i, 1]), get_az='angles')) assert numpy.all(self._all_node_distances_map >= 0.) return self._all_node_distances_map, self._all_node_azimuths_map def _sort_links_by_midpoint(self): """Sort links in order first by midpoint x coordinate, then y. Examples -------- >>> from landlab import HexModelGrid >>> hg = HexModelGrid(3, 3) >>> hg._sort_links_by_midpoint() """ pts = np.zeros((self.number_of_links, 2)) pts[:, 0] = (self.node_x[self.node_at_link_tail] + self.node_x[self.node_at_link_head]) / 2 pts[:, 1] = (self.node_y[self.node_at_link_tail] + self.node_y[self.node_at_link_head]) / 2 indices = argsort_points_by_x_then_y(pts) self.node_at_link_tail[:] = self.node_at_link_tail[indices] self.node_at_link_head[:] = self.node_at_link_head[indices] def move_origin(self, origin): """Changes the x, y values of all nodes. Initially a grid will have an origin of 0,0, and all x,y values will be relative to 0,0. This will add origin[0] to all x values and origin[1] to all y values. Note this is most likely useful when importing a DEM that has an absolute location, however it can be used generally. Parameters ---------- origin : list of two float values, can be negative. [x,y], where x is the value to add to all x values and y is the value to add to all y values Examples -------- >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((4, 3), 1.0) # rows, columns, spacing >>> rmg.node_x array([ 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.]) >>> rmg.node_y array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 3., 3., 3.]) >>> rmg.move_origin((5,1.5)) >>> rmg.node_x array([ 5., 6., 7., 5., 6., 7., 5., 6., 7., 5., 6., 7.]) >>> rmg.node_y array([ 1.5, 1.5, 1.5, 2.5, 2.5, 2.5, 3.5, 3.5, 3.5, 4.5, 4.5, 4.5]) LLCATS: GINF MEAS """ self._node_x += origin[0] self._node_y += origin[1] add_module_functions_to_class(ModelGrid, 'mappers.py', pattern='map_*') # add_module_functions_to_class(ModelGrid, 'gradients.py', # pattern='calculate_*') add_module_functions_to_class(ModelGrid, 'gradients.py', pattern='calc_*') add_module_functions_to_class(ModelGrid, 'divergence.py', pattern='calc_*') if __name__ == '__main__': import doctest doctest.testmod()
#!/usr/bin/python # Copyright (c) 2005-2008, Alexander Belchenko # All rights reserved. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided # that the following conditions are met: # # * Redistributions of source code must retain # the above copyright notice, this list of conditions # and the following disclaimer. # * Redistributions in binary form must reproduce # the above copyright notice, this list of conditions # and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the author nor the names # of its contributors may be used to endorse # or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Test suite for IntelHex class.""" import array from cStringIO import StringIO import os import sys import tempfile import unittest import intelhex from intelhex import IntelHex, \ IntelHexError, \ HexReaderError, \ AddressOverlapError, \ HexRecordError, \ RecordLengthError, \ RecordTypeError, \ RecordChecksumError, \ EOFRecordError, \ ExtendedSegmentAddressRecordError, \ ExtendedLinearAddressRecordError, \ StartSegmentAddressRecordError, \ StartLinearAddressRecordError, \ DuplicateStartAddressRecordError, \ InvalidStartAddressValueError, \ _EndOfFile, \ BadAccess16bit, \ hex2bin ## # Data for tests hex8 = '''\ :1004E300CFF0FBE2FDF220FF20F2E120E2FBE6F396 :1004F3000A00FDE0E1E2E3B4E4E5BAE6E7B3BFE80E :10050300E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8E0 :10051300F9FCFEFF00C0C1C2C3A5C4C5AAC6C7B2C9 :10052300AFC8C9CACBCCCDCECFD0D1D2D3D4D5D6F8 :07053300D7D8D9DCDEDF00A0 :10053A0078227C007D007BFF7A0479F57E007F2398 :10054A0012042F78457C007D007BFF7A0579187E9E :10055A00007F2212042F759850438920758DDDD2B1 :10056A008ED2996390017BFF7A0479E31200658049 :01057A00FE82 :030000000205A254 :0C05A200787FE4F6D8FD75817A02053AF6 :10035F00E709F608DFFA8046E709F208DFFA803E80 :10036F0088828C83E709F0A3DFFA8032E309F6086D :10037F00DFFA8078E309F208DFFA807088828C83D5 :10038F00E309F0A3DFFA806489828A83E0A3F60889 :10039F00DFFA805889828A83E0A3F208DFFA804C63 :1003AF0080D280FA80C680D4806980F2803380103A :1003BF0080A680EA809A80A880DA80E280CA8033A3 :1003CF0089828A83ECFAE493A3C8C582C8CCC5831B :1003DF00CCF0A3C8C582C8CCC583CCDFE9DEE780EB :1003EF000D89828A83E493A3F608DFF9ECFAA9F06A :1003FF00EDFB2289828A83ECFAE0A3C8C582C8CCC0 :10040F00C583CCF0A3C8C582C8CCC583CCDFEADED8 :10041F00E880DB89828A83E493A3F208DFF980CC3A :10042F0088F0EF60010E4E60C388F0ED2402B40433 :10043F000050B9F582EB2402B4040050AF232345DA :06044F0082239003AF734D :10000300E576246AF8E60576227867300702786A8F :10001300E475F0011204AD0204552000EB7F2ED2EB :10002300008018EF540F2490D43440D4FF30040BD5 :10003300EF24BFB41A0050032461FFE57760021573 :1000430077057AE57A7002057930070D7867E475EC :10005300F0011204ADEF02049B02057B7403D20787 :100063008003E4C207F5768B678A688969E4F577CC :10007300F579F57AE57760077F2012003E80F57504 :1000830078FFC201C200C202C203C205C206C2088F :1000930012000CFF700D3007057F0012004FAF7A7E :1000A300AE7922B4255FC2D5C20412000CFF24D05E :1000B300B40A00501A75F00A787730D50508B6FFF0 :1000C3000106C6A426F620D5047002D20380D924E3 :1000D300CFB41A00EF5004C2E5D20402024FD2019A :1000E30080C6D20080C0D20280BCD2D580BAD205ED :1000F30080B47F2012003E2002077401B5770040D0 :10010300F1120003FF12003E020077D208D20680EC :1001130095120003FB120003FA120003F94A4B7015 :100123000679207A037BFF20022EE577602A7E0082 :100133008E8275830012046E60060EEE657870F091 :10014300C2D5EBC0E0EAC0E0E9C0E0EE120296D00F :10015300E0F9D0E0FAD0E0FB120455FF60AAEBC04F :10016300E0EAC0E0E9C0E012003ED0E02401F9D0AB :10017300E03400FAD0E0FBE5780460DCD578D98080 :10018300877BFF7A027992D202809C791080027970 :1001930008C206C2088008D2D5790A8004790AC247 :1001A300D5E578047002F578E4FAFDFEFF1200034A :1001B300FC7B08200113120003FD7B1030000A12A0 :1001C3000003FE120003FF7B20EC3382D592D5504F :1001D30013C3E43000069FFFE49EFEE42001039D69 :1001E300FDE49CFCE4CBF8C201EC700CCFCECDCC8B :1001F300E824F8F870F38017C3EF33FFEE33FEED16 :1002030033FDEC33FCEB33FB994002FB0FD8E9EBF6 :10021300300105F8D0E0C448B201C0E00AEC4D4E0D :100223004F78207B0070C2EAB5780040BCC0E01272 :100233000298D0F0D0E0200104C4C0E0C4B201C0F1 :10024300F0120027D0F0D5F0EB0200771204BD01C5 :100253001453018E5800E54C00E14201924F019A7C :0F02630044019A4900FA4301A0550184460184E1 :100272004501844703405000E92D00ED2E01102B6B :1002820000F123010E2003292A00A94800000108D9 :100292003F3F3F00790AA2D5200314300509B91067 :1002A200020404B9080104A2D52006025001042068 :1002B20002689202B577005034C0E07F2030031903 :1002C2007F30A20272067205500F1202EFC202C202 :1002D20006C205C2087F30800F300503E9C0E01274 :1002E200003E300503D0E0F9D0E0B577CC300517F9 :1002F2007F30B9100C12003E7F583004077F78809F :1003020003B9080312003E3002057F2D02003E7F32 :10031200202008F87F2B2006F322920280CF286E3D :10032200756C6C2900D2011200033001F8C2017809 :100332007730D50108F60200A92D50434958120022 :10034200032403B405004001E490033B9312002F01 :0D035200743A12002FD20375770402018E59 :10045500BB010689828A83E0225002E722BBFE02A5 :09046500E32289828A83E49322D8 :10046E00BB010CE58229F582E5833AF583E0225043 :10047E0006E92582F8E622BBFE06E92582F8E2228D :0D048E00E58229F582E5833AF583E49322A7 :10049B00BB010689828A83F0225002F722BBFE0140 :0204AB00F3223A :1004AD00FAE6FB0808E6F925F0F618E6CA3AF62250 :1004BD00D083D082F8E4937012740193700DA3A3CE :1004CD0093F8740193F5828883E4737402936860E2 :0604DD00EFA3A3A380DFE2 :10057B00EFB40A07740D120586740A309811A89906 :10058B00B8130CC2983098FDA899C298B811F630E0 :07059B0099FDC299F59922B8 :00000001FF ''' bin8 = array.array('B',[2, 5, 162, 229, 118, 36, 106, 248, 230, 5, 118, 34, 120, 103, 48, 7, 2, 120, 106, 228, 117, 240, 1, 18, 4, 173, 2, 4, 85, 32, 0, 235, 127, 46, 210, 0, 128, 24, 239, 84, 15, 36, 144, 212, 52, 64, 212, 255, 48, 4, 11, 239, 36, 191, 180, 26, 0, 80, 3, 36, 97, 255, 229, 119, 96, 2, 21, 119, 5, 122, 229, 122, 112, 2, 5, 121, 48, 7, 13, 120, 103, 228, 117, 240, 1, 18, 4, 173, 239, 2, 4, 155, 2, 5, 123, 116, 3, 210, 7, 128, 3, 228, 194, 7, 245, 118, 139, 103, 138, 104, 137, 105, 228, 245, 119, 245, 121, 245, 122, 229, 119, 96, 7, 127, 32, 18, 0, 62, 128, 245, 117, 120, 255, 194, 1, 194, 0, 194, 2, 194, 3, 194, 5, 194, 6, 194, 8, 18, 0, 12, 255, 112, 13, 48, 7, 5, 127, 0, 18, 0, 79, 175, 122, 174, 121, 34, 180, 37, 95, 194, 213, 194, 4, 18, 0, 12, 255, 36, 208, 180, 10, 0, 80, 26, 117, 240, 10, 120, 119, 48, 213, 5, 8, 182, 255, 1, 6, 198, 164, 38, 246, 32, 213, 4, 112, 2, 210, 3, 128, 217, 36, 207, 180, 26, 0, 239, 80, 4, 194, 229, 210, 4, 2, 2, 79, 210, 1, 128, 198, 210, 0, 128, 192, 210, 2, 128, 188, 210, 213, 128, 186, 210, 5, 128, 180, 127, 32, 18, 0, 62, 32, 2, 7, 116, 1, 181, 119, 0, 64, 241, 18, 0, 3, 255, 18, 0, 62, 2, 0, 119, 210, 8, 210, 6, 128, 149, 18, 0, 3, 251, 18, 0, 3, 250, 18, 0, 3, 249, 74, 75, 112, 6, 121, 32, 122, 3, 123, 255, 32, 2, 46, 229, 119, 96, 42, 126, 0, 142, 130, 117, 131, 0, 18, 4, 110, 96, 6, 14, 238, 101, 120, 112, 240, 194, 213, 235, 192, 224, 234, 192, 224, 233, 192, 224, 238, 18, 2, 150, 208, 224, 249, 208, 224, 250, 208, 224, 251, 18, 4, 85, 255, 96, 170, 235, 192, 224, 234, 192, 224, 233, 192, 224, 18, 0, 62, 208, 224, 36, 1, 249, 208, 224, 52, 0, 250, 208, 224, 251, 229, 120, 4, 96, 220, 213, 120, 217, 128, 135, 123, 255, 122, 2, 121, 146, 210, 2, 128, 156, 121, 16, 128, 2, 121, 8, 194, 6, 194, 8, 128, 8, 210, 213, 121, 10, 128, 4, 121, 10, 194, 213, 229, 120, 4, 112, 2, 245, 120, 228, 250, 253, 254, 255, 18, 0, 3, 252, 123, 8, 32, 1, 19, 18, 0, 3, 253, 123, 16, 48, 0, 10, 18, 0, 3, 254, 18, 0, 3, 255, 123, 32, 236, 51, 130, 213, 146, 213, 80, 19, 195, 228, 48, 0, 6, 159, 255, 228, 158, 254, 228, 32, 1, 3, 157, 253, 228, 156, 252, 228, 203, 248, 194, 1, 236, 112, 12, 207, 206, 205, 204, 232, 36, 248, 248, 112, 243, 128, 23, 195, 239, 51, 255, 238, 51, 254, 237, 51, 253, 236, 51, 252, 235, 51, 251, 153, 64, 2, 251, 15, 216, 233, 235, 48, 1, 5, 248, 208, 224, 196, 72, 178, 1, 192, 224, 10, 236, 77, 78, 79, 120, 32, 123, 0, 112, 194, 234, 181, 120, 0, 64, 188, 192, 224, 18, 2, 152, 208, 240, 208, 224, 32, 1, 4, 196, 192, 224, 196, 178, 1, 192, 240, 18, 0, 39, 208, 240, 213, 240, 235, 2, 0, 119, 18, 4, 189, 1, 20, 83, 1, 142, 88, 0, 229, 76, 0, 225, 66, 1, 146, 79, 1, 154, 68, 1, 154, 73, 0, 250, 67, 1, 160, 85, 1, 132, 70, 1, 132, 69, 1, 132, 71, 3, 64, 80, 0, 233, 45, 0, 237, 46, 1, 16, 43, 0, 241, 35, 1, 14, 32, 3, 41, 42, 0, 169, 72, 0, 0, 1, 8, 63, 63, 63, 0, 121, 10, 162, 213, 32, 3, 20, 48, 5, 9, 185, 16, 2, 4, 4, 185, 8, 1, 4, 162, 213, 32, 6, 2, 80, 1, 4, 32, 2, 104, 146, 2, 181, 119, 0, 80, 52, 192, 224, 127, 32, 48, 3, 25, 127, 48, 162, 2, 114, 6, 114, 5, 80, 15, 18, 2, 239, 194, 2, 194, 6, 194, 5, 194, 8, 127, 48, 128, 15, 48, 5, 3, 233, 192, 224, 18, 0, 62, 48, 5, 3, 208, 224, 249, 208, 224, 181, 119, 204, 48, 5, 23, 127, 48, 185, 16, 12, 18, 0, 62, 127, 88, 48, 4, 7, 127, 120, 128, 3, 185, 8, 3, 18, 0, 62, 48, 2, 5, 127, 45, 2, 0, 62, 127, 32, 32, 8, 248, 127, 43, 32, 6, 243, 34, 146, 2, 128, 207, 40, 110, 117, 108, 108, 41, 0, 210, 1, 18, 0, 3, 48, 1, 248, 194, 1, 120, 119, 48, 213, 1, 8, 246, 2, 0, 169, 45, 80, 67, 73, 88, 18, 0, 3, 36, 3, 180, 5, 0, 64, 1, 228, 144, 3, 59, 147, 18, 0, 47, 116, 58, 18, 0, 47, 210, 3, 117, 119, 4, 2, 1, 142, 231, 9, 246, 8, 223, 250, 128, 70, 231, 9, 242, 8, 223, 250, 128, 62, 136, 130, 140, 131, 231, 9, 240, 163, 223, 250, 128, 50, 227, 9, 246, 8, 223, 250, 128, 120, 227, 9, 242, 8, 223, 250, 128, 112, 136, 130, 140, 131, 227, 9, 240, 163, 223, 250, 128, 100, 137, 130, 138, 131, 224, 163, 246, 8, 223, 250, 128, 88, 137, 130, 138, 131, 224, 163, 242, 8, 223, 250, 128, 76, 128, 210, 128, 250, 128, 198, 128, 212, 128, 105, 128, 242, 128, 51, 128, 16, 128, 166, 128, 234, 128, 154, 128, 168, 128, 218, 128, 226, 128, 202, 128, 51, 137, 130, 138, 131, 236, 250, 228, 147, 163, 200, 197, 130, 200, 204, 197, 131, 204, 240, 163, 200, 197, 130, 200, 204, 197, 131, 204, 223, 233, 222, 231, 128, 13, 137, 130, 138, 131, 228, 147, 163, 246, 8, 223, 249, 236, 250, 169, 240, 237, 251, 34, 137, 130, 138, 131, 236, 250, 224, 163, 200, 197, 130, 200, 204, 197, 131, 204, 240, 163, 200, 197, 130, 200, 204, 197, 131, 204, 223, 234, 222, 232, 128, 219, 137, 130, 138, 131, 228, 147, 163, 242, 8, 223, 249, 128, 204, 136, 240, 239, 96, 1, 14, 78, 96, 195, 136, 240, 237, 36, 2, 180, 4, 0, 80, 185, 245, 130, 235, 36, 2, 180, 4, 0, 80, 175, 35, 35, 69, 130, 35, 144, 3, 175, 115, 187, 1, 6, 137, 130, 138, 131, 224, 34, 80, 2, 231, 34, 187, 254, 2, 227, 34, 137, 130, 138, 131, 228, 147, 34, 187, 1, 12, 229, 130, 41, 245, 130, 229, 131, 58, 245, 131, 224, 34, 80, 6, 233, 37, 130, 248, 230, 34, 187, 254, 6, 233, 37, 130, 248, 226, 34, 229, 130, 41, 245, 130, 229, 131, 58, 245, 131, 228, 147, 34, 187, 1, 6, 137, 130, 138, 131, 240, 34, 80, 2, 247, 34, 187, 254, 1, 243, 34, 250, 230, 251, 8, 8, 230, 249, 37, 240, 246, 24, 230, 202, 58, 246, 34, 208, 131, 208, 130, 248, 228, 147, 112, 18, 116, 1, 147, 112, 13, 163, 163, 147, 248, 116, 1, 147, 245, 130, 136, 131, 228, 115, 116, 2, 147, 104, 96, 239, 163, 163, 163, 128, 223, 207, 240, 251, 226, 253, 242, 32, 255, 32, 242, 225, 32, 226, 251, 230, 243, 10, 0, 253, 224, 225, 226, 227, 180, 228, 229, 186, 230, 231, 179, 191, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 252, 254, 255, 0, 192, 193, 194, 195, 165, 196, 197, 170, 198, 199, 178, 175, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 220, 222, 223, 0, 120, 34, 124, 0, 125, 0, 123, 255, 122, 4, 121, 245, 126, 0, 127, 35, 18, 4, 47, 120, 69, 124, 0, 125, 0, 123, 255, 122, 5, 121, 24, 126, 0, 127, 34, 18, 4, 47, 117, 152, 80, 67, 137, 32, 117, 141, 221, 210, 142, 210, 153, 99, 144, 1, 123, 255, 122, 4, 121, 227, 18, 0, 101, 128, 254, 239, 180, 10, 7, 116, 13, 18, 5, 134, 116, 10, 48, 152, 17, 168, 153, 184, 19, 12, 194, 152, 48, 152, 253, 168, 153, 194, 152, 184, 17, 246, 48, 153, 253, 194, 153, 245, 153, 34, 120, 127, 228, 246, 216, 253, 117, 129, 122, 2, 5, 58]) hex16 = """:020000040000FA :10000000000083120313072055301820042883169C :10001000031340309900181598168312031318160D :1000200098170800831203138C1E14281A0808005E :0C003000831203130C1E1A28990008000C :00000001FF """ bin16 = array.array('H', [0x0000, 0x1283, 0x1303, 0x2007, 0x3055, 0x2018, 0x2804, 0x1683, 0x1303, 0x3040, 0x0099, 0x1518, 0x1698, 0x1283, 0x1303, 0x1618, 0x1798, 0x0008, 0x1283, 0x1303, 0x1E8C, 0x2814, 0x081A, 0x0008, 0x1283, 0x1303, 0x1E0C, 0x281A, 0x0099, 0x0008, 0x3FFF, 0x3FFF]) hex64k = """:020000040000FA :0100000001FE :020000040001F9 :0100000002FD :00000001FF """ data64k = {0: 1, 0x10000: 2} hex_rectype3 = """:0400000312345678E5 :0100000001FE :00000001FF """ data_rectype3 = {0: 1} start_addr_rectype3 = {'CS': 0x1234, 'IP': 0x5678} hex_rectype5 = """:0400000512345678E3 :0100000002FD :00000001FF """ data_rectype5 = {0: 2} start_addr_rectype5 = {'EIP': 0x12345678} hex_empty_file = ':00000001FF\n' hex_simple = """\ :10000000000083120313072055301820042883169C :10001000031340309900181598168312031318160D :1000200098170800831203138C1E14281A0808005E :0C003000831203130C1E1A28990008000C :00000001FF """ ## # Test cases class TestIntelHexBase(unittest.TestCase): """Base class for all tests. Provide additional functionality for testing. """ def assertRaisesMsg(self, excClass, msg, callableObj, *args, **kwargs): """Just like unittest.TestCase.assertRaises, but checks that the message is right too. Borrowed from Ned Batchelder Blog. See: http://www.nedbatchelder.com/blog/200609.html#e20060905T064418 Typical usage: self.assertRaisesMsg(MyException, "Exception message", my_function, (arg1, arg2)) """ try: callableObj(*args, **kwargs) except excClass, exc: excMsg = str(exc) if not msg: # No message provided: any message is fine. return elif excMsg == msg: # Message provided, and we got the right message: it passes. return else: # Message provided, and it didn't match: fail! raise self.failureException( "Right exception, wrong message: got '%s' expected '%s'" % (excMsg, msg) ) else: if hasattr(excClass, '__name__'): excName = excClass.__name__ else: excName = str(excClass) raise self.failureException( "Expected to raise %s, didn't get an exception at all" % excName ) def assertEqualWrittenData(self, a, b): return self.assertEquals(a, b, """Written data is incorrect Should be: %s Written: %s """ % (a, b)) #/class TestIntelHexBase class TestIntelHex(TestIntelHexBase): def setUp(self): self.f = StringIO(hex8) def tearDown(self): self.f.close() del self.f def test_init_from_file(self): ih = IntelHex(self.f) for addr in xrange(len(bin8)): expected = bin8[addr] actual = ih[addr] self.assertEqual(expected, actual, "Data different at address " "%x (%x != %x)" % (addr, expected, actual)) def test_hex_fromfile(self): ih = IntelHex() ih.fromfile(self.f, format='hex') for addr in xrange(len(bin8)): expected = bin8[addr] actual = ih[addr] self.assertEqual(expected, actual, "Data different at address " "%x (%x != %x)" % (addr, expected, actual)) def test_unicode_filename(self): handle, fname = tempfile.mkstemp(u'') os.close(handle) try: self.assertTrue(isinstance(fname, unicode)) f = file(fname, 'w') try: f.write(hex8) finally: f.close() ih = IntelHex(fname) self.assertEqual(0, ih.minaddr()) self.assertEqual(len(bin8)-1, ih.maxaddr()) finally: os.remove(fname) def test_tobinstr(self): ih = IntelHex(self.f) s1 = ih.tobinstr() s2 = bin8.tostring() self.assertEqual(s2, s1, "data not equal\n%s\n\n%s" % (s1, s2)) def test_tobinfile(self): ih = IntelHex(self.f) sio = StringIO() ih.tobinfile(sio) s1 = sio.getvalue() sio.close() s2 = bin8.tostring() self.assertEqual(s2, s1, "data not equal\n%s\n\n%s" % (s1, s2)) # new API: .tofile universal method sio = StringIO() ih.tofile(sio, format='bin') s1 = sio.getvalue() sio.close() s2 = bin8.tostring() self.assertEqual(s2, s1, "data not equal\n%s\n\n%s" % (s1, s2)) def test_write_empty_hexfile(self): ih = intelhex.IntelHex() sio = StringIO() ih.write_hex_file(sio) s = sio.getvalue() sio.close() self.assertEqualWrittenData(hex_empty_file, s) def test_write_hexfile(self): ih = intelhex.IntelHex(StringIO(hex_simple)) sio = StringIO() ih.write_hex_file(sio) s = sio.getvalue() sio.close() self.assertEqualWrittenData(hex_simple, s) # new API: .tofile universal method sio = StringIO() ih.tofile(sio, format='hex') s = sio.getvalue() sio.close() self.assertEqualWrittenData(hex_simple, s) def test_tofile_wrong_format(self): ih = IntelHex() sio = StringIO() self.assertRaises(ValueError, ih.tofile, sio, {'format': 'bad'}) def test_todict(self): ih = IntelHex() self.assertEquals({}, ih.todict()) ih = IntelHex(StringIO(hex64k)) self.assertEquals(data64k, ih.todict()) ih = IntelHex() ih[1] = 2 ih.start_addr = {'EIP': 1234} self.assertEquals({1: 2, 'start_addr': {'EIP': 1234}}, ih.todict()) def test_fromdict(self): ih = IntelHex() ih.fromdict({1:2, 3:4}) self.assertEquals({1:2, 3:4}, ih.todict()) ih.fromdict({1:5, 6:7}) self.assertEquals({1:5, 3:4, 6:7}, ih.todict()) ih = IntelHex() ih.fromdict({1: 2, 'start_addr': {'EIP': 1234}}) self.assertEquals({1: 2, 'start_addr': {'EIP': 1234}}, ih.todict()) # bad dict self.assertRaises(ValueError, ih.fromdict, {'EIP': 1234}) self.assertRaises(ValueError, ih.fromdict, {-1: 1234}) def test_init_from_obj(self): ih = IntelHex({1:2, 3:4}) self.assertEquals({1:2, 3:4}, ih.todict()) ih.start_addr = {'EIP': 1234} ih2 = IntelHex(ih) ih[1] = 5 ih.start_addr = {'EIP': 5678} self.assertEquals({1:2, 3:4, 'start_addr': {'EIP': 1234}}, ih2.todict()) self.assertNotEqual(id(ih), id(ih2)) def test_dict_interface(self): ih = IntelHex() self.assertEquals(0xFF, ih[0]) # padding byte substitution ih[0] = 1 self.assertEquals(1, ih[0]) del ih[0] self.assertEquals({}, ih.todict()) # padding byte substitution class TestIntelHexLoadBin(TestIntelHexBase): def setUp(self): self.data = '0123456789' self.f = StringIO(self.data) def tearDown(self): self.f.close() def test_loadbin(self): ih = IntelHex() ih.loadbin(self.f) self.assertEqual(0, ih.minaddr()) self.assertEqual(9, ih.maxaddr()) self.assertEqual(self.data, ih.tobinstr()) def test_bin_fromfile(self): ih = IntelHex() ih.fromfile(self.f, format='bin') self.assertEqual(0, ih.minaddr()) self.assertEqual(9, ih.maxaddr()) self.assertEqual(self.data, ih.tobinstr()) def test_loadbin_w_offset(self): ih = IntelHex() ih.loadbin(self.f, offset=100) self.assertEqual(100, ih.minaddr()) self.assertEqual(109, ih.maxaddr()) self.assertEqual(self.data, ih.tobinstr()) def test_loadfile_format_bin(self): ih = IntelHex() ih.loadfile(self.f, format='bin') self.assertEqual(0, ih.minaddr()) self.assertEqual(9, ih.maxaddr()) self.assertEqual(self.data, ih.tobinstr()) class TestIntelHexStartingAddressRecords(TestIntelHexBase): def _test_read(self, hexstr, data, start_addr): sio = StringIO(hexstr) ih = IntelHex(sio) sio.close() # test data self.assertEqual(data, ih._buf, "Internal buffer: %r != %r" % (data, ih._buf)) self.assertEqual(start_addr, ih.start_addr, "Start address: %r != %r" % (start_addr, ih.start_addr)) def test_read_rectype3(self): self._test_read(hex_rectype3, data_rectype3, start_addr_rectype3) def test_read_rectype5(self): self._test_read(hex_rectype5, data_rectype5, start_addr_rectype5) def _test_write(self, hexstr, data, start_addr, write_start_addr=True): # prepare ih = IntelHex(None) ih._buf = data ih.start_addr = start_addr # write sio = StringIO() ih.write_hex_file(sio, write_start_addr) s = sio.getvalue() sio.close() # check self.assertEqualWrittenData(hexstr, s) def _test_dont_write(self, hexstr, data, start_addr): expected = ''.join(hexstr.splitlines(True)[1:]) self._test_write(expected, data, start_addr, False) def test_write_rectype3(self): self._test_write(hex_rectype3, data_rectype3, start_addr_rectype3) def test_dont_write_rectype3(self): self._test_dont_write(hex_rectype3, data_rectype3, start_addr_rectype3) def test_write_rectype5(self): self._test_write(hex_rectype5, data_rectype5, start_addr_rectype5) def test_dont_write_rectype5(self): self._test_dont_write(hex_rectype5, data_rectype5, start_addr_rectype5) def test_write_invalid_start_addr_value(self): ih = IntelHex() ih.start_addr = {'foo': 1} sio = StringIO() self.assertRaises(InvalidStartAddressValueError, ih.write_hex_file, sio) class TestIntelHex_big_files(TestIntelHexBase): """Test that data bigger than 64K read/write correctly""" def setUp(self): self.f = StringIO(hex64k) def tearDown(self): self.f.close() del self.f def test_readfile(self): ih = intelhex.IntelHex(self.f) for addr, byte in data64k.items(): readed = ih[addr] self.assertEquals(byte, readed, "data not equal at addr %X " "(%X != %X)" % (addr, byte, readed)) def test_write_hex_file(self): ih = intelhex.IntelHex(self.f) sio = StringIO() ih.write_hex_file(sio) s = sio.getvalue() sio.close() self.assertEqualWrittenData(hex64k, s) class TestIntelHex16bit(TestIntelHexBase): def setUp(self): self.f = StringIO(hex16) def tearDown(self): self.f.close() del self.f def test_init_from_file(self): ih = intelhex.IntelHex16bit(self.f) def test_init_from_ih(self): ih = intelhex.IntelHex(self.f) ih16 = intelhex.IntelHex16bit(ih) def test_minaddr(self): ih = intelhex.IntelHex16bit(self.f) addr = ih.minaddr() self.assertEqual(0, addr, 'Error in detection of minaddr (0 != 0x%x)' % addr) def test_maxaddr(self): ih = intelhex.IntelHex16bit(self.f) addr = ih.maxaddr() self.assertEqual(0x001D, addr, 'Error in detection of maxaddr ' '(0x001D != 0x%x)' % addr) def test_getitem(self): ih = intelhex.IntelHex16bit(self.f) ih.padding = 0x3FFF for addr, word in enumerate(bin16): self.assertEqual(word, ih[addr], 'Data mismatch at address ' '0x%x (0x%x != 0x%x)' % (addr, word, ih[addr])) def test_not_enough_data(self): ih = intelhex.IntelHex() ih[0] = 1 ih16 = intelhex.IntelHex16bit(ih) self.assertRaisesMsg(BadAccess16bit, 'Bad access at 0x0: ' 'not enough data to read 16 bit value', lambda x: ih16[x], 0) def test_write_hex_file(self): ih = intelhex.IntelHex16bit(self.f) sio = StringIO() ih.write_hex_file(sio) s = sio.getvalue() sio.close() fin = StringIO(s) ih2 = intelhex.IntelHex16bit(fin) self.assertEqual(ih.tobinstr(), ih2.tobinstr(), "Written hex file does not equal with original") def test_setitem(self): ih = intelhex.IntelHex16bit(self.f) old = ih[0] ih[0] = old ^ 0xFFFF self.assertNotEqual(old, ih[0], "Setting new value to internal buffer failed") #/class TestIntelHex16bit class TestIntelHexErrors(TestIntelHexBase): """Tests for custom errors classes""" def _raise_error(self, ErrorClass, dict={}): """Raise ErrorClass for testing""" raise ErrorClass(**dict) def test_IntelHexError(self): self.assertRaisesMsg(IntelHexError, 'IntelHex base error', self._raise_error, IntelHexError) def test_IntelHexError_message(self): self.assertRaisesMsg(IntelHexError, 'IntelHex custom error', self._raise_error, IntelHexError, {'message': 'IntelHex custom error'}) self.assertRaisesMsg(IntelHexError, 'IntelHex base error', self._raise_error, IntelHexError, {'message': ''}) def test_HexReaderError(self): self.assertRaisesMsg(HexReaderError, 'Hex reader base error', self._raise_error, HexReaderError) # also catch via base exception class self.assertRaisesMsg(IntelHexError, 'Hex reader base error', self._raise_error, HexReaderError) def test_HexRecordError(self): self.assertRaisesMsg(HexRecordError, 'Hex file contains invalid record at line 1', self._raise_error, HexRecordError, {'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Hex file contains invalid record at line 1', self._raise_error, HexRecordError, {'line': 1}) def test_RecordLengthError(self): self.assertRaisesMsg(RecordLengthError, 'Record at line 1 has invalid length', self._raise_error, RecordLengthError, {'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Record at line 1 has invalid length', self._raise_error, RecordLengthError, {'line': 1}) def test_RecordTypeError(self): self.assertRaisesMsg(RecordTypeError, 'Record at line 1 has invalid record type', self._raise_error, RecordTypeError, {'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Record at line 1 has invalid record type', self._raise_error, RecordTypeError, {'line': 1}) def test_RecordChecksumError(self): self.assertRaisesMsg(RecordChecksumError, 'Record at line 1 has invalid checksum', self._raise_error, RecordChecksumError, {'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Record at line 1 has invalid checksum', self._raise_error, RecordChecksumError, {'line': 1}) def test_EOFRecordError(self): self.assertRaisesMsg(EOFRecordError, 'File has invalid End-of-File record', self._raise_error, EOFRecordError) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'File has invalid End-of-File record', self._raise_error, EOFRecordError) def test_ExtendedSegmentAddressRecordError(self): self.assertRaisesMsg(ExtendedSegmentAddressRecordError, 'Invalid Extended Segment Address Record at line 1', self._raise_error, ExtendedSegmentAddressRecordError, {'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Invalid Extended Segment Address Record at line 1', self._raise_error, ExtendedSegmentAddressRecordError, {'line': 1}) def test_ExtendedLinearAddressRecordError(self): self.assertRaisesMsg(ExtendedLinearAddressRecordError, 'Invalid Extended Linear Address Record ' 'at line 1', self._raise_error, ExtendedLinearAddressRecordError, {'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Invalid Extended Linear Address Record ' 'at line 1', self._raise_error, ExtendedLinearAddressRecordError, {'line': 1}) def test_StartSegmentAddressRecordError(self): self.assertRaisesMsg(StartSegmentAddressRecordError, 'Invalid Start Segment Address Record at line 1', self._raise_error, StartSegmentAddressRecordError, {'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Invalid Start Segment Address Record at line 1', self._raise_error, StartSegmentAddressRecordError, {'line': 1}) def test_StartLinearAddressRecordError(self): self.assertRaisesMsg(StartLinearAddressRecordError, 'Invalid Start Linear Address Record at line 1', self._raise_error, StartLinearAddressRecordError, {'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Invalid Start Linear Address Record at line 1', self._raise_error, StartLinearAddressRecordError, {'line': 1}) def test_DuplicateStartAddressRecord(self): self.assertRaisesMsg(DuplicateStartAddressRecordError, 'Start Address Record appears twice at line 1', self._raise_error, DuplicateStartAddressRecordError, {'line': 1}) def test_InvalidStartAddressValue(self): self.assertRaisesMsg(InvalidStartAddressValueError, "Invalid start address value: {'foo': 1}", self._raise_error, InvalidStartAddressValueError, {'start_addr': {'foo': 1}}) def test_AddressOverlapError(self): self.assertRaisesMsg(AddressOverlapError, 'Hex file has data overlap at address 0x1234 ' 'on line 1', self._raise_error, AddressOverlapError, {'address': 0x1234, 'line': 1}) # also catch via base exception class self.assertRaisesMsg(HexReaderError, 'Hex file has data overlap at address 0x1234 ' 'on line 1', self._raise_error, AddressOverlapError, {'address': 0x1234, 'line': 1}) def test_BadAccess16bit(self): self.assertRaisesMsg(BadAccess16bit, 'Bad access at 0x1234: ' 'not enough data to read 16 bit value', self._raise_error, BadAccess16bit, {'address': 0x1234}) #/class TestIntelHexErrors class TestDecodeHexRecords(TestIntelHexBase): """Testing that decoding of records is correct and all errors raised when needed """ def setUp(self): self.ih = IntelHex() self.decode_record = self.ih._decode_record def tearDown(self): del self.ih def test_empty_line(self): # do we could to accept empty lines in hex files? # standard don't say anything about this self.decode_record('') def test_non_empty_line(self): self.assertRaisesMsg(HexRecordError, 'Hex file contains invalid record at line 1', self.decode_record, ' ', 1) def test_short_record(self): # if record too short it's not a hex record self.assertRaisesMsg(HexRecordError, 'Hex file contains invalid record at line 1', self.decode_record, ':', 1) def test_odd_hexascii_digits(self): self.assertRaisesMsg(HexRecordError, 'Hex file contains invalid record at line 1', self.decode_record, ':0100000100F', 1) def test_invalid_length(self): self.assertRaisesMsg(RecordLengthError, 'Record at line 1 has invalid length', self.decode_record, ':FF00000100', 1) def test_invalid_record_type(self): self.assertRaisesMsg(RecordTypeError, 'Record at line 1 has invalid record type', self.decode_record, ':000000FF01', 1) def test_invalid_checksum(self): self.assertRaisesMsg(RecordChecksumError, 'Record at line 1 has invalid checksum', self.decode_record, ':0000000100', 1) def test_invalid_eof(self): self.assertRaisesMsg(EOFRecordError, 'File has invalid End-of-File record', self.decode_record, ':0100000100FE', 1) def test_invalid_extended_segment(self): # length self.assertRaisesMsg(ExtendedSegmentAddressRecordError, 'Invalid Extended Segment Address Record at line 1', self.decode_record, ':00000002FE', 1) # addr field self.assertRaisesMsg(ExtendedSegmentAddressRecordError, 'Invalid Extended Segment Address Record at line 1', self.decode_record, ':020001020000FB', 1) def test_invalid_linear_address(self): # length self.assertRaisesMsg(ExtendedLinearAddressRecordError, 'Invalid Extended Linear Address Record ' 'at line 1', self.decode_record, ':00000004FC', 1) # addr field self.assertRaisesMsg(ExtendedLinearAddressRecordError, 'Invalid Extended Linear Address Record ' 'at line 1', self.decode_record, ':020001040000F9', 1) def test_invalid_start_segment_addr(self): # length self.assertRaisesMsg(StartSegmentAddressRecordError, 'Invalid Start Segment Address Record at line 1', self.decode_record, ':00000003FD', 1) # addr field self.assertRaisesMsg(StartSegmentAddressRecordError, 'Invalid Start Segment Address Record at line 1', self.decode_record, ':0400010300000000F8', 1) def test_duplicate_start_segment_addr(self): self.decode_record(':0400000312345678E5') self.assertRaisesMsg(DuplicateStartAddressRecordError, 'Start Address Record appears twice at line 2', self.decode_record, ':0400000300000000F9', 2) def test_invalid_start_linear_addr(self): # length self.assertRaisesMsg(StartLinearAddressRecordError, 'Invalid Start Linear Address Record at line 1', self.decode_record, ':00000005FB', 1) # addr field self.assertRaisesMsg(StartLinearAddressRecordError, 'Invalid Start Linear Address Record at line 1', self.decode_record, ':0400010500000000F6', 1) def test_duplicate_start_linear_addr(self): self.decode_record(':0400000512345678E3') self.assertRaisesMsg(DuplicateStartAddressRecordError, 'Start Address Record appears twice at line 2', self.decode_record, ':0400000500000000F7', 2) def test_addr_overlap(self): self.decode_record(':0100000000FF') self.assertRaisesMsg(AddressOverlapError, 'Hex file has data overlap at address 0x0 ' 'on line 1', self.decode_record, ':0100000000FF', 1) def test_data_record(self): # should be no exceptions self.decode_record(':0100000000FF\n') self.decode_record(':03000100000102F9\r\n') self.decode_record(':1004E300CFF0FBE2FDF220FF20F2E120E2FBE6F396') def test_eof(self): # EOF should raise special exception self.assertRaises(_EndOfFile, self.decode_record, ':00000001FF') #/class TestDecodeHexRecords class TestHex2Bin(unittest.TestCase): def setUp(self): self.fin = StringIO(hex8) self.fout = StringIO() def tearDown(self): self.fin.close() self.fout.close() def test_hex2bin(self): ih = hex2bin(self.fin, self.fout) data = array.array('B', self.fout.getvalue()) for addr in xrange(len(bin8)): expected = bin8[addr] actual = data[addr] self.assertEqual(expected, actual, "Data different at address " "%x (%x != %x)" % (addr, expected, actual)) class TestBuildRecords(TestIntelHexBase): def test__from_bytes(self): self.assertEqual(':00000001FF', intelhex.Record._from_bytes([0,0,0,1])) def test_data(self): self.assertEqual(':011234005663', intelhex.Record.data(0x1234, [0x56])) self.assertEqual(':0312340056789059', intelhex.Record.data(0x1234, [0x56, 0x78, 0x90])) def test_eof(self): self.assertEqual(':00000001FF', intelhex.Record.eof()) def test_extended_segment_address(self): self.assertEqual(':020000021234B6', intelhex.Record.extended_segment_address(0x1234)) def test_start_segment_address(self): self.assertEqual(':0400000312345678E5', intelhex.Record.start_segment_address(0x1234, 0x5678)) def test_extended_linear_address(self): self.assertEqual(':020000041234B4', intelhex.Record.extended_linear_address(0x1234)) def test_start_linear_address(self): self.assertEqual(':0400000512345678E3', intelhex.Record.start_linear_address(0x12345678)) ## # MAIN if __name__ == '__main__': unittest.main() tests for error messages is greatly simplified. #!/usr/bin/python # Copyright (c) 2005-2008, Alexander Belchenko # All rights reserved. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided # that the following conditions are met: # # * Redistributions of source code must retain # the above copyright notice, this list of conditions # and the following disclaimer. # * Redistributions in binary form must reproduce # the above copyright notice, this list of conditions # and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the author nor the names # of its contributors may be used to endorse # or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Test suite for IntelHex class.""" import array from cStringIO import StringIO import os import sys import tempfile import unittest import intelhex from intelhex import IntelHex, \ IntelHexError, \ HexReaderError, \ AddressOverlapError, \ HexRecordError, \ RecordLengthError, \ RecordTypeError, \ RecordChecksumError, \ EOFRecordError, \ ExtendedSegmentAddressRecordError, \ ExtendedLinearAddressRecordError, \ StartSegmentAddressRecordError, \ StartLinearAddressRecordError, \ DuplicateStartAddressRecordError, \ InvalidStartAddressValueError, \ _EndOfFile, \ BadAccess16bit, \ hex2bin ## # Data for tests hex8 = '''\ :1004E300CFF0FBE2FDF220FF20F2E120E2FBE6F396 :1004F3000A00FDE0E1E2E3B4E4E5BAE6E7B3BFE80E :10050300E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8E0 :10051300F9FCFEFF00C0C1C2C3A5C4C5AAC6C7B2C9 :10052300AFC8C9CACBCCCDCECFD0D1D2D3D4D5D6F8 :07053300D7D8D9DCDEDF00A0 :10053A0078227C007D007BFF7A0479F57E007F2398 :10054A0012042F78457C007D007BFF7A0579187E9E :10055A00007F2212042F759850438920758DDDD2B1 :10056A008ED2996390017BFF7A0479E31200658049 :01057A00FE82 :030000000205A254 :0C05A200787FE4F6D8FD75817A02053AF6 :10035F00E709F608DFFA8046E709F208DFFA803E80 :10036F0088828C83E709F0A3DFFA8032E309F6086D :10037F00DFFA8078E309F208DFFA807088828C83D5 :10038F00E309F0A3DFFA806489828A83E0A3F60889 :10039F00DFFA805889828A83E0A3F208DFFA804C63 :1003AF0080D280FA80C680D4806980F2803380103A :1003BF0080A680EA809A80A880DA80E280CA8033A3 :1003CF0089828A83ECFAE493A3C8C582C8CCC5831B :1003DF00CCF0A3C8C582C8CCC583CCDFE9DEE780EB :1003EF000D89828A83E493A3F608DFF9ECFAA9F06A :1003FF00EDFB2289828A83ECFAE0A3C8C582C8CCC0 :10040F00C583CCF0A3C8C582C8CCC583CCDFEADED8 :10041F00E880DB89828A83E493A3F208DFF980CC3A :10042F0088F0EF60010E4E60C388F0ED2402B40433 :10043F000050B9F582EB2402B4040050AF232345DA :06044F0082239003AF734D :10000300E576246AF8E60576227867300702786A8F :10001300E475F0011204AD0204552000EB7F2ED2EB :10002300008018EF540F2490D43440D4FF30040BD5 :10003300EF24BFB41A0050032461FFE57760021573 :1000430077057AE57A7002057930070D7867E475EC :10005300F0011204ADEF02049B02057B7403D20787 :100063008003E4C207F5768B678A688969E4F577CC :10007300F579F57AE57760077F2012003E80F57504 :1000830078FFC201C200C202C203C205C206C2088F :1000930012000CFF700D3007057F0012004FAF7A7E :1000A300AE7922B4255FC2D5C20412000CFF24D05E :1000B300B40A00501A75F00A787730D50508B6FFF0 :1000C3000106C6A426F620D5047002D20380D924E3 :1000D300CFB41A00EF5004C2E5D20402024FD2019A :1000E30080C6D20080C0D20280BCD2D580BAD205ED :1000F30080B47F2012003E2002077401B5770040D0 :10010300F1120003FF12003E020077D208D20680EC :1001130095120003FB120003FA120003F94A4B7015 :100123000679207A037BFF20022EE577602A7E0082 :100133008E8275830012046E60060EEE657870F091 :10014300C2D5EBC0E0EAC0E0E9C0E0EE120296D00F :10015300E0F9D0E0FAD0E0FB120455FF60AAEBC04F :10016300E0EAC0E0E9C0E012003ED0E02401F9D0AB :10017300E03400FAD0E0FBE5780460DCD578D98080 :10018300877BFF7A027992D202809C791080027970 :1001930008C206C2088008D2D5790A8004790AC247 :1001A300D5E578047002F578E4FAFDFEFF1200034A :1001B300FC7B08200113120003FD7B1030000A12A0 :1001C3000003FE120003FF7B20EC3382D592D5504F :1001D30013C3E43000069FFFE49EFEE42001039D69 :1001E300FDE49CFCE4CBF8C201EC700CCFCECDCC8B :1001F300E824F8F870F38017C3EF33FFEE33FEED16 :1002030033FDEC33FCEB33FB994002FB0FD8E9EBF6 :10021300300105F8D0E0C448B201C0E00AEC4D4E0D :100223004F78207B0070C2EAB5780040BCC0E01272 :100233000298D0F0D0E0200104C4C0E0C4B201C0F1 :10024300F0120027D0F0D5F0EB0200771204BD01C5 :100253001453018E5800E54C00E14201924F019A7C :0F02630044019A4900FA4301A0550184460184E1 :100272004501844703405000E92D00ED2E01102B6B :1002820000F123010E2003292A00A94800000108D9 :100292003F3F3F00790AA2D5200314300509B91067 :1002A200020404B9080104A2D52006025001042068 :1002B20002689202B577005034C0E07F2030031903 :1002C2007F30A20272067205500F1202EFC202C202 :1002D20006C205C2087F30800F300503E9C0E01274 :1002E200003E300503D0E0F9D0E0B577CC300517F9 :1002F2007F30B9100C12003E7F583004077F78809F :1003020003B9080312003E3002057F2D02003E7F32 :10031200202008F87F2B2006F322920280CF286E3D :10032200756C6C2900D2011200033001F8C2017809 :100332007730D50108F60200A92D50434958120022 :10034200032403B405004001E490033B9312002F01 :0D035200743A12002FD20375770402018E59 :10045500BB010689828A83E0225002E722BBFE02A5 :09046500E32289828A83E49322D8 :10046E00BB010CE58229F582E5833AF583E0225043 :10047E0006E92582F8E622BBFE06E92582F8E2228D :0D048E00E58229F582E5833AF583E49322A7 :10049B00BB010689828A83F0225002F722BBFE0140 :0204AB00F3223A :1004AD00FAE6FB0808E6F925F0F618E6CA3AF62250 :1004BD00D083D082F8E4937012740193700DA3A3CE :1004CD0093F8740193F5828883E4737402936860E2 :0604DD00EFA3A3A380DFE2 :10057B00EFB40A07740D120586740A309811A89906 :10058B00B8130CC2983098FDA899C298B811F630E0 :07059B0099FDC299F59922B8 :00000001FF ''' bin8 = array.array('B',[2, 5, 162, 229, 118, 36, 106, 248, 230, 5, 118, 34, 120, 103, 48, 7, 2, 120, 106, 228, 117, 240, 1, 18, 4, 173, 2, 4, 85, 32, 0, 235, 127, 46, 210, 0, 128, 24, 239, 84, 15, 36, 144, 212, 52, 64, 212, 255, 48, 4, 11, 239, 36, 191, 180, 26, 0, 80, 3, 36, 97, 255, 229, 119, 96, 2, 21, 119, 5, 122, 229, 122, 112, 2, 5, 121, 48, 7, 13, 120, 103, 228, 117, 240, 1, 18, 4, 173, 239, 2, 4, 155, 2, 5, 123, 116, 3, 210, 7, 128, 3, 228, 194, 7, 245, 118, 139, 103, 138, 104, 137, 105, 228, 245, 119, 245, 121, 245, 122, 229, 119, 96, 7, 127, 32, 18, 0, 62, 128, 245, 117, 120, 255, 194, 1, 194, 0, 194, 2, 194, 3, 194, 5, 194, 6, 194, 8, 18, 0, 12, 255, 112, 13, 48, 7, 5, 127, 0, 18, 0, 79, 175, 122, 174, 121, 34, 180, 37, 95, 194, 213, 194, 4, 18, 0, 12, 255, 36, 208, 180, 10, 0, 80, 26, 117, 240, 10, 120, 119, 48, 213, 5, 8, 182, 255, 1, 6, 198, 164, 38, 246, 32, 213, 4, 112, 2, 210, 3, 128, 217, 36, 207, 180, 26, 0, 239, 80, 4, 194, 229, 210, 4, 2, 2, 79, 210, 1, 128, 198, 210, 0, 128, 192, 210, 2, 128, 188, 210, 213, 128, 186, 210, 5, 128, 180, 127, 32, 18, 0, 62, 32, 2, 7, 116, 1, 181, 119, 0, 64, 241, 18, 0, 3, 255, 18, 0, 62, 2, 0, 119, 210, 8, 210, 6, 128, 149, 18, 0, 3, 251, 18, 0, 3, 250, 18, 0, 3, 249, 74, 75, 112, 6, 121, 32, 122, 3, 123, 255, 32, 2, 46, 229, 119, 96, 42, 126, 0, 142, 130, 117, 131, 0, 18, 4, 110, 96, 6, 14, 238, 101, 120, 112, 240, 194, 213, 235, 192, 224, 234, 192, 224, 233, 192, 224, 238, 18, 2, 150, 208, 224, 249, 208, 224, 250, 208, 224, 251, 18, 4, 85, 255, 96, 170, 235, 192, 224, 234, 192, 224, 233, 192, 224, 18, 0, 62, 208, 224, 36, 1, 249, 208, 224, 52, 0, 250, 208, 224, 251, 229, 120, 4, 96, 220, 213, 120, 217, 128, 135, 123, 255, 122, 2, 121, 146, 210, 2, 128, 156, 121, 16, 128, 2, 121, 8, 194, 6, 194, 8, 128, 8, 210, 213, 121, 10, 128, 4, 121, 10, 194, 213, 229, 120, 4, 112, 2, 245, 120, 228, 250, 253, 254, 255, 18, 0, 3, 252, 123, 8, 32, 1, 19, 18, 0, 3, 253, 123, 16, 48, 0, 10, 18, 0, 3, 254, 18, 0, 3, 255, 123, 32, 236, 51, 130, 213, 146, 213, 80, 19, 195, 228, 48, 0, 6, 159, 255, 228, 158, 254, 228, 32, 1, 3, 157, 253, 228, 156, 252, 228, 203, 248, 194, 1, 236, 112, 12, 207, 206, 205, 204, 232, 36, 248, 248, 112, 243, 128, 23, 195, 239, 51, 255, 238, 51, 254, 237, 51, 253, 236, 51, 252, 235, 51, 251, 153, 64, 2, 251, 15, 216, 233, 235, 48, 1, 5, 248, 208, 224, 196, 72, 178, 1, 192, 224, 10, 236, 77, 78, 79, 120, 32, 123, 0, 112, 194, 234, 181, 120, 0, 64, 188, 192, 224, 18, 2, 152, 208, 240, 208, 224, 32, 1, 4, 196, 192, 224, 196, 178, 1, 192, 240, 18, 0, 39, 208, 240, 213, 240, 235, 2, 0, 119, 18, 4, 189, 1, 20, 83, 1, 142, 88, 0, 229, 76, 0, 225, 66, 1, 146, 79, 1, 154, 68, 1, 154, 73, 0, 250, 67, 1, 160, 85, 1, 132, 70, 1, 132, 69, 1, 132, 71, 3, 64, 80, 0, 233, 45, 0, 237, 46, 1, 16, 43, 0, 241, 35, 1, 14, 32, 3, 41, 42, 0, 169, 72, 0, 0, 1, 8, 63, 63, 63, 0, 121, 10, 162, 213, 32, 3, 20, 48, 5, 9, 185, 16, 2, 4, 4, 185, 8, 1, 4, 162, 213, 32, 6, 2, 80, 1, 4, 32, 2, 104, 146, 2, 181, 119, 0, 80, 52, 192, 224, 127, 32, 48, 3, 25, 127, 48, 162, 2, 114, 6, 114, 5, 80, 15, 18, 2, 239, 194, 2, 194, 6, 194, 5, 194, 8, 127, 48, 128, 15, 48, 5, 3, 233, 192, 224, 18, 0, 62, 48, 5, 3, 208, 224, 249, 208, 224, 181, 119, 204, 48, 5, 23, 127, 48, 185, 16, 12, 18, 0, 62, 127, 88, 48, 4, 7, 127, 120, 128, 3, 185, 8, 3, 18, 0, 62, 48, 2, 5, 127, 45, 2, 0, 62, 127, 32, 32, 8, 248, 127, 43, 32, 6, 243, 34, 146, 2, 128, 207, 40, 110, 117, 108, 108, 41, 0, 210, 1, 18, 0, 3, 48, 1, 248, 194, 1, 120, 119, 48, 213, 1, 8, 246, 2, 0, 169, 45, 80, 67, 73, 88, 18, 0, 3, 36, 3, 180, 5, 0, 64, 1, 228, 144, 3, 59, 147, 18, 0, 47, 116, 58, 18, 0, 47, 210, 3, 117, 119, 4, 2, 1, 142, 231, 9, 246, 8, 223, 250, 128, 70, 231, 9, 242, 8, 223, 250, 128, 62, 136, 130, 140, 131, 231, 9, 240, 163, 223, 250, 128, 50, 227, 9, 246, 8, 223, 250, 128, 120, 227, 9, 242, 8, 223, 250, 128, 112, 136, 130, 140, 131, 227, 9, 240, 163, 223, 250, 128, 100, 137, 130, 138, 131, 224, 163, 246, 8, 223, 250, 128, 88, 137, 130, 138, 131, 224, 163, 242, 8, 223, 250, 128, 76, 128, 210, 128, 250, 128, 198, 128, 212, 128, 105, 128, 242, 128, 51, 128, 16, 128, 166, 128, 234, 128, 154, 128, 168, 128, 218, 128, 226, 128, 202, 128, 51, 137, 130, 138, 131, 236, 250, 228, 147, 163, 200, 197, 130, 200, 204, 197, 131, 204, 240, 163, 200, 197, 130, 200, 204, 197, 131, 204, 223, 233, 222, 231, 128, 13, 137, 130, 138, 131, 228, 147, 163, 246, 8, 223, 249, 236, 250, 169, 240, 237, 251, 34, 137, 130, 138, 131, 236, 250, 224, 163, 200, 197, 130, 200, 204, 197, 131, 204, 240, 163, 200, 197, 130, 200, 204, 197, 131, 204, 223, 234, 222, 232, 128, 219, 137, 130, 138, 131, 228, 147, 163, 242, 8, 223, 249, 128, 204, 136, 240, 239, 96, 1, 14, 78, 96, 195, 136, 240, 237, 36, 2, 180, 4, 0, 80, 185, 245, 130, 235, 36, 2, 180, 4, 0, 80, 175, 35, 35, 69, 130, 35, 144, 3, 175, 115, 187, 1, 6, 137, 130, 138, 131, 224, 34, 80, 2, 231, 34, 187, 254, 2, 227, 34, 137, 130, 138, 131, 228, 147, 34, 187, 1, 12, 229, 130, 41, 245, 130, 229, 131, 58, 245, 131, 224, 34, 80, 6, 233, 37, 130, 248, 230, 34, 187, 254, 6, 233, 37, 130, 248, 226, 34, 229, 130, 41, 245, 130, 229, 131, 58, 245, 131, 228, 147, 34, 187, 1, 6, 137, 130, 138, 131, 240, 34, 80, 2, 247, 34, 187, 254, 1, 243, 34, 250, 230, 251, 8, 8, 230, 249, 37, 240, 246, 24, 230, 202, 58, 246, 34, 208, 131, 208, 130, 248, 228, 147, 112, 18, 116, 1, 147, 112, 13, 163, 163, 147, 248, 116, 1, 147, 245, 130, 136, 131, 228, 115, 116, 2, 147, 104, 96, 239, 163, 163, 163, 128, 223, 207, 240, 251, 226, 253, 242, 32, 255, 32, 242, 225, 32, 226, 251, 230, 243, 10, 0, 253, 224, 225, 226, 227, 180, 228, 229, 186, 230, 231, 179, 191, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 252, 254, 255, 0, 192, 193, 194, 195, 165, 196, 197, 170, 198, 199, 178, 175, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 220, 222, 223, 0, 120, 34, 124, 0, 125, 0, 123, 255, 122, 4, 121, 245, 126, 0, 127, 35, 18, 4, 47, 120, 69, 124, 0, 125, 0, 123, 255, 122, 5, 121, 24, 126, 0, 127, 34, 18, 4, 47, 117, 152, 80, 67, 137, 32, 117, 141, 221, 210, 142, 210, 153, 99, 144, 1, 123, 255, 122, 4, 121, 227, 18, 0, 101, 128, 254, 239, 180, 10, 7, 116, 13, 18, 5, 134, 116, 10, 48, 152, 17, 168, 153, 184, 19, 12, 194, 152, 48, 152, 253, 168, 153, 194, 152, 184, 17, 246, 48, 153, 253, 194, 153, 245, 153, 34, 120, 127, 228, 246, 216, 253, 117, 129, 122, 2, 5, 58]) hex16 = """:020000040000FA :10000000000083120313072055301820042883169C :10001000031340309900181598168312031318160D :1000200098170800831203138C1E14281A0808005E :0C003000831203130C1E1A28990008000C :00000001FF """ bin16 = array.array('H', [0x0000, 0x1283, 0x1303, 0x2007, 0x3055, 0x2018, 0x2804, 0x1683, 0x1303, 0x3040, 0x0099, 0x1518, 0x1698, 0x1283, 0x1303, 0x1618, 0x1798, 0x0008, 0x1283, 0x1303, 0x1E8C, 0x2814, 0x081A, 0x0008, 0x1283, 0x1303, 0x1E0C, 0x281A, 0x0099, 0x0008, 0x3FFF, 0x3FFF]) hex64k = """:020000040000FA :0100000001FE :020000040001F9 :0100000002FD :00000001FF """ data64k = {0: 1, 0x10000: 2} hex_rectype3 = """:0400000312345678E5 :0100000001FE :00000001FF """ data_rectype3 = {0: 1} start_addr_rectype3 = {'CS': 0x1234, 'IP': 0x5678} hex_rectype5 = """:0400000512345678E3 :0100000002FD :00000001FF """ data_rectype5 = {0: 2} start_addr_rectype5 = {'EIP': 0x12345678} hex_empty_file = ':00000001FF\n' hex_simple = """\ :10000000000083120313072055301820042883169C :10001000031340309900181598168312031318160D :1000200098170800831203138C1E14281A0808005E :0C003000831203130C1E1A28990008000C :00000001FF """ ## # Test cases class TestIntelHexBase(unittest.TestCase): """Base class for all tests. Provide additional functionality for testing. """ def assertRaisesMsg(self, excClass, msg, callableObj, *args, **kwargs): """Just like unittest.TestCase.assertRaises, but checks that the message is right too. Borrowed from Ned Batchelder Blog. See: http://www.nedbatchelder.com/blog/200609.html#e20060905T064418 Typical usage: self.assertRaisesMsg(MyException, "Exception message", my_function, (arg1, arg2)) """ try: callableObj(*args, **kwargs) except excClass, exc: excMsg = str(exc) if not msg: # No message provided: any message is fine. return elif excMsg == msg: # Message provided, and we got the right message: it passes. return else: # Message provided, and it didn't match: fail! raise self.failureException( "Right exception, wrong message: got '%s' expected '%s'" % (excMsg, msg) ) else: if hasattr(excClass, '__name__'): excName = excClass.__name__ else: excName = str(excClass) raise self.failureException( "Expected to raise %s, didn't get an exception at all" % excName ) def assertEqualWrittenData(self, a, b): return self.assertEquals(a, b, """Written data is incorrect Should be: %s Written: %s """ % (a, b)) #/class TestIntelHexBase class TestIntelHex(TestIntelHexBase): def setUp(self): self.f = StringIO(hex8) def tearDown(self): self.f.close() del self.f def test_init_from_file(self): ih = IntelHex(self.f) for addr in xrange(len(bin8)): expected = bin8[addr] actual = ih[addr] self.assertEqual(expected, actual, "Data different at address " "%x (%x != %x)" % (addr, expected, actual)) def test_hex_fromfile(self): ih = IntelHex() ih.fromfile(self.f, format='hex') for addr in xrange(len(bin8)): expected = bin8[addr] actual = ih[addr] self.assertEqual(expected, actual, "Data different at address " "%x (%x != %x)" % (addr, expected, actual)) def test_unicode_filename(self): handle, fname = tempfile.mkstemp(u'') os.close(handle) try: self.assertTrue(isinstance(fname, unicode)) f = file(fname, 'w') try: f.write(hex8) finally: f.close() ih = IntelHex(fname) self.assertEqual(0, ih.minaddr()) self.assertEqual(len(bin8)-1, ih.maxaddr()) finally: os.remove(fname) def test_tobinstr(self): ih = IntelHex(self.f) s1 = ih.tobinstr() s2 = bin8.tostring() self.assertEqual(s2, s1, "data not equal\n%s\n\n%s" % (s1, s2)) def test_tobinfile(self): ih = IntelHex(self.f) sio = StringIO() ih.tobinfile(sio) s1 = sio.getvalue() sio.close() s2 = bin8.tostring() self.assertEqual(s2, s1, "data not equal\n%s\n\n%s" % (s1, s2)) # new API: .tofile universal method sio = StringIO() ih.tofile(sio, format='bin') s1 = sio.getvalue() sio.close() s2 = bin8.tostring() self.assertEqual(s2, s1, "data not equal\n%s\n\n%s" % (s1, s2)) def test_write_empty_hexfile(self): ih = intelhex.IntelHex() sio = StringIO() ih.write_hex_file(sio) s = sio.getvalue() sio.close() self.assertEqualWrittenData(hex_empty_file, s) def test_write_hexfile(self): ih = intelhex.IntelHex(StringIO(hex_simple)) sio = StringIO() ih.write_hex_file(sio) s = sio.getvalue() sio.close() self.assertEqualWrittenData(hex_simple, s) # new API: .tofile universal method sio = StringIO() ih.tofile(sio, format='hex') s = sio.getvalue() sio.close() self.assertEqualWrittenData(hex_simple, s) def test_tofile_wrong_format(self): ih = IntelHex() sio = StringIO() self.assertRaises(ValueError, ih.tofile, sio, {'format': 'bad'}) def test_todict(self): ih = IntelHex() self.assertEquals({}, ih.todict()) ih = IntelHex(StringIO(hex64k)) self.assertEquals(data64k, ih.todict()) ih = IntelHex() ih[1] = 2 ih.start_addr = {'EIP': 1234} self.assertEquals({1: 2, 'start_addr': {'EIP': 1234}}, ih.todict()) def test_fromdict(self): ih = IntelHex() ih.fromdict({1:2, 3:4}) self.assertEquals({1:2, 3:4}, ih.todict()) ih.fromdict({1:5, 6:7}) self.assertEquals({1:5, 3:4, 6:7}, ih.todict()) ih = IntelHex() ih.fromdict({1: 2, 'start_addr': {'EIP': 1234}}) self.assertEquals({1: 2, 'start_addr': {'EIP': 1234}}, ih.todict()) # bad dict self.assertRaises(ValueError, ih.fromdict, {'EIP': 1234}) self.assertRaises(ValueError, ih.fromdict, {-1: 1234}) def test_init_from_obj(self): ih = IntelHex({1:2, 3:4}) self.assertEquals({1:2, 3:4}, ih.todict()) ih.start_addr = {'EIP': 1234} ih2 = IntelHex(ih) ih[1] = 5 ih.start_addr = {'EIP': 5678} self.assertEquals({1:2, 3:4, 'start_addr': {'EIP': 1234}}, ih2.todict()) self.assertNotEqual(id(ih), id(ih2)) def test_dict_interface(self): ih = IntelHex() self.assertEquals(0xFF, ih[0]) # padding byte substitution ih[0] = 1 self.assertEquals(1, ih[0]) del ih[0] self.assertEquals({}, ih.todict()) # padding byte substitution class TestIntelHexLoadBin(TestIntelHexBase): def setUp(self): self.data = '0123456789' self.f = StringIO(self.data) def tearDown(self): self.f.close() def test_loadbin(self): ih = IntelHex() ih.loadbin(self.f) self.assertEqual(0, ih.minaddr()) self.assertEqual(9, ih.maxaddr()) self.assertEqual(self.data, ih.tobinstr()) def test_bin_fromfile(self): ih = IntelHex() ih.fromfile(self.f, format='bin') self.assertEqual(0, ih.minaddr()) self.assertEqual(9, ih.maxaddr()) self.assertEqual(self.data, ih.tobinstr()) def test_loadbin_w_offset(self): ih = IntelHex() ih.loadbin(self.f, offset=100) self.assertEqual(100, ih.minaddr()) self.assertEqual(109, ih.maxaddr()) self.assertEqual(self.data, ih.tobinstr()) def test_loadfile_format_bin(self): ih = IntelHex() ih.loadfile(self.f, format='bin') self.assertEqual(0, ih.minaddr()) self.assertEqual(9, ih.maxaddr()) self.assertEqual(self.data, ih.tobinstr()) class TestIntelHexStartingAddressRecords(TestIntelHexBase): def _test_read(self, hexstr, data, start_addr): sio = StringIO(hexstr) ih = IntelHex(sio) sio.close() # test data self.assertEqual(data, ih._buf, "Internal buffer: %r != %r" % (data, ih._buf)) self.assertEqual(start_addr, ih.start_addr, "Start address: %r != %r" % (start_addr, ih.start_addr)) def test_read_rectype3(self): self._test_read(hex_rectype3, data_rectype3, start_addr_rectype3) def test_read_rectype5(self): self._test_read(hex_rectype5, data_rectype5, start_addr_rectype5) def _test_write(self, hexstr, data, start_addr, write_start_addr=True): # prepare ih = IntelHex(None) ih._buf = data ih.start_addr = start_addr # write sio = StringIO() ih.write_hex_file(sio, write_start_addr) s = sio.getvalue() sio.close() # check self.assertEqualWrittenData(hexstr, s) def _test_dont_write(self, hexstr, data, start_addr): expected = ''.join(hexstr.splitlines(True)[1:]) self._test_write(expected, data, start_addr, False) def test_write_rectype3(self): self._test_write(hex_rectype3, data_rectype3, start_addr_rectype3) def test_dont_write_rectype3(self): self._test_dont_write(hex_rectype3, data_rectype3, start_addr_rectype3) def test_write_rectype5(self): self._test_write(hex_rectype5, data_rectype5, start_addr_rectype5) def test_dont_write_rectype5(self): self._test_dont_write(hex_rectype5, data_rectype5, start_addr_rectype5) def test_write_invalid_start_addr_value(self): ih = IntelHex() ih.start_addr = {'foo': 1} sio = StringIO() self.assertRaises(InvalidStartAddressValueError, ih.write_hex_file, sio) class TestIntelHex_big_files(TestIntelHexBase): """Test that data bigger than 64K read/write correctly""" def setUp(self): self.f = StringIO(hex64k) def tearDown(self): self.f.close() del self.f def test_readfile(self): ih = intelhex.IntelHex(self.f) for addr, byte in data64k.items(): readed = ih[addr] self.assertEquals(byte, readed, "data not equal at addr %X " "(%X != %X)" % (addr, byte, readed)) def test_write_hex_file(self): ih = intelhex.IntelHex(self.f) sio = StringIO() ih.write_hex_file(sio) s = sio.getvalue() sio.close() self.assertEqualWrittenData(hex64k, s) class TestIntelHex16bit(TestIntelHexBase): def setUp(self): self.f = StringIO(hex16) def tearDown(self): self.f.close() del self.f def test_init_from_file(self): ih = intelhex.IntelHex16bit(self.f) def test_init_from_ih(self): ih = intelhex.IntelHex(self.f) ih16 = intelhex.IntelHex16bit(ih) def test_minaddr(self): ih = intelhex.IntelHex16bit(self.f) addr = ih.minaddr() self.assertEqual(0, addr, 'Error in detection of minaddr (0 != 0x%x)' % addr) def test_maxaddr(self): ih = intelhex.IntelHex16bit(self.f) addr = ih.maxaddr() self.assertEqual(0x001D, addr, 'Error in detection of maxaddr ' '(0x001D != 0x%x)' % addr) def test_getitem(self): ih = intelhex.IntelHex16bit(self.f) ih.padding = 0x3FFF for addr, word in enumerate(bin16): self.assertEqual(word, ih[addr], 'Data mismatch at address ' '0x%x (0x%x != 0x%x)' % (addr, word, ih[addr])) def test_not_enough_data(self): ih = intelhex.IntelHex() ih[0] = 1 ih16 = intelhex.IntelHex16bit(ih) self.assertRaisesMsg(BadAccess16bit, 'Bad access at 0x0: ' 'not enough data to read 16 bit value', lambda x: ih16[x], 0) def test_write_hex_file(self): ih = intelhex.IntelHex16bit(self.f) sio = StringIO() ih.write_hex_file(sio) s = sio.getvalue() sio.close() fin = StringIO(s) ih2 = intelhex.IntelHex16bit(fin) self.assertEqual(ih.tobinstr(), ih2.tobinstr(), "Written hex file does not equal with original") def test_setitem(self): ih = intelhex.IntelHex16bit(self.f) old = ih[0] ih[0] = old ^ 0xFFFF self.assertNotEqual(old, ih[0], "Setting new value to internal buffer failed") #/class TestIntelHex16bit class TestIntelHexErrors(TestIntelHexBase): """Tests for custom errors classes""" def assertEqualExc(self, message, exception): return self.assertEqual(message, str(exception)) def test_IntelHexError(self): self.assertEqualExc('IntelHex base error', IntelHexError()) def test_IntelHexError_message(self): self.assertEqualExc('IntelHex custom error message', IntelHexError(message='IntelHex custom error message')) self.assertEqualExc('IntelHex base error', IntelHexError(message='')) def test_HexReaderError(self): self.assertEqualExc('Hex reader base error', HexReaderError()) def test_HexRecordError(self): self.assertEqualExc('Hex file contains invalid record at line 1', HexRecordError(line=1)) def test_RecordLengthError(self): self.assertEqualExc('Record at line 1 has invalid length', RecordLengthError(line=1)) def test_RecordTypeError(self): self.assertEqualExc('Record at line 1 has invalid record type', RecordTypeError(line=1)) def test_RecordChecksumError(self): self.assertEqualExc('Record at line 1 has invalid checksum', RecordChecksumError(line=1)) def test_EOFRecordError(self): self.assertEqualExc('File has invalid End-of-File record', EOFRecordError()) def test_ExtendedSegmentAddressRecordError(self): self.assertEqualExc( 'Invalid Extended Segment Address Record at line 1', ExtendedSegmentAddressRecordError(line=1)) def test_ExtendedLinearAddressRecordError(self): self.assertEqualExc('Invalid Extended Linear Address Record at line 1', ExtendedLinearAddressRecordError(line=1)) def test_StartSegmentAddressRecordError(self): self.assertEqualExc('Invalid Start Segment Address Record at line 1', StartSegmentAddressRecordError(line=1)) def test_StartLinearAddressRecordError(self): self.assertEqualExc('Invalid Start Linear Address Record at line 1', StartLinearAddressRecordError(line=1)) def test_DuplicateStartAddressRecord(self): self.assertEqualExc('Start Address Record appears twice at line 1', DuplicateStartAddressRecordError(line=1)) def test_InvalidStartAddressValue(self): self.assertEqualExc("Invalid start address value: {'foo': 1}", InvalidStartAddressValueError(start_addr={'foo': 1})) def test_AddressOverlapError(self): self.assertEqualExc('Hex file has data overlap at address 0x1234 ' 'on line 1', AddressOverlapError(address=0x1234, line=1)) def test_BadAccess16bit(self): self.assertEqualExc('Bad access at 0x1234: ' 'not enough data to read 16 bit value', BadAccess16bit(address=0x1234)) #/class TestIntelHexErrors class TestDecodeHexRecords(TestIntelHexBase): """Testing that decoding of records is correct and all errors raised when needed """ def setUp(self): self.ih = IntelHex() self.decode_record = self.ih._decode_record def tearDown(self): del self.ih def test_empty_line(self): # do we could to accept empty lines in hex files? # standard don't say anything about this self.decode_record('') def test_non_empty_line(self): self.assertRaisesMsg(HexRecordError, 'Hex file contains invalid record at line 1', self.decode_record, ' ', 1) def test_short_record(self): # if record too short it's not a hex record self.assertRaisesMsg(HexRecordError, 'Hex file contains invalid record at line 1', self.decode_record, ':', 1) def test_odd_hexascii_digits(self): self.assertRaisesMsg(HexRecordError, 'Hex file contains invalid record at line 1', self.decode_record, ':0100000100F', 1) def test_invalid_length(self): self.assertRaisesMsg(RecordLengthError, 'Record at line 1 has invalid length', self.decode_record, ':FF00000100', 1) def test_invalid_record_type(self): self.assertRaisesMsg(RecordTypeError, 'Record at line 1 has invalid record type', self.decode_record, ':000000FF01', 1) def test_invalid_checksum(self): self.assertRaisesMsg(RecordChecksumError, 'Record at line 1 has invalid checksum', self.decode_record, ':0000000100', 1) def test_invalid_eof(self): self.assertRaisesMsg(EOFRecordError, 'File has invalid End-of-File record', self.decode_record, ':0100000100FE', 1) def test_invalid_extended_segment(self): # length self.assertRaisesMsg(ExtendedSegmentAddressRecordError, 'Invalid Extended Segment Address Record at line 1', self.decode_record, ':00000002FE', 1) # addr field self.assertRaisesMsg(ExtendedSegmentAddressRecordError, 'Invalid Extended Segment Address Record at line 1', self.decode_record, ':020001020000FB', 1) def test_invalid_linear_address(self): # length self.assertRaisesMsg(ExtendedLinearAddressRecordError, 'Invalid Extended Linear Address Record ' 'at line 1', self.decode_record, ':00000004FC', 1) # addr field self.assertRaisesMsg(ExtendedLinearAddressRecordError, 'Invalid Extended Linear Address Record ' 'at line 1', self.decode_record, ':020001040000F9', 1) def test_invalid_start_segment_addr(self): # length self.assertRaisesMsg(StartSegmentAddressRecordError, 'Invalid Start Segment Address Record at line 1', self.decode_record, ':00000003FD', 1) # addr field self.assertRaisesMsg(StartSegmentAddressRecordError, 'Invalid Start Segment Address Record at line 1', self.decode_record, ':0400010300000000F8', 1) def test_duplicate_start_segment_addr(self): self.decode_record(':0400000312345678E5') self.assertRaisesMsg(DuplicateStartAddressRecordError, 'Start Address Record appears twice at line 2', self.decode_record, ':0400000300000000F9', 2) def test_invalid_start_linear_addr(self): # length self.assertRaisesMsg(StartLinearAddressRecordError, 'Invalid Start Linear Address Record at line 1', self.decode_record, ':00000005FB', 1) # addr field self.assertRaisesMsg(StartLinearAddressRecordError, 'Invalid Start Linear Address Record at line 1', self.decode_record, ':0400010500000000F6', 1) def test_duplicate_start_linear_addr(self): self.decode_record(':0400000512345678E3') self.assertRaisesMsg(DuplicateStartAddressRecordError, 'Start Address Record appears twice at line 2', self.decode_record, ':0400000500000000F7', 2) def test_addr_overlap(self): self.decode_record(':0100000000FF') self.assertRaisesMsg(AddressOverlapError, 'Hex file has data overlap at address 0x0 ' 'on line 1', self.decode_record, ':0100000000FF', 1) def test_data_record(self): # should be no exceptions self.decode_record(':0100000000FF\n') self.decode_record(':03000100000102F9\r\n') self.decode_record(':1004E300CFF0FBE2FDF220FF20F2E120E2FBE6F396') def test_eof(self): # EOF should raise special exception self.assertRaises(_EndOfFile, self.decode_record, ':00000001FF') #/class TestDecodeHexRecords class TestHex2Bin(unittest.TestCase): def setUp(self): self.fin = StringIO(hex8) self.fout = StringIO() def tearDown(self): self.fin.close() self.fout.close() def test_hex2bin(self): ih = hex2bin(self.fin, self.fout) data = array.array('B', self.fout.getvalue()) for addr in xrange(len(bin8)): expected = bin8[addr] actual = data[addr] self.assertEqual(expected, actual, "Data different at address " "%x (%x != %x)" % (addr, expected, actual)) class TestBuildRecords(TestIntelHexBase): def test__from_bytes(self): self.assertEqual(':00000001FF', intelhex.Record._from_bytes([0,0,0,1])) def test_data(self): self.assertEqual(':011234005663', intelhex.Record.data(0x1234, [0x56])) self.assertEqual(':0312340056789059', intelhex.Record.data(0x1234, [0x56, 0x78, 0x90])) def test_eof(self): self.assertEqual(':00000001FF', intelhex.Record.eof()) def test_extended_segment_address(self): self.assertEqual(':020000021234B6', intelhex.Record.extended_segment_address(0x1234)) def test_start_segment_address(self): self.assertEqual(':0400000312345678E5', intelhex.Record.start_segment_address(0x1234, 0x5678)) def test_extended_linear_address(self): self.assertEqual(':020000041234B4', intelhex.Record.extended_linear_address(0x1234)) def test_start_linear_address(self): self.assertEqual(':0400000512345678E3', intelhex.Record.start_linear_address(0x12345678)) ## # MAIN if __name__ == '__main__': unittest.main()
#!/usr/bin/env python2.7 """ Create pileups from GAMs, and evaluate different parameter sets for the pileup- to-glennfile and glenn-to-vcf steps of the variant calling pipeline. Takes alignments stored like this: alignments/brca1/cactus/NA19240.gam so: <alignments IOstore>/<region>/<graph>/<sample>.gam The graphs must also be accessible: graphs/cactus-brca1.vg so: <graphs IOStore>/<graph method>-<region>.vg note: debruin is exception where -k63 tag gets tacked on at end (treated as special case) """ import argparse, sys, os, os.path, random, subprocess, shutil, itertools, glob import doctest, re, json, collections, time, timeit, string import hashlib import signal from threading import Timer from toil.job import Job from toillib import RealTimeLogger, robust_makedirs, IOStore class ExperimentCondition: """ Represents a combination of read filtering, graph augmenting, vcf generating, and vcf filtering options. """ def __init__(self, read_filter_options, pileup_options, call_options, vcf_options, vcfeval_options): """ Take dicts from option string to option value for read filtering, pileup-ing, graph augmenting, vcf conversion, and vcf evaluation, and produces an ExperimentCondition wrapping them. Option values may only be single strings, and an option may only occur a single time (since we have a dict). TODO: also add VCF filtering """ self.read_filter_options = read_filter_options self.pileup_options = pileup_options self.call_options = call_options self.vcf_options = vcf_options self.vcfeval_options = vcfeval_options def dict_to_string(self, options_dict): """ Convert a dict of option values to a single string. """ # Get a nested list of pairs of options and value strings. Use sorting # to make sure we get them in a deterministic order. nested = ([opt_name, str(opt_value)] for opt_name, opt_value in sorted(options_dict.iteritems())) # Flatten and join into a string return " ".join((item for pair in nested for item in pair)) def string_to_path(self, string): """ Convert a string into a usable path component (directory name). """ # Condense spaces to underscores, and remove all but a few safe # characters. return re.sub('[^a-zA-Z0-9_.]', "", re.sub('\s+', "_", re.sub("_", "", string)).strip("_")) def get_read_filter_options(self): """ Return the options string for read filtering. """ return self.dict_to_string(self.read_filter_options) def get_pileup_options(self): """ Return the options string for pileup-ing. """ return self.dict_to_string(self.pileup_options) def get_call_options(self): """ Return the options string for vg call. """ return self.dict_to_string(self.call_options) def get_vcf_options(self): """ Return the options string for glenn2vcf. """ return self.dict_to_string(self.vcf_options) def get_vcfeval_options(self): """ Return the options string for vcfeval. """ return self.dict_to_string(self.vcfeval_options) def get_pileup_condition_name(self): """ Return a string that can be part of a filesystem path and which depends on all the parameters that affect the pielup. """ # Depends on the filter and pileup options return self.string_to_path(self.get_read_filter_options()) + "/" + self.string_to_path(self.get_pileup_options()) def get_glennfile_condition_name(self): """ Return a string that can be part of a filesystem path (potentially including slashes) and which depends on all the parameters that affect the glenn file, including those that affect the pileup. """ # Depends on the pileup file and the call options return self.get_pileup_condition_name() + "/" + self.string_to_path(self.get_call_options()) def get_vcf_condition_name(self): """ Return a string that can be part of a filesystem path (potentially including slashes) and which depends on all the parameters that affect the final VCF file, given the glenn file. """ # Depends on the gelnnfile and the glenn2vcf options return self.get_glennfile_condition_name() + "/" + self.string_to_path(self.get_vcf_options()) def get_vcfeval_condition_name(self): """ Return a string that can be part of a filesystem path (potentially including slashes) and which depends on all the parameters that affect the vcfeval evaluation. """ # Depends on the gelnnfile and the glenn2vcf options return self.get_vcf_condition_name() + "/" + self.string_to_path(self.get_vcfeval_options()) def parse_args(args): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add the Toil options so the job store is the first argument Job.Runner.addToilOptions(parser) # General options parser.add_argument("in_gams", help="input alignment files IOStore") parser.add_argument("in_graphs", help="input graph files IOStore") parser.add_argument("cache", help="cache IOStore so we don't have to re-do pileups constantly") parser.add_argument("out_dir", help="output IOStore, containing experimental results") parser.add_argument("--truth", help="IOStore to search for truth vcfs for comparison. For each sample " "and region we expect <sample>/<REGION>.vcf.gz and " "<sample>/<REGION>.vcf.gz.tbi") parser.add_argument("--regions", help="IOStore to search for region BEDs. For each region we " "expect <REGION>.bed, with the region in upper-case.") parser.add_argument("--sdf", default="data/g1kvcf/chrom.sdf", help="SDF-format directory structure for reference assembly for " "vcfeval") parser.add_argument("--blacklist", nargs="+", default=["vglr", "mhc:camel", "lrc_kir:camel", "debruijn-k31", "debruijn-k63", "cenx", "simons", "curoverse", "flat1kg", "primary1kg"], help="ignore the specified regions, graphs, or region:graph pairs") args = args[1:] return parser.parse_args(args) def run(cmds, stdout = sys.stdout, stderr = sys.stderr, timeout_sec = sys.maxint, timeout_dep = None, fail_hard = False): """ Run commands in the given list in the shell, piping each in the next. Throw an exception if any of the commands fails or if the whole pipeline times out. """ def timeout_fail(procs, cmds): """ Called when the given processes, launched from the given commands, have run for too long. Kills the processes and logs an error. """ for proc in procs: os.kill(proc.pid, signal.SIGKILL) proc.kill() # we often check to see if some output file exists before running # if we timeout, make sure the file exists so rerunning wont timeout again # at same place (unless overwrite explicitly desired) if timeout_dep is not None and os.path.exists(timeout_dep): os.system("rm -rf {}; echo timeout > {}".format(timeout_dep, timeout_dep)) if fail_hard is True: raise RuntimeError("Command: {} timed out".format(" | ".join(cmds))) else: RealTimeLogger.get().warning("Command: {} timed out".format(" | ".join(cmds))) RealTimeLogger.get().info("RUN: {}".format(" | ".join(cmds))) # We have a list of processes, one per command. procs = [] # We remember the previous process's standard output last_stdout = None for cmd in cmds[:-1]: # All but the last command feed their standard output into pipes proc = subprocess.Popen(cmd, shell=True, bufsize=-1, stdin=last_stdout, stdout=subprocess.PIPE, stderr=stderr) last_stdout = proc.stdout procs.append(proc) for cmd in cmds[-1:]: # The last command, if any, just dumps to our standard output proc = subprocess.Popen(cmd, shell=True, bufsize=-1, stdin=last_stdout, stdout=stdout, stderr=stderr) procs.append(proc) # We collect the return codes statuses = [] # based on a comment in http://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout timer = Timer(timeout_sec, timeout_fail, [procs, cmds]) try: timer.start() for proc, cmd in itertools.izip(procs, cmds): sts = proc.wait() statuses.append(sts) if sts != 0: message = "Command: {} in pipeline {} exited with non-zero status {}".format(cmd, " | ".join(cmds), sts) if fail_hard is True: raise RuntimeError(message) else: RealTimeLogger.get().warning(message) finally: timer.cancel() if len(statuses) > 0: # Return the max return code (0 if everything worked) return max(statuses) else: # Nothing bad haoppened because nothing happened return 0 def alignment_region_tag(alignment_key): """ Given an alignment key formatted like <region>/<graph>/<sample>.gam, produce the region name. """ region = alignment_key.split("/")[-3] # TODO: can we not hardcode a list of known regions? assert region in ["brca1", "brca2", "cenx", "lrc_kir", "sma", "mhc"] return region def alignment_graph_tag(alignment_key): """ Given an alignment key formatted like <region>/<graph>/<sample>.gam, produce the graph name. """ return alignment_key.split("/")[-2] def alignment_sample_tag(alignment_key): """ Given an alignment key formatted like <region>/<graph>/<sample>.gam, produce the sample name. """ return os.path.splitext(os.path.basename(alignment_key))[0] def graph_key(alignment_key): """ Get the graph key (i.e. relative path) for the garph athat a GAM file was aligned against, given a GAM key (i.e. relative path). """ region = alignment_region_tag(alignment_key) graph = alignment_graph_tag(alignment_key) # Special-case the De Bruijn graphs and stick the -kwhatever at the end. if graph.find("debruijn") == 0: assert graph.find("-") == 8 tag = graph[8:] graph = "debruijn" else: tag = "" return "{}-{}{}.vg".format(graph, region, tag) def cache_key_stem(alignment_key): """ Get the cache key stem (region/graph) for the given GAM key. """ region = alignment_region_tag(alignment_key) graph = alignment_graph_tag(alignment_key) return region + "/" + graph def pileup_key(alignment_key, condition): """ Given a GAM file key, get the key under which the pileup for that GAM file should be stored, under the given experimental conditions. """ name = alignment_sample_tag(alignment_key) name += ".vgpu" return "/".join([cache_key_stem(alignment_key), condition.get_pileup_condition_name(), name]) def glennfile_key(alignment_key, condition): """ Get the key for the Glennfile in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_call.tsv" return "/".join([cache_key_stem(alignment_key), condition.get_glennfile_condition_name(), name]) def augmented_graph_key(alignment_key, condition): """ Get the key for the augmented graph in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_augmented.tsv" return "/".join([cache_key_stem(alignment_key), condition.get_glennfile_condition_name(), name]) def vcf_compressed_key(alignment_key, condition): """ Get the key for the compressed VCF file in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_sample.vcf.gz" return "/".join([cache_key_stem(alignment_key), condition.get_vcf_condition_name(), name]) def vcf_index_key(alignment_key, condition): """ Get the key for the index of the compressed VCF file in the cache, based on the experimental condition and the original GAM name. """ return vcf_compressed_key(alignment_key, condition) + ".tbi" def vcf_log_key(alignment_key, condition): """ Get the key for the glenn2vcf log file in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_sample.vcf.stderr" return "/".join([cache_key_stem(alignment_key), condition.get_vcf_condition_name(), name]) def vcfeval_summary_key(alignment_key, condition): """ Get the key for the vcfeval comparison summary in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_summary.txt" return "/".join([cache_key_stem(alignment_key), condition.get_vcfeval_condition_name(), name]) def vcfeval_fp_key(alignment_key, condition): """ Get the key for the vcfeval false positives VCF in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_pf.vcf.gz" return "/".join([cache_key_stem(alignment_key), condition.get_vcfeval_condition_name(), name]) def vcfeval_fn_key(alignment_key, condition): """ Get the key for the vcfeval false negatives VCF in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_fn.vcf.gz" return "/".join([cache_key_stem(alignment_key), condition.get_vcfeval_condition_name(), name]) def vcfeval_roc_key(alignment_key, condition): """ Get the key for the vcfeval weighted ROC curve in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_weighted_roc.tsv.gz" return "/".join([cache_key_stem(alignment_key), condition.get_vcfeval_condition_name(), name]) def truth_compressed_key(alignment_key): """ Get the key for the compressed truth VCF for this sample in the **truth IOstore**, not the cache. """ sample = os.path.splitext(os.path.basename(alignment_key))[0] region = alignment_region_tag(alignment_key) return "{}/{}.vcf.gz".format(sample, region.upper()) def truth_index_key(alignment_key): """ Get the key for the index of the compressed truth VCF for this sample in the **truth IOstore**, not the cache. """ return truth_compressed_key(alignment_key) + ".tbi" def make_pileup(job, gam_key, condition, options): """ Toil job to make a pileup from the given GAM, in the given experimental condition. Loads the GAM from the input GAM IOStore, and saves the pileup to the right place in the cache IOStore for the given sample. Returns nothing. """ # Make IOStores gam_store = IOStore.get(options.in_gams) graph_store = IOStore.get(options.in_graphs) cache_store = IOStore.get(options.cache) # Determine output key out_pileup_key = pileup_key(gam_key, condition) if cache_store.exists(out_pileup_key): # We already made this file return # Download the GAM input_gam = gam_store.get_input_file(job, gam_key) # And the graph it was aligned to input_graph = graph_store.get_input_file(job, graph_key(gam_key)) # Plan where the output pileup goes out_pileup_path = "{}/pileup.vgpu".format(job.fileStore.getLocalTempDir()) # Run the filter and pileup steps, and die if they fail pipeline = [] pipeline.append("vg filter {} {}".format(input_gam, condition.get_read_filter_options())) pipeline.append("vg pileup {} - {} -t {} > {}".format(input_graph, condition.get_pileup_options(), job.cores, out_pileup_path)) run(pipeline, fail_hard = True) # Upload the pileup to the cache for the current experimental conditions cache_store.write_output_file(out_pileup_path, out_pileup_key) def make_glennfile_from_pileup(job, gam_key, condition, options): """ Toil job which, assuming that the GAM has already been turned into a pileup in the cache for the given experimental condition, produces the augmented graph and associated glennfile in the cache for the current condition. Returns nothing. """ # Make IOStores graph_store = IOStore.get(options.in_graphs) cache_store = IOStore.get(options.cache) # Determine output filenames out_glennfile_key = glennfile_key(gam_key, condition) out_augmented_graph_key = augmented_graph_key(gam_key, condition) if cache_store.exists(out_glennfile_key) and cache_store.exists(out_augmented_graph_key): # We already made these files return # Get the non-augmented graph input_graph = graph_store.get_input_file(job, graph_key(gam_key)) # Get the pileup from the cache input_pileup = cache_store.get_input_file(job, pileup_key(gam_key, condition)) # Plan where the output glennfile goes out_glennfile = "{}/sample.glenn".format(job.fileStore.getLocalTempDir()) # And where the output augmented graph goes out_augmented_graph = "{}/sample.vg".format(job.fileStore.getLocalTempDir()) # Do the actual vg call-ing pipeline = [] pipeline.append("vg call {} {} {} -l -c {} -t {} > {}".format( input_graph, input_pileup, condition.get_call_options(), out_glennfile, job.cores, out_augmented_graph)) run(pipeline, fail_hard = True) # Save the glennfile and augmented graph back to the cache cache_store.write_output_file(out_glennfile, out_glennfile_key) cache_store.write_output_file(out_augmented_graph, out_augmented_graph_key) def make_vcf_from_glennfile(job, gam_key, condition, options): """ Toil job which, assuming that the Glennfile and augmented graph have already been made for the given sample and experimental condition, produces the VCF. Needs the regions option to be specified. Returns nothing. """ # Make IOStores cache_store = IOStore.get(options.cache) region_store = IOStore.get(options.regions) # Determine output keys out_vcf_compressed_key = vcf_compressed_key(gam_key, condition) out_vcf_index_key = vcf_index_key(gam_key, condition) out_vcf_log_key = vcf_log_key(gam_key, condition) if (cache_store.exists(out_vcf_compressed_key) and cache_store.exists(out_vcf_index_key) and cache_store.exists(out_vcf_log_key)): # We already made these files return # Get the augmented graph from the cache input_augmented_graph = cache_store.get_input_file(job, augmented_graph_key(gam_key, condition)) # Get the glennfile from the cache input_glennfile = cache_store.get_input_file(job, glennfile_key(gam_key, condition)) # Get the BED that tells us where the region is region_bed = region_store.get_input_file(job, alignment_region_tag(gam_key).upper() + ".bed") with open(region_bed) as f: # Read the contig and offset we want our VCF to be in from the BED file. contig, offset = f.readline().split()[0:2] # Get the sample name sample_name = alignment_sample_tag(gam_key) # Plan where to put the output VCF out_vcf = "{}/sample.vcf".format(job.fileStore.getLocalTempDir()) # And its compressed and indexed versions out_vcf_compressed = out_vcf + ".gz" out_vcf_index = out_vcf_compressed + ".tbi" # Plan where to put the intermediate unsorted VCF unsorted_vcf = "{}/unsorted.vcf".format(job.fileStore.getLocalTempDir()) # And the glenn2vcf error log (which has bases dropped, etc.) out_errlog = "{}/sample.err".format(job.fileStore.getLocalTempDir()) # Do the actual VCF conversion pipeline = [] pipeline.append("glenn2vcf {} {} -o {} -c {} -s {} {} > {} 2> {}".format( input_augmented_graph, input_glennfile, offset, contig, sample_name, condition.get_vcf_options(), unsorted_vcf, out_errlog)) run(pipeline, fail_hard = True) # Sort the VCF pipeline = [] pipeline.append("scripts/vcfsort {} > {}".format(unsorted_vcf, out_vcf)) run(pipeline, fail_hard = True) # Compress and index the VCF run(["bgzip {} -c > {}".format(out_vcf, out_vcf_compressed)], fail_hard=True) # TODO: This is forced to append .tbi as the index name run(["tabix -f -p vcf {}".format(out_vcf_compressed)], fail_hard=True) # Save the compressed VCF, its index, and its error log back to the cache cache_store.write_output_file(out_vcf_compressed, out_vcf_compressed_key) cache_store.write_output_file(out_vcf_index, out_vcf_index_key) cache_store.write_output_file(out_errlog, out_vcf_log_key) def compute_performance_from_vcf(job, gam_key, condition, options): """ Compute the performance of the given GAM (aligned to the given graph) against the truth set for its region. Places the vcfeval summary file for the given sample in the cache. """ # Make IOStores cache_store = IOStore.get(options.cache) truth_store = IOStore.get(options.truth) # Determine where the resuls go # Summary out_summary_key = vcfeval_summary_key(gam_key, condition) # False positives VCF out_fp_key = vcfeval_fp_key(gam_key, condition) # False negatives VCF out_fn_key = vcfeval_fn_key(gam_key, condition) # ROC curve data out_roc_key = vcfeval_roc_key(gam_key, condition) if (cache_store.exists(out_summary_key) and cache_store.exists(out_fp_key) and cache_store.exists(out_fn_key) and cache_store.exists(out_roc_key)): # We already did this return # Get the query VCF query_vcf_compressed = cache_store.get_input_file(job, vcf_compressed_key(gam_key, condition)) query_vcf_index = cache_store.get_input_file(job, vcf_index_key(gam_key, condition)) if query_vcf_index != query_vcf_compressed + ".tbi": # Hack them over to the right names with symlinks new_vcf_name = "{}/sample.vcf.gz".format(job.fileStore.getLocalTempDir()) os.symlink(query_vcf_compressed, new_vcf_name) os.symlink(query_vcf_index, new_vcf_name + ".tbi") query_vcf_compressed = new_vcf_name query_vcf_index = query_vcf_compressed + ".tbi" # Find the truth VCF truth_vcf_compressed = truth_store.get_input_file(job, truth_compressed_key(gam_key)) truth_vcf_index = truth_store.get_input_file(job, truth_index_key(gam_key)) if truth_vcf_index != truth_vcf_compressed + ".tbi": # Hack them over to the right names with symlinks new_vcf_name = "{}/truth.vcf.gz".format(job.fileStore.getLocalTempDir()) os.symlink(truth_vcf_compressed, new_vcf_name) os.symlink(truth_vcf_index, new_vcf_name + ".tbi") truth_vcf_compressed = new_vcf_name truth_vcf_index = truth_vcf_compressed + ".tbi" # Decide on an output directory out_dir = "{}/vcfeval".format(job.fileStore.getLocalTempDir()) # Do the actual VCF conversion pipeline = [] pipeline.append("rtg vcfeval -b {} -c {} -t {} -o {} {}".format( truth_vcf_compressed, query_vcf_compressed, options.sdf, out_dir, condition.get_vcfeval_options())) run(pipeline, fail_hard=True) # Save the result files back to the cache cache_store.write_output_file(out_dir + "/summary.txt", out_summary_key) cache_store.write_output_file(out_dir + "/fp.vcf.gz", out_fp_key) cache_store.write_output_file(out_dir + "/fn.vcf.gz", out_fn_key) cache_store.write_output_file(out_dir + "/weighted_roc.tsv.gz", out_roc_key) def run_experiment(job, options): """ Toil job to run an experiment on a variety of conditions and compare the results. """ # Make the IOStore we can search for GAMs gam_store = IOStore.get(options.in_gams) for region_dir in gam_store.list_input_directory(""): # Within every region we have samples for, look through all the # different graphs. for graph_dir in gam_store.list_input_directory(region_dir): # Within every graph for a region, we have a collection of samples. if ("{}:{}".format(region_dir, graph_dir) in options.blacklist or region_dir in options.blacklist or graph_dir in options.blacklist): # We don't want to process this region/graph pair. RealTimeLogger.get().info("Skipping {} graph {}".format( region_dir, graph_dir)) continue for filename in gam_store.list_input_directory("{}/{}".format( region_dir, graph_dir)): # Look at each potential sample file # Is this file a sample? match = re.match("(.+)\\.gam$", filename) if not match: # It's not a sample continue # Otherwise, compose the full GAM key gam_key = "{}/{}/{}".format(region_dir, graph_dir, filename) # Make some experimental conditions with filter, pileup, call, # and glenn2vcf options. TODO: change to long options for # readability condition = ExperimentCondition( { # vg filter "-r": 0.90, "-d": 0.05, "-e": 0.05, "-a": "", "-f": "", "-u": "", "-s": 10000, "-o": 10 }, { # vg pileup "-w": 40, "-m": 10, "-q": 10 }, { # vg call "-r": 0.0001, "-b": 0.4, "-f": 0.25, "-d": 11 }, { # glenn2vcf "--depth": 10 }, { # vcfeval "--all-records": "", "--vcf-score-field": "DP" }) # Kick off a pipeline to make the variant calls. # TODO: assumes all the extra directories we need to read stuff from are set pileup_job = job.addChildJobFn(make_pileup, gam_key, condition, options, cores=1, memory="10G", disk="10G") glennfile_job = pileup_job.addFollowOnJobFn(make_glennfile_from_pileup, gam_key, condition, options, cores=1, memory="10G", disk="10G") vcf_job = glennfile_job.addFollowOnJobFn(make_vcf_from_glennfile, gam_key, condition, options, cores=1, memory="10G", disk="10G") vcfeval_job = vcf_job.addFollowOnJobFn(compute_performance_from_vcf, gam_key, condition, options, cores=1, memory="10G", disk="10G") def main(args): options = parse_args(args) RealTimeLogger.start_master() # Make a root job root_job = Job.wrapJobFn(run_experiment, options, cores=1, memory="2G", disk="2G") # Run it and see how many jobs fail failed_jobs = Job.Runner.startToil(root_job, options) if failed_jobs > 0: raise Exception("{} jobs failed!".format(failed_jobs)) RealTimeLogger.stop_master() if __name__ == "__main__" : sys.exit(main(sys.argv)) Fix spelling of fp. #!/usr/bin/env python2.7 """ Create pileups from GAMs, and evaluate different parameter sets for the pileup- to-glennfile and glenn-to-vcf steps of the variant calling pipeline. Takes alignments stored like this: alignments/brca1/cactus/NA19240.gam so: <alignments IOstore>/<region>/<graph>/<sample>.gam The graphs must also be accessible: graphs/cactus-brca1.vg so: <graphs IOStore>/<graph method>-<region>.vg note: debruin is exception where -k63 tag gets tacked on at end (treated as special case) """ import argparse, sys, os, os.path, random, subprocess, shutil, itertools, glob import doctest, re, json, collections, time, timeit, string import hashlib import signal from threading import Timer from toil.job import Job from toillib import RealTimeLogger, robust_makedirs, IOStore class ExperimentCondition: """ Represents a combination of read filtering, graph augmenting, vcf generating, and vcf filtering options. """ def __init__(self, read_filter_options, pileup_options, call_options, vcf_options, vcfeval_options): """ Take dicts from option string to option value for read filtering, pileup-ing, graph augmenting, vcf conversion, and vcf evaluation, and produces an ExperimentCondition wrapping them. Option values may only be single strings, and an option may only occur a single time (since we have a dict). TODO: also add VCF filtering """ self.read_filter_options = read_filter_options self.pileup_options = pileup_options self.call_options = call_options self.vcf_options = vcf_options self.vcfeval_options = vcfeval_options def dict_to_string(self, options_dict): """ Convert a dict of option values to a single string. """ # Get a nested list of pairs of options and value strings. Use sorting # to make sure we get them in a deterministic order. nested = ([opt_name, str(opt_value)] for opt_name, opt_value in sorted(options_dict.iteritems())) # Flatten and join into a string return " ".join((item for pair in nested for item in pair)) def string_to_path(self, string): """ Convert a string into a usable path component (directory name). """ # Condense spaces to underscores, and remove all but a few safe # characters. return re.sub('[^a-zA-Z0-9_.]', "", re.sub('\s+', "_", re.sub("_", "", string)).strip("_")) def get_read_filter_options(self): """ Return the options string for read filtering. """ return self.dict_to_string(self.read_filter_options) def get_pileup_options(self): """ Return the options string for pileup-ing. """ return self.dict_to_string(self.pileup_options) def get_call_options(self): """ Return the options string for vg call. """ return self.dict_to_string(self.call_options) def get_vcf_options(self): """ Return the options string for glenn2vcf. """ return self.dict_to_string(self.vcf_options) def get_vcfeval_options(self): """ Return the options string for vcfeval. """ return self.dict_to_string(self.vcfeval_options) def get_pileup_condition_name(self): """ Return a string that can be part of a filesystem path and which depends on all the parameters that affect the pielup. """ # Depends on the filter and pileup options return self.string_to_path(self.get_read_filter_options()) + "/" + self.string_to_path(self.get_pileup_options()) def get_glennfile_condition_name(self): """ Return a string that can be part of a filesystem path (potentially including slashes) and which depends on all the parameters that affect the glenn file, including those that affect the pileup. """ # Depends on the pileup file and the call options return self.get_pileup_condition_name() + "/" + self.string_to_path(self.get_call_options()) def get_vcf_condition_name(self): """ Return a string that can be part of a filesystem path (potentially including slashes) and which depends on all the parameters that affect the final VCF file, given the glenn file. """ # Depends on the gelnnfile and the glenn2vcf options return self.get_glennfile_condition_name() + "/" + self.string_to_path(self.get_vcf_options()) def get_vcfeval_condition_name(self): """ Return a string that can be part of a filesystem path (potentially including slashes) and which depends on all the parameters that affect the vcfeval evaluation. """ # Depends on the gelnnfile and the glenn2vcf options return self.get_vcf_condition_name() + "/" + self.string_to_path(self.get_vcfeval_options()) def parse_args(args): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add the Toil options so the job store is the first argument Job.Runner.addToilOptions(parser) # General options parser.add_argument("in_gams", help="input alignment files IOStore") parser.add_argument("in_graphs", help="input graph files IOStore") parser.add_argument("cache", help="cache IOStore so we don't have to re-do pileups constantly") parser.add_argument("out_dir", help="output IOStore, containing experimental results") parser.add_argument("--truth", help="IOStore to search for truth vcfs for comparison. For each sample " "and region we expect <sample>/<REGION>.vcf.gz and " "<sample>/<REGION>.vcf.gz.tbi") parser.add_argument("--regions", help="IOStore to search for region BEDs. For each region we " "expect <REGION>.bed, with the region in upper-case.") parser.add_argument("--sdf", default="data/g1kvcf/chrom.sdf", help="SDF-format directory structure for reference assembly for " "vcfeval") parser.add_argument("--blacklist", nargs="+", default=["vglr", "mhc:camel", "lrc_kir:camel", "debruijn-k31", "debruijn-k63", "cenx", "simons", "curoverse", "flat1kg", "primary1kg"], help="ignore the specified regions, graphs, or region:graph pairs") args = args[1:] return parser.parse_args(args) def run(cmds, stdout = sys.stdout, stderr = sys.stderr, timeout_sec = sys.maxint, timeout_dep = None, fail_hard = False): """ Run commands in the given list in the shell, piping each in the next. Throw an exception if any of the commands fails or if the whole pipeline times out. """ def timeout_fail(procs, cmds): """ Called when the given processes, launched from the given commands, have run for too long. Kills the processes and logs an error. """ for proc in procs: os.kill(proc.pid, signal.SIGKILL) proc.kill() # we often check to see if some output file exists before running # if we timeout, make sure the file exists so rerunning wont timeout again # at same place (unless overwrite explicitly desired) if timeout_dep is not None and os.path.exists(timeout_dep): os.system("rm -rf {}; echo timeout > {}".format(timeout_dep, timeout_dep)) if fail_hard is True: raise RuntimeError("Command: {} timed out".format(" | ".join(cmds))) else: RealTimeLogger.get().warning("Command: {} timed out".format(" | ".join(cmds))) RealTimeLogger.get().info("RUN: {}".format(" | ".join(cmds))) # We have a list of processes, one per command. procs = [] # We remember the previous process's standard output last_stdout = None for cmd in cmds[:-1]: # All but the last command feed their standard output into pipes proc = subprocess.Popen(cmd, shell=True, bufsize=-1, stdin=last_stdout, stdout=subprocess.PIPE, stderr=stderr) last_stdout = proc.stdout procs.append(proc) for cmd in cmds[-1:]: # The last command, if any, just dumps to our standard output proc = subprocess.Popen(cmd, shell=True, bufsize=-1, stdin=last_stdout, stdout=stdout, stderr=stderr) procs.append(proc) # We collect the return codes statuses = [] # based on a comment in http://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout timer = Timer(timeout_sec, timeout_fail, [procs, cmds]) try: timer.start() for proc, cmd in itertools.izip(procs, cmds): sts = proc.wait() statuses.append(sts) if sts != 0: message = "Command: {} in pipeline {} exited with non-zero status {}".format(cmd, " | ".join(cmds), sts) if fail_hard is True: raise RuntimeError(message) else: RealTimeLogger.get().warning(message) finally: timer.cancel() if len(statuses) > 0: # Return the max return code (0 if everything worked) return max(statuses) else: # Nothing bad haoppened because nothing happened return 0 def alignment_region_tag(alignment_key): """ Given an alignment key formatted like <region>/<graph>/<sample>.gam, produce the region name. """ region = alignment_key.split("/")[-3] # TODO: can we not hardcode a list of known regions? assert region in ["brca1", "brca2", "cenx", "lrc_kir", "sma", "mhc"] return region def alignment_graph_tag(alignment_key): """ Given an alignment key formatted like <region>/<graph>/<sample>.gam, produce the graph name. """ return alignment_key.split("/")[-2] def alignment_sample_tag(alignment_key): """ Given an alignment key formatted like <region>/<graph>/<sample>.gam, produce the sample name. """ return os.path.splitext(os.path.basename(alignment_key))[0] def graph_key(alignment_key): """ Get the graph key (i.e. relative path) for the garph athat a GAM file was aligned against, given a GAM key (i.e. relative path). """ region = alignment_region_tag(alignment_key) graph = alignment_graph_tag(alignment_key) # Special-case the De Bruijn graphs and stick the -kwhatever at the end. if graph.find("debruijn") == 0: assert graph.find("-") == 8 tag = graph[8:] graph = "debruijn" else: tag = "" return "{}-{}{}.vg".format(graph, region, tag) def cache_key_stem(alignment_key): """ Get the cache key stem (region/graph) for the given GAM key. """ region = alignment_region_tag(alignment_key) graph = alignment_graph_tag(alignment_key) return region + "/" + graph def pileup_key(alignment_key, condition): """ Given a GAM file key, get the key under which the pileup for that GAM file should be stored, under the given experimental conditions. """ name = alignment_sample_tag(alignment_key) name += ".vgpu" return "/".join([cache_key_stem(alignment_key), condition.get_pileup_condition_name(), name]) def glennfile_key(alignment_key, condition): """ Get the key for the Glennfile in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_call.tsv" return "/".join([cache_key_stem(alignment_key), condition.get_glennfile_condition_name(), name]) def augmented_graph_key(alignment_key, condition): """ Get the key for the augmented graph in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_augmented.tsv" return "/".join([cache_key_stem(alignment_key), condition.get_glennfile_condition_name(), name]) def vcf_compressed_key(alignment_key, condition): """ Get the key for the compressed VCF file in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_sample.vcf.gz" return "/".join([cache_key_stem(alignment_key), condition.get_vcf_condition_name(), name]) def vcf_index_key(alignment_key, condition): """ Get the key for the index of the compressed VCF file in the cache, based on the experimental condition and the original GAM name. """ return vcf_compressed_key(alignment_key, condition) + ".tbi" def vcf_log_key(alignment_key, condition): """ Get the key for the glenn2vcf log file in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_sample.vcf.stderr" return "/".join([cache_key_stem(alignment_key), condition.get_vcf_condition_name(), name]) def vcfeval_summary_key(alignment_key, condition): """ Get the key for the vcfeval comparison summary in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_summary.txt" return "/".join([cache_key_stem(alignment_key), condition.get_vcfeval_condition_name(), name]) def vcfeval_fp_key(alignment_key, condition): """ Get the key for the vcfeval false positives VCF in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_fp.vcf.gz" return "/".join([cache_key_stem(alignment_key), condition.get_vcfeval_condition_name(), name]) def vcfeval_fn_key(alignment_key, condition): """ Get the key for the vcfeval false negatives VCF in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_fn.vcf.gz" return "/".join([cache_key_stem(alignment_key), condition.get_vcfeval_condition_name(), name]) def vcfeval_roc_key(alignment_key, condition): """ Get the key for the vcfeval weighted ROC curve in the cache, based on the experimental condition and the original GAM name. """ name = alignment_sample_tag(alignment_key) name += "_weighted_roc.tsv.gz" return "/".join([cache_key_stem(alignment_key), condition.get_vcfeval_condition_name(), name]) def truth_compressed_key(alignment_key): """ Get the key for the compressed truth VCF for this sample in the **truth IOstore**, not the cache. """ sample = os.path.splitext(os.path.basename(alignment_key))[0] region = alignment_region_tag(alignment_key) return "{}/{}.vcf.gz".format(sample, region.upper()) def truth_index_key(alignment_key): """ Get the key for the index of the compressed truth VCF for this sample in the **truth IOstore**, not the cache. """ return truth_compressed_key(alignment_key) + ".tbi" def make_pileup(job, gam_key, condition, options): """ Toil job to make a pileup from the given GAM, in the given experimental condition. Loads the GAM from the input GAM IOStore, and saves the pileup to the right place in the cache IOStore for the given sample. Returns nothing. """ # Make IOStores gam_store = IOStore.get(options.in_gams) graph_store = IOStore.get(options.in_graphs) cache_store = IOStore.get(options.cache) # Determine output key out_pileup_key = pileup_key(gam_key, condition) if cache_store.exists(out_pileup_key): # We already made this file return # Download the GAM input_gam = gam_store.get_input_file(job, gam_key) # And the graph it was aligned to input_graph = graph_store.get_input_file(job, graph_key(gam_key)) # Plan where the output pileup goes out_pileup_path = "{}/pileup.vgpu".format(job.fileStore.getLocalTempDir()) # Run the filter and pileup steps, and die if they fail pipeline = [] pipeline.append("vg filter {} {}".format(input_gam, condition.get_read_filter_options())) pipeline.append("vg pileup {} - {} -t {} > {}".format(input_graph, condition.get_pileup_options(), job.cores, out_pileup_path)) run(pipeline, fail_hard = True) # Upload the pileup to the cache for the current experimental conditions cache_store.write_output_file(out_pileup_path, out_pileup_key) def make_glennfile_from_pileup(job, gam_key, condition, options): """ Toil job which, assuming that the GAM has already been turned into a pileup in the cache for the given experimental condition, produces the augmented graph and associated glennfile in the cache for the current condition. Returns nothing. """ # Make IOStores graph_store = IOStore.get(options.in_graphs) cache_store = IOStore.get(options.cache) # Determine output filenames out_glennfile_key = glennfile_key(gam_key, condition) out_augmented_graph_key = augmented_graph_key(gam_key, condition) if cache_store.exists(out_glennfile_key) and cache_store.exists(out_augmented_graph_key): # We already made these files return # Get the non-augmented graph input_graph = graph_store.get_input_file(job, graph_key(gam_key)) # Get the pileup from the cache input_pileup = cache_store.get_input_file(job, pileup_key(gam_key, condition)) # Plan where the output glennfile goes out_glennfile = "{}/sample.glenn".format(job.fileStore.getLocalTempDir()) # And where the output augmented graph goes out_augmented_graph = "{}/sample.vg".format(job.fileStore.getLocalTempDir()) # Do the actual vg call-ing pipeline = [] pipeline.append("vg call {} {} {} -l -c {} -t {} > {}".format( input_graph, input_pileup, condition.get_call_options(), out_glennfile, job.cores, out_augmented_graph)) run(pipeline, fail_hard = True) # Save the glennfile and augmented graph back to the cache cache_store.write_output_file(out_glennfile, out_glennfile_key) cache_store.write_output_file(out_augmented_graph, out_augmented_graph_key) def make_vcf_from_glennfile(job, gam_key, condition, options): """ Toil job which, assuming that the Glennfile and augmented graph have already been made for the given sample and experimental condition, produces the VCF. Needs the regions option to be specified. Returns nothing. """ # Make IOStores cache_store = IOStore.get(options.cache) region_store = IOStore.get(options.regions) # Determine output keys out_vcf_compressed_key = vcf_compressed_key(gam_key, condition) out_vcf_index_key = vcf_index_key(gam_key, condition) out_vcf_log_key = vcf_log_key(gam_key, condition) if (cache_store.exists(out_vcf_compressed_key) and cache_store.exists(out_vcf_index_key) and cache_store.exists(out_vcf_log_key)): # We already made these files return # Get the augmented graph from the cache input_augmented_graph = cache_store.get_input_file(job, augmented_graph_key(gam_key, condition)) # Get the glennfile from the cache input_glennfile = cache_store.get_input_file(job, glennfile_key(gam_key, condition)) # Get the BED that tells us where the region is region_bed = region_store.get_input_file(job, alignment_region_tag(gam_key).upper() + ".bed") with open(region_bed) as f: # Read the contig and offset we want our VCF to be in from the BED file. contig, offset = f.readline().split()[0:2] # Get the sample name sample_name = alignment_sample_tag(gam_key) # Plan where to put the output VCF out_vcf = "{}/sample.vcf".format(job.fileStore.getLocalTempDir()) # And its compressed and indexed versions out_vcf_compressed = out_vcf + ".gz" out_vcf_index = out_vcf_compressed + ".tbi" # Plan where to put the intermediate unsorted VCF unsorted_vcf = "{}/unsorted.vcf".format(job.fileStore.getLocalTempDir()) # And the glenn2vcf error log (which has bases dropped, etc.) out_errlog = "{}/sample.err".format(job.fileStore.getLocalTempDir()) # Do the actual VCF conversion pipeline = [] pipeline.append("glenn2vcf {} {} -o {} -c {} -s {} {} > {} 2> {}".format( input_augmented_graph, input_glennfile, offset, contig, sample_name, condition.get_vcf_options(), unsorted_vcf, out_errlog)) run(pipeline, fail_hard = True) # Sort the VCF pipeline = [] pipeline.append("scripts/vcfsort {} > {}".format(unsorted_vcf, out_vcf)) run(pipeline, fail_hard = True) # Compress and index the VCF run(["bgzip {} -c > {}".format(out_vcf, out_vcf_compressed)], fail_hard=True) # TODO: This is forced to append .tbi as the index name run(["tabix -f -p vcf {}".format(out_vcf_compressed)], fail_hard=True) # Save the compressed VCF, its index, and its error log back to the cache cache_store.write_output_file(out_vcf_compressed, out_vcf_compressed_key) cache_store.write_output_file(out_vcf_index, out_vcf_index_key) cache_store.write_output_file(out_errlog, out_vcf_log_key) def compute_performance_from_vcf(job, gam_key, condition, options): """ Compute the performance of the given GAM (aligned to the given graph) against the truth set for its region. Places the vcfeval summary file for the given sample in the cache. """ # Make IOStores cache_store = IOStore.get(options.cache) truth_store = IOStore.get(options.truth) # Determine where the resuls go # Summary out_summary_key = vcfeval_summary_key(gam_key, condition) # False positives VCF out_fp_key = vcfeval_fp_key(gam_key, condition) # False negatives VCF out_fn_key = vcfeval_fn_key(gam_key, condition) # ROC curve data out_roc_key = vcfeval_roc_key(gam_key, condition) if (cache_store.exists(out_summary_key) and cache_store.exists(out_fp_key) and cache_store.exists(out_fn_key) and cache_store.exists(out_roc_key)): # We already did this return # Get the query VCF query_vcf_compressed = cache_store.get_input_file(job, vcf_compressed_key(gam_key, condition)) query_vcf_index = cache_store.get_input_file(job, vcf_index_key(gam_key, condition)) if query_vcf_index != query_vcf_compressed + ".tbi": # Hack them over to the right names with symlinks new_vcf_name = "{}/sample.vcf.gz".format(job.fileStore.getLocalTempDir()) os.symlink(query_vcf_compressed, new_vcf_name) os.symlink(query_vcf_index, new_vcf_name + ".tbi") query_vcf_compressed = new_vcf_name query_vcf_index = query_vcf_compressed + ".tbi" # Find the truth VCF truth_vcf_compressed = truth_store.get_input_file(job, truth_compressed_key(gam_key)) truth_vcf_index = truth_store.get_input_file(job, truth_index_key(gam_key)) if truth_vcf_index != truth_vcf_compressed + ".tbi": # Hack them over to the right names with symlinks new_vcf_name = "{}/truth.vcf.gz".format(job.fileStore.getLocalTempDir()) os.symlink(truth_vcf_compressed, new_vcf_name) os.symlink(truth_vcf_index, new_vcf_name + ".tbi") truth_vcf_compressed = new_vcf_name truth_vcf_index = truth_vcf_compressed + ".tbi" # Decide on an output directory out_dir = "{}/vcfeval".format(job.fileStore.getLocalTempDir()) # Do the actual VCF conversion pipeline = [] pipeline.append("rtg vcfeval -b {} -c {} -t {} -o {} {}".format( truth_vcf_compressed, query_vcf_compressed, options.sdf, out_dir, condition.get_vcfeval_options())) run(pipeline, fail_hard=True) # Save the result files back to the cache cache_store.write_output_file(out_dir + "/summary.txt", out_summary_key) cache_store.write_output_file(out_dir + "/fp.vcf.gz", out_fp_key) cache_store.write_output_file(out_dir + "/fn.vcf.gz", out_fn_key) cache_store.write_output_file(out_dir + "/weighted_roc.tsv.gz", out_roc_key) def run_experiment(job, options): """ Toil job to run an experiment on a variety of conditions and compare the results. """ # Make the IOStore we can search for GAMs gam_store = IOStore.get(options.in_gams) for region_dir in gam_store.list_input_directory(""): # Within every region we have samples for, look through all the # different graphs. for graph_dir in gam_store.list_input_directory(region_dir): # Within every graph for a region, we have a collection of samples. if ("{}:{}".format(region_dir, graph_dir) in options.blacklist or region_dir in options.blacklist or graph_dir in options.blacklist): # We don't want to process this region/graph pair. RealTimeLogger.get().info("Skipping {} graph {}".format( region_dir, graph_dir)) continue for filename in gam_store.list_input_directory("{}/{}".format( region_dir, graph_dir)): # Look at each potential sample file # Is this file a sample? match = re.match("(.+)\\.gam$", filename) if not match: # It's not a sample continue # Otherwise, compose the full GAM key gam_key = "{}/{}/{}".format(region_dir, graph_dir, filename) # Make some experimental conditions with filter, pileup, call, # and glenn2vcf options. TODO: change to long options for # readability condition = ExperimentCondition( { # vg filter "-r": 0.90, "-d": 0.05, "-e": 0.05, "-a": "", "-f": "", "-u": "", "-s": 10000, "-o": 10 }, { # vg pileup "-w": 40, "-m": 10, "-q": 10 }, { # vg call "-r": 0.0001, "-b": 0.4, "-f": 0.25, "-d": 11 }, { # glenn2vcf "--depth": 10 }, { # vcfeval "--all-records": "", "--vcf-score-field": "DP" }) # Kick off a pipeline to make the variant calls. # TODO: assumes all the extra directories we need to read stuff from are set pileup_job = job.addChildJobFn(make_pileup, gam_key, condition, options, cores=1, memory="10G", disk="10G") glennfile_job = pileup_job.addFollowOnJobFn(make_glennfile_from_pileup, gam_key, condition, options, cores=1, memory="10G", disk="10G") vcf_job = glennfile_job.addFollowOnJobFn(make_vcf_from_glennfile, gam_key, condition, options, cores=1, memory="10G", disk="10G") vcfeval_job = vcf_job.addFollowOnJobFn(compute_performance_from_vcf, gam_key, condition, options, cores=1, memory="10G", disk="10G") def main(args): options = parse_args(args) RealTimeLogger.start_master() # Make a root job root_job = Job.wrapJobFn(run_experiment, options, cores=1, memory="2G", disk="2G") # Run it and see how many jobs fail failed_jobs = Job.Runner.startToil(root_job, options) if failed_jobs > 0: raise Exception("{} jobs failed!".format(failed_jobs)) RealTimeLogger.stop_master() if __name__ == "__main__" : sys.exit(main(sys.argv))
""" draw a histogram of the distribution of a given column and check for uniformity with the chisq test. """ import argparse import numpy as np from chart import chart from _common import pairwise def run(args): # get rid of N, just keep the correlation. col_num = args.c if args.c < 0 else (args.c - 1) file_iter = (l.rstrip("\r\n").split("\t") for l in open(args.file) if l[0] != "#") pvals = np.array([float(b[col_num]) for b in file_iter]) kwargs = {"bins": args.n } if args.n else {} hist, bins = np.histogram(pvals, normed=True, **kwargs) xlabels = "|".join("%.2f-%.2f" % b for b in pairwise(bins)) print "#", chart(hist, xlabels) hist, bins = np.histogram(pvals, normed=False, **kwargs) try: from scipy.stats import chisquare chisq, p = chisquare(hist) print "#chi-square test of uniformity. p-val: %.3g " \ "(low value means reject null of uniformity)" % p except ImportError: pass print "#bin_start\tbin_end\tn" for bin, val in zip(pairwise(bins), hist): print "%.2f\t%.2f\t%i" % (bin[0], bin[1], val) def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("-c", dest="c", help="column number for the histogram", type=int, default=-1) p.add_argument("-n", dest="n", help="number of bins in the histogram", type=int, default=None) p.add_argument('file', help='bed file to correct') args = p.parse_args() return run(args) if __name__ == "__main__": import doctest if doctest.testmod(optionflags=doctest.ELLIPSIS |\ doctest.NORMALIZE_WHITESPACE).failed == 0: main() add some summary stats to hist """ draw a histogram of the distribution of a given column and check for uniformity with the chisq test. """ import argparse import numpy as np from chart import chart from _common import pairwise def run(args): # get rid of N, just keep the correlation. col_num = args.c if args.c < 0 else (args.c - 1) file_iter = (l.rstrip("\r\n").split("\t") for l in open(args.file) if l[0] != "#") pvals = np.array([float(b[col_num]) for b in file_iter]) kwargs = {"bins": args.n } if args.n else {} hist, bins = np.histogram(pvals, normed=True, **kwargs) xlabels = "|".join("%.2f-%.2f" % b for b in pairwise(bins)) print "#", chart(hist, xlabels) hist, bins = np.histogram(pvals, normed=False, **kwargs) print "# median: %.3f mean:%.3f; std: %.3f min:%.3f; max:%.3f" % ( np.median(pvals), pvals.mean(), pvals.std(), pvals.min(), pvals.max()) try: from scipy.stats import chisquare chisq, p = chisquare(hist) print "#chi-square test of uniformity. p: %.3g " \ "(low value means reject null of uniformity)" % p except ImportError: pass print "#bin_start\tbin_end\tn" for bin, val in zip(pairwise(bins), hist): print "%.2f\t%.2f\t%i" % (bin[0], bin[1], val) def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("-c", dest="c", help="column number for the histogram", type=int, default=-1) p.add_argument("-n", dest="n", help="number of bins in the histogram", type=int, default=None) p.add_argument('file', help='bed file to correct') args = p.parse_args() return run(args) if __name__ == "__main__": import doctest if doctest.testmod(optionflags=doctest.ELLIPSIS |\ doctest.NORMALIZE_WHITESPACE).failed == 0: main()
# Copyright (c) 2020, 2021 The Linux Foundation # # SPDX-License-Identifier: Apache-2.0 import os from west import log from zspdx.walker import WalkerConfig, Walker from zspdx.scanner import ScannerConfig, scanDocument from zspdx.writer import writeSPDX # SBOMConfig contains settings that will be passed along to the various # SBOM maker subcomponents. class SBOMConfig: def __init__(self): super(SBOMConfig, self).__init__() # prefix for Document namespaces; should not end with "/" self.namespacePrefix = "" # location of build directory self.buildDir = "" # location of SPDX document output directory self.spdxDir = "" # should also analyze for included header files? self.analyzeIncludes = False # should also add an SPDX document for the SDK? self.includeSDK = False # create Cmake file-based API directories and query file # Arguments: # 1) build_dir: build directory def setupCmakeQuery(build_dir): # check that query dir exists as a directory, or else create it cmakeApiDirPath = os.path.join(build_dir, ".cmake", "api", "v1", "query") if os.path.exists(cmakeApiDirPath): if not os.path.isdir(cmakeApiDirPath): log.err(f'cmake api query directory {cmakeApiDirPath} exists and is not a directory') return False # directory exists, we're good else: # create the directory os.makedirs(cmakeApiDirPath, exist_ok=False) # check that codemodel-v2 exists as a file, or else create it queryFilePath = os.path.join(cmakeApiDirPath, "codemodel-v2") if os.path.exists(queryFilePath): if not os.path.isfile(queryFilePath): log.err(f'cmake api query file {queryFilePath} exists and is not a directory') return False # file exists, we're good return True else: # file doesn't exist, let's create it os.mknod(queryFilePath) return True # main entry point for SBOM maker # Arguments: # 1) cfg: SBOMConfig def makeSPDX(cfg): # report any odd configuration settings if cfg.analyzeIncludes and not cfg.includeSDK: log.wrn(f"config: requested to analyze includes but not to generate SDK SPDX document;") log.wrn(f"config: will proceed but will discard detected includes for SDK header files") # set up walker configuration walkerCfg = WalkerConfig() walkerCfg.namespacePrefix = cfg.namespacePrefix walkerCfg.buildDir = cfg.buildDir walkerCfg.analyzeIncludes = cfg.analyzeIncludes walkerCfg.includeSDK = cfg.includeSDK # make and run the walker w = Walker(walkerCfg) retval = w.makeDocuments() if not retval: log.err("SPDX walker failed; bailing") return False # set up scanner configuration scannerCfg = ScannerConfig() # scan each document from walker if cfg.includeSDK: scanDocument(scannerCfg, w.docSDK) scanDocument(scannerCfg, w.docApp) scanDocument(scannerCfg, w.docZephyr) scanDocument(scannerCfg, w.docBuild) # write each document, in this particular order so that the # hashes for external references are calculated # write SDK document, if we made one if cfg.includeSDK: retval = writeSPDX(os.path.join(cfg.spdxDir, "sdk.spdx"), w.docSDK) if not retval: log.err("SPDX writer failed for SDK document; bailing") return False # write app document retval = writeSPDX(os.path.join(cfg.spdxDir, "app.spdx"), w.docApp) if not retval: log.err("SPDX writer failed for app document; bailing") return False # write zephyr document writeSPDX(os.path.join(cfg.spdxDir, "zephyr.spdx"), w.docZephyr) if not retval: log.err("SPDX writer failed for zephyr document; bailing") return False # write build document writeSPDX(os.path.join(cfg.spdxDir, "build.spdx"), w.docBuild) if not retval: log.err("SPDX writer failed for build document; bailing") return False return True west: spdx: Fix --init for Windows builds Currently, west spdx --init uses os.mknod to create an empty file to enable the Cmake file-based API system. As reported in #39311, Python on Windows does not implement os.mknod. This commit switches to using open()/close() instead of os.mknod() to address this issue. Signed-off-by: Steve Winslow <9ce5770b3bb4b2a1d59be2d97e34379cd192299f@swinslow.net> # Copyright (c) 2020, 2021 The Linux Foundation # # SPDX-License-Identifier: Apache-2.0 import os from west import log from zspdx.walker import WalkerConfig, Walker from zspdx.scanner import ScannerConfig, scanDocument from zspdx.writer import writeSPDX # SBOMConfig contains settings that will be passed along to the various # SBOM maker subcomponents. class SBOMConfig: def __init__(self): super(SBOMConfig, self).__init__() # prefix for Document namespaces; should not end with "/" self.namespacePrefix = "" # location of build directory self.buildDir = "" # location of SPDX document output directory self.spdxDir = "" # should also analyze for included header files? self.analyzeIncludes = False # should also add an SPDX document for the SDK? self.includeSDK = False # create Cmake file-based API directories and query file # Arguments: # 1) build_dir: build directory def setupCmakeQuery(build_dir): # check that query dir exists as a directory, or else create it cmakeApiDirPath = os.path.join(build_dir, ".cmake", "api", "v1", "query") if os.path.exists(cmakeApiDirPath): if not os.path.isdir(cmakeApiDirPath): log.err(f'cmake api query directory {cmakeApiDirPath} exists and is not a directory') return False # directory exists, we're good else: # create the directory os.makedirs(cmakeApiDirPath, exist_ok=False) # check that codemodel-v2 exists as a file, or else create it queryFilePath = os.path.join(cmakeApiDirPath, "codemodel-v2") if os.path.exists(queryFilePath): if not os.path.isfile(queryFilePath): log.err(f'cmake api query file {queryFilePath} exists and is not a directory') return False # file exists, we're good return True else: # file doesn't exist, let's create an empty file cm_fd = open(queryFilePath, "w") cm_fd.close() return True # main entry point for SBOM maker # Arguments: # 1) cfg: SBOMConfig def makeSPDX(cfg): # report any odd configuration settings if cfg.analyzeIncludes and not cfg.includeSDK: log.wrn(f"config: requested to analyze includes but not to generate SDK SPDX document;") log.wrn(f"config: will proceed but will discard detected includes for SDK header files") # set up walker configuration walkerCfg = WalkerConfig() walkerCfg.namespacePrefix = cfg.namespacePrefix walkerCfg.buildDir = cfg.buildDir walkerCfg.analyzeIncludes = cfg.analyzeIncludes walkerCfg.includeSDK = cfg.includeSDK # make and run the walker w = Walker(walkerCfg) retval = w.makeDocuments() if not retval: log.err("SPDX walker failed; bailing") return False # set up scanner configuration scannerCfg = ScannerConfig() # scan each document from walker if cfg.includeSDK: scanDocument(scannerCfg, w.docSDK) scanDocument(scannerCfg, w.docApp) scanDocument(scannerCfg, w.docZephyr) scanDocument(scannerCfg, w.docBuild) # write each document, in this particular order so that the # hashes for external references are calculated # write SDK document, if we made one if cfg.includeSDK: retval = writeSPDX(os.path.join(cfg.spdxDir, "sdk.spdx"), w.docSDK) if not retval: log.err("SPDX writer failed for SDK document; bailing") return False # write app document retval = writeSPDX(os.path.join(cfg.spdxDir, "app.spdx"), w.docApp) if not retval: log.err("SPDX writer failed for app document; bailing") return False # write zephyr document writeSPDX(os.path.join(cfg.spdxDir, "zephyr.spdx"), w.docZephyr) if not retval: log.err("SPDX writer failed for zephyr document; bailing") return False # write build document writeSPDX(os.path.join(cfg.spdxDir, "build.spdx"), w.docBuild) if not retval: log.err("SPDX writer failed for build document; bailing") return False return True
import rtmidi midiout = None midiin = None def connect(port = 0): global midiout, midiin midiout = rtmidi.MidiOut() midiin = rtmidi.MidiIn() available_ports = midiout.get_ports() if available_ports: midiout.open_port(port) midiin.open_port(port) else: raise Exception("Cannot connect") def set_led_color(led, color): midiout.send_message([144, led, color]) def clear_led(led): set_led_color(led, 0) def send_sysex(message_body): midiout.send_message([240, 0, 32, 41, 2, 24] + message_body + [247]) def set_all_led_color(color): send_sysex([14, color]) def clear_all_led(): set_all_led_color(0) def scroll_text(text, color, loop = False): ascii_array = [ord(c) for c in text] send_sysex([20, color, loop and 1 or 0] + ascii_array) def cancel_scroll_text(): send_sysex([20]) # cb is a function that takes two parameters ((message, time), data) def subscribe_touch(cb, data=None): midiin.set_callback(cb, data) Added blinking and pulsing import rtmidi midiout = None midiin = None def connect(port = 0): global midiout, midiin midiout = rtmidi.MidiOut() midiin = rtmidi.MidiIn() available_ports = midiout.get_ports() if available_ports: midiout.open_port(port) midiin.open_port(port) else: raise Exception("Cannot connect") def set_led_color(led, color): midiout.send_message([144, led, color]) def pulse_led(led, color): midiout.send_message([146, led, color]) def blink_led(led, color): midiout.send_message([145, led, color]) def clear_led(led): set_led_color(led, 0) def send_sysex(message_body): midiout.send_message([240, 0, 32, 41, 2, 24] + message_body + [247]) def set_all_led_color(color): send_sysex([14, color]) def clear_all_led(): set_all_led_color(0) def scroll_text(text, color, loop = False): ascii_array = [ord(c) for c in text] send_sysex([20, color, loop and 1 or 0] + ascii_array) def cancel_scroll_text(): send_sysex([20]) # cb is a function that takes two parameters ((message, time), data) def subscribe_touch(cb, data=None): midiin.set_callback(cb, data) # As an alternative to subcribe_touch(), polls for touch messages, or returns None if none are available def poll_touch(): return midiin.get_message()
# -*- coding: utf-8 -*- """ Copyright (c) 2013, 2014 Jaime Soffer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the involved organizations nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from PyQt4.QtNetwork import QNetworkCookieJar, QNetworkCookie from os.path import expanduser from tldextract import extract def format_cookie(url, cookies): """ Constructs a log message from a list of cookies and the host where they're set """ prefix = "\n< COOKIES ({}{}) ".format(url.host(), url.path()) suffix = ", ".join(["[[{}{}] {} => {}]".format(cookie.domain(), cookie.path(), cookie.name(), cookie.value()) for cookie in cookies]) return prefix + suffix class CookieJar(QNetworkCookieJar): """ Logs and intercepts cookies; part of the Network Access Manager """ def __init__(self, parent=None, options=None): """ Load cookies from a file """ super(CookieJar, self).__init__(parent) print("INIT CookieJar") if options['cookie_allow'] is None: self.allowed = [] else: self.allowed = options['cookie_allow'] self.storage = options['cookie_file'] if self.storage is not None: self.storage = expanduser("~/.eilat/cookies/") + self.storage print(self.storage) try: with open(self.storage, "r") as readfile: cookies = [QNetworkCookie.parseCookies(k) for k in readfile.readlines()] cookies = [x for y in cookies for x in y] # flatten self.setAllCookies(cookies) except IOError: print("LOAD COOKIES: empty?") def store_cookies(self): """ Saves all cookies to 'storage'; called from the NAM when it sends a 'deleted' signal """ if self.storage is not None: print("Store cookies...") with open(self.storage, "w") as savefile: for cookie in self.allCookies(): savefile.write(cookie.toRawForm().data().decode()+"\n") def set_cookies_from_url(self, cookies, url): """ Reimplementation from base class. Prevents cookies from being set if not from whitelisted domains. """ (_, domain, suffix) = extract(url.host()) site = domain + '.' + suffix if site not in self.allowed: print("COOKIE FROM {} not set".format(url.toString())) ret = [] else: print("SET COOKIE FROM {}".format(url.toString())) ret = cookies return QNetworkCookieJar.setCookiesFromUrl(self, ret, url) # Clean reimplement for Qt # pylint: disable=C0103 setCookiesFromUrl = set_cookies_from_url # pylint: enable=C0103 do not report blocked attempts to set cookies; TODO make optional # -*- coding: utf-8 -*- """ Copyright (c) 2013, 2014 Jaime Soffer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the involved organizations nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from PyQt4.QtNetwork import QNetworkCookieJar, QNetworkCookie from os.path import expanduser from tldextract import extract def format_cookie(url, cookies): """ Constructs a log message from a list of cookies and the host where they're set """ prefix = "\n< COOKIES ({}{}) ".format(url.host(), url.path()) suffix = ", ".join(["[[{}{}] {} => {}]".format(cookie.domain(), cookie.path(), cookie.name(), cookie.value()) for cookie in cookies]) return prefix + suffix class CookieJar(QNetworkCookieJar): """ Logs and intercepts cookies; part of the Network Access Manager """ def __init__(self, parent=None, options=None): """ Load cookies from a file """ super(CookieJar, self).__init__(parent) print("INIT CookieJar") if options['cookie_allow'] is None: self.allowed = [] else: self.allowed = options['cookie_allow'] self.storage = options['cookie_file'] if self.storage is not None: self.storage = expanduser("~/.eilat/cookies/") + self.storage print(self.storage) try: with open(self.storage, "r") as readfile: cookies = [QNetworkCookie.parseCookies(k) for k in readfile.readlines()] cookies = [x for y in cookies for x in y] # flatten self.setAllCookies(cookies) except IOError: print("LOAD COOKIES: empty?") def store_cookies(self): """ Saves all cookies to 'storage'; called from the NAM when it sends a 'deleted' signal """ if self.storage is not None: print("Store cookies...") with open(self.storage, "w") as savefile: for cookie in self.allCookies(): savefile.write(cookie.toRawForm().data().decode()+"\n") def set_cookies_from_url(self, cookies, url): """ Reimplementation from base class. Prevents cookies from being set if not from whitelisted domains. """ (_, domain, suffix) = extract(url.host()) site = domain + '.' + suffix if site not in self.allowed: # FIXME make optional to print this # print("COOKIE FROM {} not set".format(url.toString())) ret = [] else: print("SET COOKIE FROM {}".format(url.toString())) ret = cookies return QNetworkCookieJar.setCookiesFromUrl(self, ret, url) # Clean reimplement for Qt # pylint: disable=C0103 setCookiesFromUrl = set_cookies_from_url # pylint: enable=C0103
# Copyright (c) 2001-2015, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to the responsive locomotion way of traveling! # # LICENCE: This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Stay tuned using # twitter @navitia # IRC #navitia on freenode # https://groups.google.com/d/forum/navitia # www.navitia.io from __future__ import absolute_import, print_function, unicode_literals, division from copy import deepcopy import itertools import logging from flask.ext.restful import abort from flask import g from jormungandr.scenarios import simple, journey_filter, helpers from jormungandr.scenarios.ridesharing.ridesharing_helper import decorate_journeys from jormungandr.scenarios.utils import journey_sorter, change_ids, updated_request_with_default, \ get_or_default, fill_uris, gen_all_combin, get_pseudo_duration, mode_weight from navitiacommon import type_pb2, response_pb2, request_pb2 from jormungandr.scenarios.qualifier import min_from_criteria, arrival_crit, departure_crit, \ duration_crit, transfers_crit, nonTC_crit, trip_carac, has_no_car, has_car, has_pt, \ has_no_bike, has_bike, has_no_bss, has_bss, non_pt_journey, has_walk, and_filters import numpy as np import collections from jormungandr.utils import date_to_timestamp, PeriodExtremity, copy_flask_request_context, copy_context_in_greenlet_stack from jormungandr.scenarios.simple import get_pb_data_freshness import gevent, gevent.pool import flask from jormungandr import app from jormungandr.autocomplete.geocodejson import GeocodeJson from jormungandr import global_autocomplete from six.moves import filter from six.moves import range from six.moves import zip SECTION_TYPES_TO_RETAIN = {response_pb2.PUBLIC_TRANSPORT, response_pb2.STREET_NETWORK} JOURNEY_TYPES_TO_RETAIN = ['best', 'comfort', 'non_pt_walk', 'non_pt_bike', 'non_pt_bss'] STREET_NETWORK_MODE_TO_RETAIN = {response_pb2.Ridesharing, response_pb2.Car, response_pb2.Bike, response_pb2.Bss} def get_kraken_calls(request): """ return a list of tuple (departure fallback mode, arrival fallback mode) from the request dict. for the moment it's a simple stuff: if there is only one elt in {first|last}_section_mode we take those else we do the cartesian product and remove forbidden association. The good thing to do would be to have API param to be able to better handle this """ dep_modes = request['origin_mode'] arr_modes = request['destination_mode'] if len(dep_modes) == len(arr_modes) == 1: return [(dep_modes[0], arr_modes[0])] # this allowed combination is temporary, it does not handle all the use cases at all allowed_combination = [('bss', 'bss'), ('walking', 'walking'), ('bike', 'walking'), ('car', 'walking'), ('bike', 'bss'), ('car', 'bss'), ('bike', 'bike'), ('ridesharing', 'walking'), ('walking', 'ridesharing'), ('ridesharing', 'bss'), ('bss', 'ridesharing')] # We don't want to do ridesharing - ridesharing journeys res = [c for c in allowed_combination if c in itertools.product(dep_modes, arr_modes)] if not res: abort(404, message='the asked first_section_mode[] ({}) and last_section_mode[] ' '({}) combination is not yet supported'.format(dep_modes, arr_modes)) return res def create_pb_request(requested_type, request, dep_mode, arr_mode): """Parse the request dict and create the protobuf version""" #TODO: bench if the creation of the request each time is expensive req = request_pb2.Request() req.requested_api = requested_type req._current_datetime = date_to_timestamp(request['_current_datetime']) if "origin" in request and request["origin"]: if requested_type != type_pb2.NMPLANNER: origins, durations = ([request["origin"]], [0]) else: # in the n-m query, we have several origin points, with their corresponding access duration origins, durations = (request["origin"], request["origin_access_duration"]) for place, duration in zip(origins, durations): location = req.journeys.origin.add() location.place = place location.access_duration = duration if "destination" in request and request["destination"]: if requested_type != type_pb2.NMPLANNER: destinations, durations = ([request["destination"]], [0]) else: destinations, durations = (request["destination"], request["destination_access_duration"]) for place, duration in zip(destinations, durations): location = req.journeys.destination.add() location.place = place location.access_duration = duration req.journeys.datetimes.append(request["datetime"]) #TODO remove this datetime list completly in another PR req.journeys.clockwise = request["clockwise"] sn_params = req.journeys.streetnetwork_params sn_params.max_walking_duration_to_pt = request["max_walking_duration_to_pt"] sn_params.max_bike_duration_to_pt = request["max_bike_duration_to_pt"] sn_params.max_bss_duration_to_pt = request["max_bss_duration_to_pt"] sn_params.max_car_duration_to_pt = request["max_car_duration_to_pt"] sn_params.max_car_no_park_duration_to_pt = request["max_car_no_park_duration_to_pt"] sn_params.walking_speed = request["walking_speed"] sn_params.bike_speed = request["bike_speed"] sn_params.car_speed = request["car_speed"] sn_params.bss_speed = request["bss_speed"] sn_params.car_no_park_speed = request["car_no_park_speed"] sn_params.origin_filter = request.get("origin_filter", "") sn_params.destination_filter = request.get("destination_filter", "") #we always want direct path, even for car sn_params.enable_direct_path = True #settings fallback modes sn_params.origin_mode = dep_mode sn_params.destination_mode = arr_mode req.journeys.max_duration = request["max_duration"] req.journeys.max_transfers = request["max_transfers"] if request["max_extra_second_pass"]: req.journeys.max_extra_second_pass = request["max_extra_second_pass"] req.journeys.wheelchair = request["wheelchair"] or False # default value is no wheelchair req.journeys.realtime_level = get_pb_data_freshness(request) if "details" in request and request["details"]: req.journeys.details = request["details"] req.journeys.walking_transfer_penalty = request['_walking_transfer_penalty'] for forbidden_uri in get_or_default(request, "forbidden_uris[]", []): req.journeys.forbidden_uris.append(forbidden_uri) for allowed_id in get_or_default(request, "allowed_id[]", []): req.journeys.allowed_id.append(allowed_id) req.journeys.bike_in_pt = (dep_mode == 'bike') and (arr_mode == 'bike') if request["free_radius_from"]: req.journeys.free_radius_from = request["free_radius_from"] if request["free_radius_to"]: req.journeys.free_radius_to = request["free_radius_to"] if request["min_nb_journeys"]: req.journeys.min_nb_journeys = request["min_nb_journeys"] req.journeys.night_bus_filter_max_factor = request['_night_bus_filter_max_factor'] req.journeys.night_bus_filter_base_factor = request['_night_bus_filter_base_factor'] return req def _has_pt(j): return any(s.type == response_pb2.PUBLIC_TRANSPORT for s in j.sections) def sort_journeys(resp, journey_order, clockwise): if resp.journeys: resp.journeys.sort(journey_sorter[journey_order](clockwise=clockwise)) def compute_car_co2_emission(pb_resp, api_request, instance): if not pb_resp.journeys: return car = next((j for j in pb_resp.journeys if helpers.is_car_direct_path(j)), None) if car is None or not car.HasField('co2_emission'): # if there is no car journey found, we request kraken to give us an estimation of # co2 emission co2_estimation = instance.georef.get_car_co2_emission_on_crow_fly(api_request['origin'], api_request['destination']) if co2_estimation: # Assign car_co2_emission into the resp, these value will be exposed in the final result pb_resp.car_co2_emission.value = co2_estimation.value pb_resp.car_co2_emission.unit = co2_estimation.unit else: # Assign car_co2_emission into the resp, these value will be exposed in the final result pb_resp.car_co2_emission.value = car.co2_emission.value pb_resp.car_co2_emission.unit = car.co2_emission.unit def tag_ecologic(resp): # if there is no available car_co2_emission in resp, no tag will be assigned if resp.car_co2_emission.value and resp.car_co2_emission.unit: for j in resp.journeys: if not j.HasField('co2_emission'): j.tags.append('ecologic') continue if j.co2_emission.unit != resp.car_co2_emission.unit: continue if j.co2_emission.value < resp.car_co2_emission.value * 0.5: j.tags.append('ecologic') def _tag_direct_path(responses): street_network_mode_tag_map = {response_pb2.Walking: ['non_pt_walking'], response_pb2.Bike: ['non_pt_bike']} for j in itertools.chain.from_iterable(r.journeys for r in responses): if all(s.type != response_pb2.PUBLIC_TRANSPORT for s in j.sections): j.tags.extend(['non_pt']) # TODO: remove that (and street_network_mode_tag_map) when NMP stops using it # if there is only one section if len(j.sections) == 1: if j.sections[0].type == response_pb2.STREET_NETWORK and hasattr(j.sections[0], 'street_network'): tag = street_network_mode_tag_map.get(j.sections[0].street_network.mode) if tag: j.tags.extend(tag) def _is_bike_section(s): return ((s.type == response_pb2.CROW_FLY or s.type == response_pb2.STREET_NETWORK) and s.street_network.mode == response_pb2.Bike) def _is_pt_bike_accepted_section(s): bike_ok = type_pb2.hasEquipments.has_bike_accepted return (s.type == response_pb2.PUBLIC_TRANSPORT and bike_ok in s.pt_display_informations.has_equipments.has_equipments and bike_ok in s.origin.stop_point.has_equipments.has_equipments and bike_ok in s.destination.stop_point.has_equipments.has_equipments) def _is_bike_in_pt_journey(j): bike_indifferent = [response_pb2.boarding, response_pb2.landing, response_pb2.WAITING, response_pb2.TRANSFER, response_pb2.ALIGHTING] return _has_pt(j) and \ all(_is_bike_section(s) or _is_pt_bike_accepted_section(s) or s.type in bike_indifferent for s in j.sections) def _tag_bike_in_pt(responses): ''' we tag as 'bike _in_pt' journeys that are using bike as start AND end fallback AND that allow carrying bike in transport (and journey has to include PT) ''' for j in itertools.chain.from_iterable(r.journeys for r in responses): if _is_bike_in_pt_journey(j): j.tags.extend(['bike_in_pt']) def tag_journeys(resp): """ tag the journeys """ tag_ecologic(resp) def _get_section_id(section): street_network_mode = None if section.type in SECTION_TYPES_TO_RETAIN: if getattr(section.street_network, 'mode', None) in STREET_NETWORK_MODE_TO_RETAIN: street_network_mode = section.street_network.mode return section.uris.line, street_network_mode, section.type def _build_candidate_pool_and_sections_set(resp): sections_set = set() candidates_pool = list() idx_of_jrny_must_keep = list() for (i, jrny) in enumerate(resp.journeys): if jrny.type in JOURNEY_TYPES_TO_RETAIN: idx_of_jrny_must_keep.append(i) sections_set |= set([_get_section_id(s) for s in jrny.sections if s.type in SECTION_TYPES_TO_RETAIN]) candidates_pool.append(jrny) return np.array(candidates_pool), sections_set, idx_of_jrny_must_keep def _build_selected_sections_matrix(sections_set, candidates_pool): sections_2_index_dict = dict() for index, value in enumerate(sections_set): sections_2_index_dict[value] = index selected_sections_matrix = list() nb_sections = len(sections_set) for j in candidates_pool: section_select = np.zeros(nb_sections, dtype=int) def _gen_section_ind(): for s in j.sections: ind = sections_2_index_dict.get(_get_section_id(s)) if ind is not None: yield ind selected_indexes = list(_gen_section_ind()) section_select[selected_indexes] = 1 selected_sections_matrix.append(section_select) return np.array(selected_sections_matrix) def _get_sorted_solutions_indexes(selected_sections_matrix, nb_journeys_to_find, idx_of_jrny_must_keep): """ The entry is a 2D array where its lines are journeys, its columns are (non) chosen sections """ logger = logging.getLogger(__name__) """ Get a matrix which illustrate all possible non ordered combinations of t elements from n elements where n >= t with their indexes. Let's say we'd like to find all combinations of 2 elements from a set of 3. selected_journeys_matrix will be like: [[0,1] [0,2] [1,2]] """ selected_journeys_matrix = np.array(list(gen_all_combin(selected_sections_matrix.shape[0], nb_journeys_to_find))) """ We should cut out those combinations that don't contain must-keep journeys """ def _contains(idx_selected_jrny): return set(idx_selected_jrny).issuperset(idx_of_jrny_must_keep) selected_journeys_matrix = selected_journeys_matrix[np.apply_along_axis(_contains, 1, selected_journeys_matrix)] selection_matrix = np.zeros((selected_journeys_matrix.shape[0], selected_sections_matrix.shape[0])) """ Given selected_journeys_matrix: [[0,1] [0,2] [1,2]] selection_matrix will be like: [[1,1,0], -> the first one and the second are chosen, etc... [1,0,1], [0,1,1]] """ # http://stackoverflow.com/questions/20103779/index-2d-numpy-array-by-a-2d-array-of-indices-without-loops selection_matrix[np.arange(selected_journeys_matrix.shape[0])[:, None], selected_journeys_matrix] = 1 res_pool = np.dot(selection_matrix, selected_sections_matrix) """ Get number of sections(or tranfers) for every solution """ nb_sections = np.sum(res_pool, axis=1) """ integrity shows at which point a solution(chosen journeys) covers sections. 0 means a solution covers all sections 1 means a solutions covers almost all sections but 1 is missing 2 means 2 sections are missing .... etc """ integrity = res_pool.shape[1] - np.array([np.count_nonzero(r) for r in res_pool]) """ We want to find the solutions covers as many sections as possible which has less sections(less transfer to do) """ the_best_idx = np.lexsort((nb_sections, integrity))[0] # sort by integrity then by nb_sections best_indexes = np.where(np.logical_and(nb_sections == nb_sections[the_best_idx], integrity == integrity[the_best_idx]))[0] logger.debug("Best Itegrity: {0}".format(integrity[the_best_idx])) logger.debug("Best Nb sections: {0}".format(nb_sections[the_best_idx])) return best_indexes, selection_matrix def culling_journeys(resp, request): """ Remove some journeys if there are too many of them to have max_nb_journeys journeys. resp.journeys should be sorted before this function is called The goal is to choose a bunch of journeys(max_nv_journeys) that covers as many as possible sections but have as few as possible sum(sections) Ex: From: Journey_1 : Line 1 -> Line 8 -> Bus 172 Journey_2 : Line 14 -> Line 6 -> Bus 165 Journey_3 : Line 14 -> Line 6 ->Line 8 -> Bus 165 W'd like to choose two journeys. The algo will return Journey_1 and Journey2. Because With Journey_1 and Journey_3, they cover all lines but have 5 transfers in all With Journey_2 and Journey_3, they don't cover all lines(Line 1 is missing) and have 5 transfers in all With Journey_1 and Journey_2, they cover all lines and have only 4 transfers in all -> OK No removing done in debug """ logger = logging.getLogger(__name__) if not request["max_nb_journeys"] or request["max_nb_journeys"] >= len(resp.journeys): logger.debug('No need to cull journeys') return logger.debug('Trying to culling the journeys') """ To create a candidates pool, we choose only journeys that are NOT tagged as 'comfort' and 'best' and we create a section set from that pool Ex: Journey_1 (Best): Line 14 -> Line 8 -> Bus 172 Journey_2 : Line 14 -> Line 6 -> Bus 165 Journey_3 : Line 14 -> Line 8 -> Bus 165 The candidate pool will be like [Journey_2, Journey_3] The sections set will be like set([Line 14, Line 6, Line 8, Bus 165]) """ candidates_pool, sections_set, idx_of_jrnys_must_keep = _build_candidate_pool_and_sections_set(resp) nb_journeys_must_have = len(idx_of_jrnys_must_keep) logger.debug("There are {0} journeys we must keep".format(nb_journeys_must_have)) is_debug = request.get('debug') if (request["max_nb_journeys"] - nb_journeys_must_have) <= 0: # At this point, max_nb_journeys is smaller than nb_journeys_must_have, we have to make choices def _inverse_selection(d, indexes): select = np.in1d(list(range(d.shape[0])), indexes) return d[~select] # Here we mark all journeys as dead that are not must-have for jrny in _inverse_selection(candidates_pool, idx_of_jrnys_must_keep): journey_filter.mark_as_dead(jrny, is_debug, 'Filtered by max_nb_journeys') if request["max_nb_journeys"] == nb_journeys_must_have: logger.debug('max_nb_journeys equals to nb_journeys_must_have') journey_filter.delete_journeys((resp,), request) return logger.debug('max_nb_journeys:{0} is smaller than nb_journeys_must_have:{1}' .format(request["max_nb_journeys"], nb_journeys_must_have)) # At this point, resp.journeys should contain only must-have journeys list_dict = collections.defaultdict(list) for jrny in resp.journeys: if not journey_filter.to_be_deleted(jrny): list_dict[jrny.type].append(jrny) sorted_by_type_journeys = [] for t in JOURNEY_TYPES_TO_RETAIN: sorted_by_type_journeys.extend(list_dict.get(t, [])) for jrny in sorted_by_type_journeys[request["max_nb_journeys"]:]: journey_filter.mark_as_dead(jrny, is_debug, 'Filtered by max_nb_journeys') journey_filter.delete_journeys((resp,), request) return nb_journeys_to_find = request["max_nb_journeys"] logger.debug('Trying to find {0} journeys from {1}'.format(nb_journeys_to_find, candidates_pool.shape[0])) """ Ex: Journey_2 : Line 14 -> Line 6 -> Bus 165 Journey_3 : Line 14 -> Line 8 -> Bus 165 The candidate pool will be like [Journey_2, Journey_3] The sections set will be like set([Line 14, Line 6, Line 8, Bus 165]) selected_sections_matrix: [[1,1,0,1] -> journey_2 [1,0,1,1] -> journey_3 ] """ selected_sections_matrix = _build_selected_sections_matrix(sections_set, candidates_pool) best_indexes, selection_matrix = _get_sorted_solutions_indexes(selected_sections_matrix, nb_journeys_to_find, idx_of_jrnys_must_keep) logger.debug("Nb best solutions: {0}".format(best_indexes.shape[0])) the_best_index = best_indexes[0] logger.debug("Trying to find the best of best") """ Let's find the best of best :) """ # If there're several solutions which have the same score of integrity and nb_sections if best_indexes.shape[0] != 1: requested_dt = request['datetime'] is_clockwise = request.get('clockwise', True) def combinations_sorter(v): # Hoping to find We sort the solution by the sum of journeys' pseudo duration return np.sum((get_pseudo_duration(jrny, requested_dt, is_clockwise) for jrny in np.array(candidates_pool)[np.where(selection_matrix[v, :])])) the_best_index = min(best_indexes, key=combinations_sorter) logger.debug('Removing non selected journeys') for jrny in candidates_pool[np.where(selection_matrix[the_best_index, :] == 0)]: journey_filter.mark_as_dead(jrny, is_debug, 'Filtered by max_nb_journeys') journey_filter.delete_journeys((resp,), request) def _tag_journey_by_mode(journey): mode = 'walking' for i, section in enumerate(journey.sections): cur_mode = 'walking' if ((section.type == response_pb2.BSS_RENT) or (section.type == response_pb2.CROW_FLY and section.street_network.mode == response_pb2.Bss)): cur_mode = 'bss' elif ((section.type == response_pb2.STREET_NETWORK or section.type == response_pb2.CROW_FLY) and section.street_network.mode == response_pb2.Bike and journey.sections[i - 1].type != response_pb2.BSS_RENT): cur_mode = 'bike' elif ((section.type == response_pb2.STREET_NETWORK or section.type == response_pb2.CROW_FLY) and section.street_network.mode == response_pb2.Car): cur_mode = 'car' elif ((section.type == response_pb2.STREET_NETWORK or section.type == response_pb2.CROW_FLY) and section.street_network.mode == response_pb2.Ridesharing): # When the street network data is missing, the section maybe a crow_fly cur_mode = 'ridesharing' if mode_weight[mode] < mode_weight[cur_mode]: mode = cur_mode journey.tags.append(mode) def _tag_by_mode(responses): for r in responses: for j in r.journeys: _tag_journey_by_mode(j) def _is_fake_car_section(section): """ This function test if the section is a fake car section """ return (section.type == response_pb2.STREET_NETWORK or section.type == response_pb2.CROW_FLY) and \ section.street_network.mode == response_pb2.Car def _switch_back_to_ridesharing(response, is_first_section): """ :param response: a pb_response returned by kraken :param is_first_section: a bool indicates that if the first_section or last_section is a ridesharing section True if the first_section is, False if the last_section is :return: """ for journey in response.journeys: if len(journey.sections) == 0: continue section_idx = 0 if is_first_section else -1 section = journey.sections[section_idx] if _is_fake_car_section(section): section.street_network.mode = response_pb2.Ridesharing journey.durations.ridesharing += section.duration journey.durations.car -= section.duration journey.distances.ridesharing += section.length journey.distances.car -= section.length def nb_journeys(responses): return sum(1 for r in responses for j in r.journeys if not journey_filter.to_be_deleted(j)) def type_journeys(resp, req): """ Set the type of the journeys """ best_crit = arrival_crit if req["clockwise"] else departure_crit # first, we want a type for every journey. Just pick "rapid" by default. for j in resp.journeys: j.type = "rapid" # Then, we want something like the old types trip_caracs = [ # comfort tends to limit the number of transfers and fallback ("comfort", trip_carac([ has_no_car, ], [ transfers_crit, nonTC_crit, best_crit, duration_crit ])), # for car we want at most one journey, the earliest one ("car", trip_carac([ has_car, has_pt, # We don't want car only solution, we MUST have PT ], [ best_crit, transfers_crit, nonTC_crit, duration_crit ])), # less_fallback tends to limit the fallback while walking ("less_fallback_walk", trip_carac([ has_no_car, has_no_bike, ], [ nonTC_crit, transfers_crit, duration_crit, best_crit, ])), # less_fallback tends to limit the fallback for biking and bss ("less_fallback_bike", trip_carac([ has_no_car, has_bike, has_no_bss, ], [ nonTC_crit, transfers_crit, duration_crit, best_crit, ])), # less_fallback tends to limit the fallback for biking and bss ("less_fallback_bss", trip_carac([ has_no_car, has_bss, ], [ nonTC_crit, transfers_crit, duration_crit, best_crit, ])), # the fastest is quite explicit ("fastest", trip_carac([ has_no_car, ], [ duration_crit, transfers_crit, nonTC_crit, best_crit, ])), # the non_pt journeys is the earliest journey without any public transport ("non_pt_walk", trip_carac([ non_pt_journey, has_no_car, has_walk ], [ best_crit ])), # the non_pt journey is the earliest journey without any public transport # only walking, biking or driving ("non_pt_bike", trip_carac([ non_pt_journey, has_no_car, has_bike ], [ best_crit ])), ("non_pt_bss", trip_carac([ non_pt_journey, has_no_car, has_bss, ], [ best_crit ])), ("non_pt_car", trip_carac([ non_pt_journey, has_car, ], [ best_crit ])), ] for name, carac in trip_caracs: sublist = list(filter(and_filters(carac.constraints), resp.journeys)) best = min_from_criteria(sublist, carac.criteria) if best is not None: best.type = name # Finally, we want exactly one best, the ASAP one best = min_from_criteria(resp.journeys, [best_crit, duration_crit, transfers_crit, nonTC_crit]) if best is not None: best.type = "best" def merge_responses(responses): """ Merge all responses in one protobuf response """ merged_response = response_pb2.Response() for r in responses: if r.HasField(str('error')) or not r.journeys: # we do not take responses with error, but if all responses have errors, we'll aggregate them continue change_ids(r, len(merged_response.journeys)) # we don't want to add a journey already there merged_response.journeys.extend(r.journeys) # we have to add the additional fares too # if at least one journey has the ticket we add it tickets_to_add = set(t for j in r.journeys for t in j.fare.ticket_id) merged_response.tickets.extend((t for t in r.tickets if t.id in tickets_to_add)) initial_feed_publishers = {} for fp in merged_response.feed_publishers: initial_feed_publishers[fp.id] = fp merged_response.feed_publishers.extend((fp for fp in r.feed_publishers if fp.id not in initial_feed_publishers)) # handle impacts for i in r.impacts: if any(other.uri == i.uri for other in merged_response.impacts): continue merged_response.impacts.extend([i]) if not merged_response.journeys: # we aggregate the errors found errors = {r.error.id: r.error for r in responses if r.HasField(str('error'))} # Only one errors field if len(errors) == 1: merged_response.error.id = list(errors.values())[0].id merged_response.error.message = list(errors.values())[0].message # we need to merge the errors elif len(errors) > 1: merged_response.error.id = response_pb2.Error.no_solution merged_response.error.message = "several errors occured: \n * {}"\ .format("\n * ".join([m.message for m in errors.values()])) return merged_response def get_kraken_id(entrypoint_detail): """ returns a usable id for kraken from the entrypoint detail returns None if the original ID needs to be kept """ if not entrypoint_detail: # impossible to find the object return None emb_type = entrypoint_detail.get('embedded_type') if emb_type in ('stop_point', 'stop_area', 'administrative_region'): # for those object, we need to keep the original id, as there are specific treatment to be done return None # for the other objects the id is the object coordinated coord = entrypoint_detail.get(emb_type, {}).get('coord') if not coord: # no coordinate, we keep the original id return None return '{};{}'.format(coord['lon'], coord['lat']) class Scenario(simple.Scenario): """ TODO: a bit of explanation about the new scenario """ def __init__(self): super(Scenario, self).__init__() self.nb_kraken_calls = 0 def fill_journeys(self, request_type, api_request, instance): logger = logging.getLogger(__name__) # sometimes we need to change the entrypoint id (eg if the id is from another autocomplete system) origin_detail = self.get_entrypoint_detail(api_request.get('origin'), instance) destination_detail = self.get_entrypoint_detail(api_request.get('destination'), instance) # we store the origin/destination detail in g to be able to use them after the marshall g.origin_detail = origin_detail g.destination_detail = destination_detail api_request['origin'] = get_kraken_id(origin_detail) or api_request.get('origin') api_request['destination'] = get_kraken_id(destination_detail) or api_request.get('destination') # building ridesharing request from "original" request ridesharing_req = deepcopy(api_request) if not api_request['origin_mode']: api_request['origin_mode'] = ['walking'] if not api_request['destination_mode']: api_request['destination_mode'] = ['walking'] # Return the possible couples combinations (origin_mode and destination_mode) krakens_call = get_kraken_calls(api_request) # min_nb_journeys option if api_request['min_nb_journeys']: min_nb_journeys = api_request['min_nb_journeys'] else: min_nb_journeys = api_request['min_nb_journeys'] = 1 # We need the original request (api_request) for filtering, but request # is modified by create_next_kraken_request function. request = deepcopy(api_request) min_journeys_calls = get_or_default(request, '_min_journeys_calls', 1) responses = [] nb_try = 0 nb_qualified_journeys = 0 while request is not None and \ ((nb_qualified_journeys < min_nb_journeys and nb_try < min_nb_journeys) \ or nb_try < min_journeys_calls): nb_try = nb_try + 1 # we take into account the option only if we have one origin_mode and destination_mode couple. if len(krakens_call) > 1: request['min_nb_journeys'] = 0 else: min_nb_journeys_left = min_nb_journeys - nb_qualified_journeys request['min_nb_journeys'] = max(0, min_nb_journeys_left) new_resp = self.call_kraken(request_type, request, instance, krakens_call) _tag_by_mode(new_resp) _tag_direct_path(new_resp) _tag_bike_in_pt(new_resp) journey_filter._filter_too_late_journeys(new_resp, request) if nb_journeys(new_resp) == 0: # no new journeys found, we stop # we still append the new_resp because there are journeys that a tagged as dead probably responses.extend(new_resp) break request = self.create_next_kraken_request(request, new_resp) # we filter unwanted journeys in the new response # note that filter_journeys returns a generator which will be evaluated later filtered_new_resp = journey_filter.filter_journeys(new_resp, instance, api_request) # duplicate the generator tmp1, tmp2 = itertools.tee(filtered_new_resp) qualified_journeys = journey_filter.get_qualified_journeys(responses) # now we want to filter similar journeys in the new response which is done in 2 steps # In the first step, we compare journeys from the new response only , 2 by 2 # hopefully, it may lead to some early return for the second step to improve the perf a little # In the second step, we compare the journeys from the new response with those that have been qualified # already in the former iterations # note that the journeys_pool is a list of 2-element tuple of journeys journeys_pool = itertools.chain( # First step: compare journeys from the new response only itertools.combinations(tmp1, 2), # Second step: # we use the itertools.product to create combinations between qualified journeys and new journeys # Ex: # new_journeys = [n_1, n_2] # qualified_journeys = [q_1, q_2, q_3] # itertools.product(new_journeys, qualified_journeys) gives combinations as follows: # (n_1, q_1), (n_1, q_2),(n_1, q_3),(n_2, q_1),(n_2, q_2),(n_2, q_3) itertools.product(tmp2, qualified_journeys), ) pool1, pool2 = itertools.tee(journeys_pool) journey_filter.filter_similar_vj_journeys(pool1, api_request) if api_request['no_shared_section']: journey_filter.filter_shared_sections_journeys(pool2, api_request) responses.extend(new_resp) # we keep the error for building the response nb_qualified_journeys = nb_journeys(responses) # We allow one more call to kraken if there is no valid journey. if nb_qualified_journeys == 0: min_journeys_calls = max(min_journeys_calls, 2) logger.debug('nb of call kraken: %i', nb_try) journey_filter.final_filter_journeys(responses, instance, api_request) pb_resp = merge_responses(responses) sort_journeys(pb_resp, instance.journey_order, api_request['clockwise']) compute_car_co2_emission(pb_resp, api_request, instance) tag_journeys(pb_resp) if instance.ridesharing_services and \ ('ridesharing' in ridesharing_req['origin_mode'] or 'ridesharing' in ridesharing_req['destination_mode']): logger.debug('trying to add ridesharing journeys') try: decorate_journeys(pb_resp, instance, api_request) except Exception: logger.exception('Error while retrieving ridesharing ads') else: for j in pb_resp.journeys: if 'ridesharing' in j.tags: journey_filter.mark_as_dead(j, api_request.get('debug'), 'no_matching_ridesharing_found') journey_filter.delete_journeys((pb_resp,), api_request) type_journeys(pb_resp, api_request) culling_journeys(pb_resp, api_request) self._compute_pagination_links(pb_resp, instance, api_request['clockwise']) return pb_resp def call_kraken(self, request_type, request, instance, krakens_call): """ For all krakens_call, call the kraken and aggregate the responses return the list of all responses """ # TODO: handle min_alternative_journeys # TODO: call first bss|bss and do not call walking|walking if no bss in first results resp = [] logger = logging.getLogger(__name__) futures = [] reqctx = copy_flask_request_context() def worker(dep_mode, arr_mode, instance, request, flask_request_id): with copy_context_in_greenlet_stack(reqctx): return (dep_mode, arr_mode, instance.send_and_receive(request, flask_request_id=flask_request_id)) pool = gevent.pool.Pool(app.config.get('GREENLET_POOL_SIZE', 3)) for dep_mode, arr_mode in krakens_call: pb_request = create_pb_request(request_type, request, dep_mode, arr_mode) # we spawn a new greenlet, it won't have access to our thread local request object so we pass the request_id futures.append(pool.spawn(worker, dep_mode, arr_mode, instance, pb_request, flask_request_id=flask.request.id)) for future in gevent.iwait(futures): dep_mode, arr_mode, local_resp = future.get() # for log purpose we put and id in each journeys self.nb_kraken_calls += 1 for idx, j in enumerate(local_resp.journeys): j.internal_id = "{resp}-{j}".format(resp=self.nb_kraken_calls, j=idx) if dep_mode == 'ridesharing': _switch_back_to_ridesharing(local_resp, True) if arr_mode == 'ridesharing': _switch_back_to_ridesharing(local_resp, False) fill_uris(local_resp) resp.append(local_resp) logger.debug("for mode %s|%s we have found %s journeys", dep_mode, arr_mode, len(local_resp.journeys)) return resp def __on_journeys(self, requested_type, request, instance): updated_request_with_default(request, instance) # call to kraken resp = self.fill_journeys(requested_type, request, instance) return resp def journeys(self, request, instance): return self.__on_journeys(type_pb2.PLANNER, request, instance) def isochrone(self, request, instance): updated_request_with_default(request, instance) #we don't want to filter anything! krakens_call = get_kraken_calls(request) resp = merge_responses(self.call_kraken(type_pb2.ISOCHRONE, request, instance, krakens_call)) if not request['debug']: # on isochrone we can filter the number of max journeys if request["max_nb_journeys"] and len(resp.journeys) > request["max_nb_journeys"]: del resp.journeys[request["max_nb_journeys"]:] return resp def create_next_kraken_request(self, request, responses): """ modify the request to call the next (resp previous for non clockwise search) journeys in kraken to do that we find ask the next (resp previous) query datetime """ # If Kraken send a new request date time, we use it # for the next call to skip current Journeys if responses and responses[0].HasField('next_request_date_time'): request['datetime'] = responses[0].next_request_date_time else: vjs = journey_filter.get_qualified_journeys(responses) if request["clockwise"]: request['datetime'] = self.next_journey_datetime(vjs, request["clockwise"]) else: request['datetime'] = self.previous_journey_datetime(vjs, request["clockwise"]) if request['datetime'] is None: logger = logging.getLogger(__name__) logger.error("In response next_request_date_time does not exist") return None #TODO forbid ODTs return request @staticmethod def __get_best_for_criteria(journeys, criteria): return min_from_criteria(filter(has_pt, journeys), [criteria, duration_crit, transfers_crit, nonTC_crit]) def get_best(self, journeys, clockwise): if clockwise: return self.__get_best_for_criteria(journeys, arrival_crit) else: return self.__get_best_for_criteria(journeys, departure_crit) def next_journey_datetime(self, journeys, clockwise): """ to get the next journey, we add one second to the departure of the 'best found' journey """ best = self.get_best(journeys, clockwise) if best is None: return None one_second = 1 return best.departure_date_time + one_second def previous_journey_datetime(self, journeys, clockwise): """ to get the next journey, we add one second to the arrival of the 'best found' journey """ best = self.get_best(journeys, clockwise) if best is None: return None one_second = 1 return best.arrival_date_time - one_second def get_entrypoint_detail(self, entrypoint, instance): logging.debug("calling autocomplete {} for {}".format(instance.autocomplete, entrypoint)) detail = instance.autocomplete.get_object_by_uri(entrypoint, instances=[instance]) if detail: return detail if not isinstance(instance.autocomplete, GeocodeJson): bragi = global_autocomplete.get('bragi') if bragi: # if the instance's autocomplete is not a geocodejson autocomplete, we also check in the # global autocomplete instance return bragi.get_object_by_uri(entrypoint, instances=[instance]) return None Supress too late journey filter in jormun # Copyright (c) 2001-2015, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to the responsive locomotion way of traveling! # # LICENCE: This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Stay tuned using # twitter @navitia # IRC #navitia on freenode # https://groups.google.com/d/forum/navitia # www.navitia.io from __future__ import absolute_import, print_function, unicode_literals, division from copy import deepcopy import itertools import logging from flask.ext.restful import abort from flask import g from jormungandr.scenarios import simple, journey_filter, helpers from jormungandr.scenarios.ridesharing.ridesharing_helper import decorate_journeys from jormungandr.scenarios.utils import journey_sorter, change_ids, updated_request_with_default, \ get_or_default, fill_uris, gen_all_combin, get_pseudo_duration, mode_weight from navitiacommon import type_pb2, response_pb2, request_pb2 from jormungandr.scenarios.qualifier import min_from_criteria, arrival_crit, departure_crit, \ duration_crit, transfers_crit, nonTC_crit, trip_carac, has_no_car, has_car, has_pt, \ has_no_bike, has_bike, has_no_bss, has_bss, non_pt_journey, has_walk, and_filters import numpy as np import collections from jormungandr.utils import date_to_timestamp, PeriodExtremity, copy_flask_request_context, copy_context_in_greenlet_stack from jormungandr.scenarios.simple import get_pb_data_freshness import gevent, gevent.pool import flask from jormungandr import app from jormungandr.autocomplete.geocodejson import GeocodeJson from jormungandr import global_autocomplete from six.moves import filter from six.moves import range from six.moves import zip SECTION_TYPES_TO_RETAIN = {response_pb2.PUBLIC_TRANSPORT, response_pb2.STREET_NETWORK} JOURNEY_TYPES_TO_RETAIN = ['best', 'comfort', 'non_pt_walk', 'non_pt_bike', 'non_pt_bss'] STREET_NETWORK_MODE_TO_RETAIN = {response_pb2.Ridesharing, response_pb2.Car, response_pb2.Bike, response_pb2.Bss} def get_kraken_calls(request): """ return a list of tuple (departure fallback mode, arrival fallback mode) from the request dict. for the moment it's a simple stuff: if there is only one elt in {first|last}_section_mode we take those else we do the cartesian product and remove forbidden association. The good thing to do would be to have API param to be able to better handle this """ dep_modes = request['origin_mode'] arr_modes = request['destination_mode'] if len(dep_modes) == len(arr_modes) == 1: return [(dep_modes[0], arr_modes[0])] # this allowed combination is temporary, it does not handle all the use cases at all allowed_combination = [('bss', 'bss'), ('walking', 'walking'), ('bike', 'walking'), ('car', 'walking'), ('bike', 'bss'), ('car', 'bss'), ('bike', 'bike'), ('ridesharing', 'walking'), ('walking', 'ridesharing'), ('ridesharing', 'bss'), ('bss', 'ridesharing')] # We don't want to do ridesharing - ridesharing journeys res = [c for c in allowed_combination if c in itertools.product(dep_modes, arr_modes)] if not res: abort(404, message='the asked first_section_mode[] ({}) and last_section_mode[] ' '({}) combination is not yet supported'.format(dep_modes, arr_modes)) return res def create_pb_request(requested_type, request, dep_mode, arr_mode): """Parse the request dict and create the protobuf version""" #TODO: bench if the creation of the request each time is expensive req = request_pb2.Request() req.requested_api = requested_type req._current_datetime = date_to_timestamp(request['_current_datetime']) if "origin" in request and request["origin"]: if requested_type != type_pb2.NMPLANNER: origins, durations = ([request["origin"]], [0]) else: # in the n-m query, we have several origin points, with their corresponding access duration origins, durations = (request["origin"], request["origin_access_duration"]) for place, duration in zip(origins, durations): location = req.journeys.origin.add() location.place = place location.access_duration = duration if "destination" in request and request["destination"]: if requested_type != type_pb2.NMPLANNER: destinations, durations = ([request["destination"]], [0]) else: destinations, durations = (request["destination"], request["destination_access_duration"]) for place, duration in zip(destinations, durations): location = req.journeys.destination.add() location.place = place location.access_duration = duration req.journeys.datetimes.append(request["datetime"]) #TODO remove this datetime list completly in another PR req.journeys.clockwise = request["clockwise"] sn_params = req.journeys.streetnetwork_params sn_params.max_walking_duration_to_pt = request["max_walking_duration_to_pt"] sn_params.max_bike_duration_to_pt = request["max_bike_duration_to_pt"] sn_params.max_bss_duration_to_pt = request["max_bss_duration_to_pt"] sn_params.max_car_duration_to_pt = request["max_car_duration_to_pt"] sn_params.max_car_no_park_duration_to_pt = request["max_car_no_park_duration_to_pt"] sn_params.walking_speed = request["walking_speed"] sn_params.bike_speed = request["bike_speed"] sn_params.car_speed = request["car_speed"] sn_params.bss_speed = request["bss_speed"] sn_params.car_no_park_speed = request["car_no_park_speed"] sn_params.origin_filter = request.get("origin_filter", "") sn_params.destination_filter = request.get("destination_filter", "") #we always want direct path, even for car sn_params.enable_direct_path = True #settings fallback modes sn_params.origin_mode = dep_mode sn_params.destination_mode = arr_mode req.journeys.max_duration = request["max_duration"] req.journeys.max_transfers = request["max_transfers"] if request["max_extra_second_pass"]: req.journeys.max_extra_second_pass = request["max_extra_second_pass"] req.journeys.wheelchair = request["wheelchair"] or False # default value is no wheelchair req.journeys.realtime_level = get_pb_data_freshness(request) if "details" in request and request["details"]: req.journeys.details = request["details"] req.journeys.walking_transfer_penalty = request['_walking_transfer_penalty'] for forbidden_uri in get_or_default(request, "forbidden_uris[]", []): req.journeys.forbidden_uris.append(forbidden_uri) for allowed_id in get_or_default(request, "allowed_id[]", []): req.journeys.allowed_id.append(allowed_id) req.journeys.bike_in_pt = (dep_mode == 'bike') and (arr_mode == 'bike') if request["free_radius_from"]: req.journeys.free_radius_from = request["free_radius_from"] if request["free_radius_to"]: req.journeys.free_radius_to = request["free_radius_to"] if request["min_nb_journeys"]: req.journeys.min_nb_journeys = request["min_nb_journeys"] req.journeys.night_bus_filter_max_factor = request['_night_bus_filter_max_factor'] req.journeys.night_bus_filter_base_factor = request['_night_bus_filter_base_factor'] return req def _has_pt(j): return any(s.type == response_pb2.PUBLIC_TRANSPORT for s in j.sections) def sort_journeys(resp, journey_order, clockwise): if resp.journeys: resp.journeys.sort(journey_sorter[journey_order](clockwise=clockwise)) def compute_car_co2_emission(pb_resp, api_request, instance): if not pb_resp.journeys: return car = next((j for j in pb_resp.journeys if helpers.is_car_direct_path(j)), None) if car is None or not car.HasField('co2_emission'): # if there is no car journey found, we request kraken to give us an estimation of # co2 emission co2_estimation = instance.georef.get_car_co2_emission_on_crow_fly(api_request['origin'], api_request['destination']) if co2_estimation: # Assign car_co2_emission into the resp, these value will be exposed in the final result pb_resp.car_co2_emission.value = co2_estimation.value pb_resp.car_co2_emission.unit = co2_estimation.unit else: # Assign car_co2_emission into the resp, these value will be exposed in the final result pb_resp.car_co2_emission.value = car.co2_emission.value pb_resp.car_co2_emission.unit = car.co2_emission.unit def tag_ecologic(resp): # if there is no available car_co2_emission in resp, no tag will be assigned if resp.car_co2_emission.value and resp.car_co2_emission.unit: for j in resp.journeys: if not j.HasField('co2_emission'): j.tags.append('ecologic') continue if j.co2_emission.unit != resp.car_co2_emission.unit: continue if j.co2_emission.value < resp.car_co2_emission.value * 0.5: j.tags.append('ecologic') def _tag_direct_path(responses): street_network_mode_tag_map = {response_pb2.Walking: ['non_pt_walking'], response_pb2.Bike: ['non_pt_bike']} for j in itertools.chain.from_iterable(r.journeys for r in responses): if all(s.type != response_pb2.PUBLIC_TRANSPORT for s in j.sections): j.tags.extend(['non_pt']) # TODO: remove that (and street_network_mode_tag_map) when NMP stops using it # if there is only one section if len(j.sections) == 1: if j.sections[0].type == response_pb2.STREET_NETWORK and hasattr(j.sections[0], 'street_network'): tag = street_network_mode_tag_map.get(j.sections[0].street_network.mode) if tag: j.tags.extend(tag) def _is_bike_section(s): return ((s.type == response_pb2.CROW_FLY or s.type == response_pb2.STREET_NETWORK) and s.street_network.mode == response_pb2.Bike) def _is_pt_bike_accepted_section(s): bike_ok = type_pb2.hasEquipments.has_bike_accepted return (s.type == response_pb2.PUBLIC_TRANSPORT and bike_ok in s.pt_display_informations.has_equipments.has_equipments and bike_ok in s.origin.stop_point.has_equipments.has_equipments and bike_ok in s.destination.stop_point.has_equipments.has_equipments) def _is_bike_in_pt_journey(j): bike_indifferent = [response_pb2.boarding, response_pb2.landing, response_pb2.WAITING, response_pb2.TRANSFER, response_pb2.ALIGHTING] return _has_pt(j) and \ all(_is_bike_section(s) or _is_pt_bike_accepted_section(s) or s.type in bike_indifferent for s in j.sections) def _tag_bike_in_pt(responses): ''' we tag as 'bike _in_pt' journeys that are using bike as start AND end fallback AND that allow carrying bike in transport (and journey has to include PT) ''' for j in itertools.chain.from_iterable(r.journeys for r in responses): if _is_bike_in_pt_journey(j): j.tags.extend(['bike_in_pt']) def tag_journeys(resp): """ tag the journeys """ tag_ecologic(resp) def _get_section_id(section): street_network_mode = None if section.type in SECTION_TYPES_TO_RETAIN: if getattr(section.street_network, 'mode', None) in STREET_NETWORK_MODE_TO_RETAIN: street_network_mode = section.street_network.mode return section.uris.line, street_network_mode, section.type def _build_candidate_pool_and_sections_set(resp): sections_set = set() candidates_pool = list() idx_of_jrny_must_keep = list() for (i, jrny) in enumerate(resp.journeys): if jrny.type in JOURNEY_TYPES_TO_RETAIN: idx_of_jrny_must_keep.append(i) sections_set |= set([_get_section_id(s) for s in jrny.sections if s.type in SECTION_TYPES_TO_RETAIN]) candidates_pool.append(jrny) return np.array(candidates_pool), sections_set, idx_of_jrny_must_keep def _build_selected_sections_matrix(sections_set, candidates_pool): sections_2_index_dict = dict() for index, value in enumerate(sections_set): sections_2_index_dict[value] = index selected_sections_matrix = list() nb_sections = len(sections_set) for j in candidates_pool: section_select = np.zeros(nb_sections, dtype=int) def _gen_section_ind(): for s in j.sections: ind = sections_2_index_dict.get(_get_section_id(s)) if ind is not None: yield ind selected_indexes = list(_gen_section_ind()) section_select[selected_indexes] = 1 selected_sections_matrix.append(section_select) return np.array(selected_sections_matrix) def _get_sorted_solutions_indexes(selected_sections_matrix, nb_journeys_to_find, idx_of_jrny_must_keep): """ The entry is a 2D array where its lines are journeys, its columns are (non) chosen sections """ logger = logging.getLogger(__name__) """ Get a matrix which illustrate all possible non ordered combinations of t elements from n elements where n >= t with their indexes. Let's say we'd like to find all combinations of 2 elements from a set of 3. selected_journeys_matrix will be like: [[0,1] [0,2] [1,2]] """ selected_journeys_matrix = np.array(list(gen_all_combin(selected_sections_matrix.shape[0], nb_journeys_to_find))) """ We should cut out those combinations that don't contain must-keep journeys """ def _contains(idx_selected_jrny): return set(idx_selected_jrny).issuperset(idx_of_jrny_must_keep) selected_journeys_matrix = selected_journeys_matrix[np.apply_along_axis(_contains, 1, selected_journeys_matrix)] selection_matrix = np.zeros((selected_journeys_matrix.shape[0], selected_sections_matrix.shape[0])) """ Given selected_journeys_matrix: [[0,1] [0,2] [1,2]] selection_matrix will be like: [[1,1,0], -> the first one and the second are chosen, etc... [1,0,1], [0,1,1]] """ # http://stackoverflow.com/questions/20103779/index-2d-numpy-array-by-a-2d-array-of-indices-without-loops selection_matrix[np.arange(selected_journeys_matrix.shape[0])[:, None], selected_journeys_matrix] = 1 res_pool = np.dot(selection_matrix, selected_sections_matrix) """ Get number of sections(or tranfers) for every solution """ nb_sections = np.sum(res_pool, axis=1) """ integrity shows at which point a solution(chosen journeys) covers sections. 0 means a solution covers all sections 1 means a solutions covers almost all sections but 1 is missing 2 means 2 sections are missing .... etc """ integrity = res_pool.shape[1] - np.array([np.count_nonzero(r) for r in res_pool]) """ We want to find the solutions covers as many sections as possible which has less sections(less transfer to do) """ the_best_idx = np.lexsort((nb_sections, integrity))[0] # sort by integrity then by nb_sections best_indexes = np.where(np.logical_and(nb_sections == nb_sections[the_best_idx], integrity == integrity[the_best_idx]))[0] logger.debug("Best Itegrity: {0}".format(integrity[the_best_idx])) logger.debug("Best Nb sections: {0}".format(nb_sections[the_best_idx])) return best_indexes, selection_matrix def culling_journeys(resp, request): """ Remove some journeys if there are too many of them to have max_nb_journeys journeys. resp.journeys should be sorted before this function is called The goal is to choose a bunch of journeys(max_nv_journeys) that covers as many as possible sections but have as few as possible sum(sections) Ex: From: Journey_1 : Line 1 -> Line 8 -> Bus 172 Journey_2 : Line 14 -> Line 6 -> Bus 165 Journey_3 : Line 14 -> Line 6 ->Line 8 -> Bus 165 W'd like to choose two journeys. The algo will return Journey_1 and Journey2. Because With Journey_1 and Journey_3, they cover all lines but have 5 transfers in all With Journey_2 and Journey_3, they don't cover all lines(Line 1 is missing) and have 5 transfers in all With Journey_1 and Journey_2, they cover all lines and have only 4 transfers in all -> OK No removing done in debug """ logger = logging.getLogger(__name__) if not request["max_nb_journeys"] or request["max_nb_journeys"] >= len(resp.journeys): logger.debug('No need to cull journeys') return logger.debug('Trying to culling the journeys') """ To create a candidates pool, we choose only journeys that are NOT tagged as 'comfort' and 'best' and we create a section set from that pool Ex: Journey_1 (Best): Line 14 -> Line 8 -> Bus 172 Journey_2 : Line 14 -> Line 6 -> Bus 165 Journey_3 : Line 14 -> Line 8 -> Bus 165 The candidate pool will be like [Journey_2, Journey_3] The sections set will be like set([Line 14, Line 6, Line 8, Bus 165]) """ candidates_pool, sections_set, idx_of_jrnys_must_keep = _build_candidate_pool_and_sections_set(resp) nb_journeys_must_have = len(idx_of_jrnys_must_keep) logger.debug("There are {0} journeys we must keep".format(nb_journeys_must_have)) is_debug = request.get('debug') if (request["max_nb_journeys"] - nb_journeys_must_have) <= 0: # At this point, max_nb_journeys is smaller than nb_journeys_must_have, we have to make choices def _inverse_selection(d, indexes): select = np.in1d(list(range(d.shape[0])), indexes) return d[~select] # Here we mark all journeys as dead that are not must-have for jrny in _inverse_selection(candidates_pool, idx_of_jrnys_must_keep): journey_filter.mark_as_dead(jrny, is_debug, 'Filtered by max_nb_journeys') if request["max_nb_journeys"] == nb_journeys_must_have: logger.debug('max_nb_journeys equals to nb_journeys_must_have') journey_filter.delete_journeys((resp,), request) return logger.debug('max_nb_journeys:{0} is smaller than nb_journeys_must_have:{1}' .format(request["max_nb_journeys"], nb_journeys_must_have)) # At this point, resp.journeys should contain only must-have journeys list_dict = collections.defaultdict(list) for jrny in resp.journeys: if not journey_filter.to_be_deleted(jrny): list_dict[jrny.type].append(jrny) sorted_by_type_journeys = [] for t in JOURNEY_TYPES_TO_RETAIN: sorted_by_type_journeys.extend(list_dict.get(t, [])) for jrny in sorted_by_type_journeys[request["max_nb_journeys"]:]: journey_filter.mark_as_dead(jrny, is_debug, 'Filtered by max_nb_journeys') journey_filter.delete_journeys((resp,), request) return nb_journeys_to_find = request["max_nb_journeys"] logger.debug('Trying to find {0} journeys from {1}'.format(nb_journeys_to_find, candidates_pool.shape[0])) """ Ex: Journey_2 : Line 14 -> Line 6 -> Bus 165 Journey_3 : Line 14 -> Line 8 -> Bus 165 The candidate pool will be like [Journey_2, Journey_3] The sections set will be like set([Line 14, Line 6, Line 8, Bus 165]) selected_sections_matrix: [[1,1,0,1] -> journey_2 [1,0,1,1] -> journey_3 ] """ selected_sections_matrix = _build_selected_sections_matrix(sections_set, candidates_pool) best_indexes, selection_matrix = _get_sorted_solutions_indexes(selected_sections_matrix, nb_journeys_to_find, idx_of_jrnys_must_keep) logger.debug("Nb best solutions: {0}".format(best_indexes.shape[0])) the_best_index = best_indexes[0] logger.debug("Trying to find the best of best") """ Let's find the best of best :) """ # If there're several solutions which have the same score of integrity and nb_sections if best_indexes.shape[0] != 1: requested_dt = request['datetime'] is_clockwise = request.get('clockwise', True) def combinations_sorter(v): # Hoping to find We sort the solution by the sum of journeys' pseudo duration return np.sum((get_pseudo_duration(jrny, requested_dt, is_clockwise) for jrny in np.array(candidates_pool)[np.where(selection_matrix[v, :])])) the_best_index = min(best_indexes, key=combinations_sorter) logger.debug('Removing non selected journeys') for jrny in candidates_pool[np.where(selection_matrix[the_best_index, :] == 0)]: journey_filter.mark_as_dead(jrny, is_debug, 'Filtered by max_nb_journeys') journey_filter.delete_journeys((resp,), request) def _tag_journey_by_mode(journey): mode = 'walking' for i, section in enumerate(journey.sections): cur_mode = 'walking' if ((section.type == response_pb2.BSS_RENT) or (section.type == response_pb2.CROW_FLY and section.street_network.mode == response_pb2.Bss)): cur_mode = 'bss' elif ((section.type == response_pb2.STREET_NETWORK or section.type == response_pb2.CROW_FLY) and section.street_network.mode == response_pb2.Bike and journey.sections[i - 1].type != response_pb2.BSS_RENT): cur_mode = 'bike' elif ((section.type == response_pb2.STREET_NETWORK or section.type == response_pb2.CROW_FLY) and section.street_network.mode == response_pb2.Car): cur_mode = 'car' elif ((section.type == response_pb2.STREET_NETWORK or section.type == response_pb2.CROW_FLY) and section.street_network.mode == response_pb2.Ridesharing): # When the street network data is missing, the section maybe a crow_fly cur_mode = 'ridesharing' if mode_weight[mode] < mode_weight[cur_mode]: mode = cur_mode journey.tags.append(mode) def _tag_by_mode(responses): for r in responses: for j in r.journeys: _tag_journey_by_mode(j) def _is_fake_car_section(section): """ This function test if the section is a fake car section """ return (section.type == response_pb2.STREET_NETWORK or section.type == response_pb2.CROW_FLY) and \ section.street_network.mode == response_pb2.Car def _switch_back_to_ridesharing(response, is_first_section): """ :param response: a pb_response returned by kraken :param is_first_section: a bool indicates that if the first_section or last_section is a ridesharing section True if the first_section is, False if the last_section is :return: """ for journey in response.journeys: if len(journey.sections) == 0: continue section_idx = 0 if is_first_section else -1 section = journey.sections[section_idx] if _is_fake_car_section(section): section.street_network.mode = response_pb2.Ridesharing journey.durations.ridesharing += section.duration journey.durations.car -= section.duration journey.distances.ridesharing += section.length journey.distances.car -= section.length def nb_journeys(responses): return sum(1 for r in responses for j in r.journeys if not journey_filter.to_be_deleted(j)) def type_journeys(resp, req): """ Set the type of the journeys """ best_crit = arrival_crit if req["clockwise"] else departure_crit # first, we want a type for every journey. Just pick "rapid" by default. for j in resp.journeys: j.type = "rapid" # Then, we want something like the old types trip_caracs = [ # comfort tends to limit the number of transfers and fallback ("comfort", trip_carac([ has_no_car, ], [ transfers_crit, nonTC_crit, best_crit, duration_crit ])), # for car we want at most one journey, the earliest one ("car", trip_carac([ has_car, has_pt, # We don't want car only solution, we MUST have PT ], [ best_crit, transfers_crit, nonTC_crit, duration_crit ])), # less_fallback tends to limit the fallback while walking ("less_fallback_walk", trip_carac([ has_no_car, has_no_bike, ], [ nonTC_crit, transfers_crit, duration_crit, best_crit, ])), # less_fallback tends to limit the fallback for biking and bss ("less_fallback_bike", trip_carac([ has_no_car, has_bike, has_no_bss, ], [ nonTC_crit, transfers_crit, duration_crit, best_crit, ])), # less_fallback tends to limit the fallback for biking and bss ("less_fallback_bss", trip_carac([ has_no_car, has_bss, ], [ nonTC_crit, transfers_crit, duration_crit, best_crit, ])), # the fastest is quite explicit ("fastest", trip_carac([ has_no_car, ], [ duration_crit, transfers_crit, nonTC_crit, best_crit, ])), # the non_pt journeys is the earliest journey without any public transport ("non_pt_walk", trip_carac([ non_pt_journey, has_no_car, has_walk ], [ best_crit ])), # the non_pt journey is the earliest journey without any public transport # only walking, biking or driving ("non_pt_bike", trip_carac([ non_pt_journey, has_no_car, has_bike ], [ best_crit ])), ("non_pt_bss", trip_carac([ non_pt_journey, has_no_car, has_bss, ], [ best_crit ])), ("non_pt_car", trip_carac([ non_pt_journey, has_car, ], [ best_crit ])), ] for name, carac in trip_caracs: sublist = list(filter(and_filters(carac.constraints), resp.journeys)) best = min_from_criteria(sublist, carac.criteria) if best is not None: best.type = name # Finally, we want exactly one best, the ASAP one best = min_from_criteria(resp.journeys, [best_crit, duration_crit, transfers_crit, nonTC_crit]) if best is not None: best.type = "best" def merge_responses(responses): """ Merge all responses in one protobuf response """ merged_response = response_pb2.Response() for r in responses: if r.HasField(str('error')) or not r.journeys: # we do not take responses with error, but if all responses have errors, we'll aggregate them continue change_ids(r, len(merged_response.journeys)) # we don't want to add a journey already there merged_response.journeys.extend(r.journeys) # we have to add the additional fares too # if at least one journey has the ticket we add it tickets_to_add = set(t for j in r.journeys for t in j.fare.ticket_id) merged_response.tickets.extend((t for t in r.tickets if t.id in tickets_to_add)) initial_feed_publishers = {} for fp in merged_response.feed_publishers: initial_feed_publishers[fp.id] = fp merged_response.feed_publishers.extend((fp for fp in r.feed_publishers if fp.id not in initial_feed_publishers)) # handle impacts for i in r.impacts: if any(other.uri == i.uri for other in merged_response.impacts): continue merged_response.impacts.extend([i]) if not merged_response.journeys: # we aggregate the errors found errors = {r.error.id: r.error for r in responses if r.HasField(str('error'))} # Only one errors field if len(errors) == 1: merged_response.error.id = list(errors.values())[0].id merged_response.error.message = list(errors.values())[0].message # we need to merge the errors elif len(errors) > 1: merged_response.error.id = response_pb2.Error.no_solution merged_response.error.message = "several errors occured: \n * {}"\ .format("\n * ".join([m.message for m in errors.values()])) return merged_response def get_kraken_id(entrypoint_detail): """ returns a usable id for kraken from the entrypoint detail returns None if the original ID needs to be kept """ if not entrypoint_detail: # impossible to find the object return None emb_type = entrypoint_detail.get('embedded_type') if emb_type in ('stop_point', 'stop_area', 'administrative_region'): # for those object, we need to keep the original id, as there are specific treatment to be done return None # for the other objects the id is the object coordinated coord = entrypoint_detail.get(emb_type, {}).get('coord') if not coord: # no coordinate, we keep the original id return None return '{};{}'.format(coord['lon'], coord['lat']) class Scenario(simple.Scenario): """ TODO: a bit of explanation about the new scenario """ def __init__(self): super(Scenario, self).__init__() self.nb_kraken_calls = 0 def fill_journeys(self, request_type, api_request, instance): logger = logging.getLogger(__name__) # sometimes we need to change the entrypoint id (eg if the id is from another autocomplete system) origin_detail = self.get_entrypoint_detail(api_request.get('origin'), instance) destination_detail = self.get_entrypoint_detail(api_request.get('destination'), instance) # we store the origin/destination detail in g to be able to use them after the marshall g.origin_detail = origin_detail g.destination_detail = destination_detail api_request['origin'] = get_kraken_id(origin_detail) or api_request.get('origin') api_request['destination'] = get_kraken_id(destination_detail) or api_request.get('destination') # building ridesharing request from "original" request ridesharing_req = deepcopy(api_request) if not api_request['origin_mode']: api_request['origin_mode'] = ['walking'] if not api_request['destination_mode']: api_request['destination_mode'] = ['walking'] # Return the possible couples combinations (origin_mode and destination_mode) krakens_call = get_kraken_calls(api_request) # min_nb_journeys option if api_request['min_nb_journeys']: min_nb_journeys = api_request['min_nb_journeys'] else: min_nb_journeys = api_request['min_nb_journeys'] = 1 # We need the original request (api_request) for filtering, but request # is modified by create_next_kraken_request function. request = deepcopy(api_request) min_journeys_calls = get_or_default(request, '_min_journeys_calls', 1) responses = [] nb_try = 0 nb_qualified_journeys = 0 while request is not None and \ ((nb_qualified_journeys < min_nb_journeys and nb_try < min_nb_journeys) \ or nb_try < min_journeys_calls): nb_try = nb_try + 1 # we take into account the option only if we have one origin_mode and destination_mode couple. if len(krakens_call) > 1: request['min_nb_journeys'] = 0 else: min_nb_journeys_left = min_nb_journeys - nb_qualified_journeys request['min_nb_journeys'] = max(0, min_nb_journeys_left) new_resp = self.call_kraken(request_type, request, instance, krakens_call) _tag_by_mode(new_resp) _tag_direct_path(new_resp) _tag_bike_in_pt(new_resp) if nb_journeys(new_resp) == 0: # no new journeys found, we stop # we still append the new_resp because there are journeys that a tagged as dead probably responses.extend(new_resp) break request = self.create_next_kraken_request(request, new_resp) # we filter unwanted journeys in the new response # note that filter_journeys returns a generator which will be evaluated later filtered_new_resp = journey_filter.filter_journeys(new_resp, instance, api_request) # duplicate the generator tmp1, tmp2 = itertools.tee(filtered_new_resp) qualified_journeys = journey_filter.get_qualified_journeys(responses) # now we want to filter similar journeys in the new response which is done in 2 steps # In the first step, we compare journeys from the new response only , 2 by 2 # hopefully, it may lead to some early return for the second step to improve the perf a little # In the second step, we compare the journeys from the new response with those that have been qualified # already in the former iterations # note that the journeys_pool is a list of 2-element tuple of journeys journeys_pool = itertools.chain( # First step: compare journeys from the new response only itertools.combinations(tmp1, 2), # Second step: # we use the itertools.product to create combinations between qualified journeys and new journeys # Ex: # new_journeys = [n_1, n_2] # qualified_journeys = [q_1, q_2, q_3] # itertools.product(new_journeys, qualified_journeys) gives combinations as follows: # (n_1, q_1), (n_1, q_2),(n_1, q_3),(n_2, q_1),(n_2, q_2),(n_2, q_3) itertools.product(tmp2, qualified_journeys), ) pool1, pool2 = itertools.tee(journeys_pool) journey_filter.filter_similar_vj_journeys(pool1, api_request) if api_request['no_shared_section']: journey_filter.filter_shared_sections_journeys(pool2, api_request) responses.extend(new_resp) # we keep the error for building the response nb_qualified_journeys = nb_journeys(responses) # We allow one more call to kraken if there is no valid journey. if nb_qualified_journeys == 0: min_journeys_calls = max(min_journeys_calls, 2) logger.debug('nb of call kraken: %i', nb_try) journey_filter.final_filter_journeys(responses, instance, api_request) pb_resp = merge_responses(responses) sort_journeys(pb_resp, instance.journey_order, api_request['clockwise']) compute_car_co2_emission(pb_resp, api_request, instance) tag_journeys(pb_resp) if instance.ridesharing_services and \ ('ridesharing' in ridesharing_req['origin_mode'] or 'ridesharing' in ridesharing_req['destination_mode']): logger.debug('trying to add ridesharing journeys') try: decorate_journeys(pb_resp, instance, api_request) except Exception: logger.exception('Error while retrieving ridesharing ads') else: for j in pb_resp.journeys: if 'ridesharing' in j.tags: journey_filter.mark_as_dead(j, api_request.get('debug'), 'no_matching_ridesharing_found') journey_filter.delete_journeys((pb_resp,), api_request) type_journeys(pb_resp, api_request) culling_journeys(pb_resp, api_request) self._compute_pagination_links(pb_resp, instance, api_request['clockwise']) return pb_resp def call_kraken(self, request_type, request, instance, krakens_call): """ For all krakens_call, call the kraken and aggregate the responses return the list of all responses """ # TODO: handle min_alternative_journeys # TODO: call first bss|bss and do not call walking|walking if no bss in first results resp = [] logger = logging.getLogger(__name__) futures = [] reqctx = copy_flask_request_context() def worker(dep_mode, arr_mode, instance, request, flask_request_id): with copy_context_in_greenlet_stack(reqctx): return (dep_mode, arr_mode, instance.send_and_receive(request, flask_request_id=flask_request_id)) pool = gevent.pool.Pool(app.config.get('GREENLET_POOL_SIZE', 3)) for dep_mode, arr_mode in krakens_call: pb_request = create_pb_request(request_type, request, dep_mode, arr_mode) # we spawn a new greenlet, it won't have access to our thread local request object so we pass the request_id futures.append(pool.spawn(worker, dep_mode, arr_mode, instance, pb_request, flask_request_id=flask.request.id)) for future in gevent.iwait(futures): dep_mode, arr_mode, local_resp = future.get() # for log purpose we put and id in each journeys self.nb_kraken_calls += 1 for idx, j in enumerate(local_resp.journeys): j.internal_id = "{resp}-{j}".format(resp=self.nb_kraken_calls, j=idx) if dep_mode == 'ridesharing': _switch_back_to_ridesharing(local_resp, True) if arr_mode == 'ridesharing': _switch_back_to_ridesharing(local_resp, False) fill_uris(local_resp) resp.append(local_resp) logger.debug("for mode %s|%s we have found %s journeys", dep_mode, arr_mode, len(local_resp.journeys)) return resp def __on_journeys(self, requested_type, request, instance): updated_request_with_default(request, instance) # call to kraken resp = self.fill_journeys(requested_type, request, instance) return resp def journeys(self, request, instance): return self.__on_journeys(type_pb2.PLANNER, request, instance) def isochrone(self, request, instance): updated_request_with_default(request, instance) #we don't want to filter anything! krakens_call = get_kraken_calls(request) resp = merge_responses(self.call_kraken(type_pb2.ISOCHRONE, request, instance, krakens_call)) if not request['debug']: # on isochrone we can filter the number of max journeys if request["max_nb_journeys"] and len(resp.journeys) > request["max_nb_journeys"]: del resp.journeys[request["max_nb_journeys"]:] return resp def create_next_kraken_request(self, request, responses): """ modify the request to call the next (resp previous for non clockwise search) journeys in kraken to do that we find ask the next (resp previous) query datetime """ # If Kraken send a new request date time, we use it # for the next call to skip current Journeys if responses and responses[0].HasField('next_request_date_time'): request['datetime'] = responses[0].next_request_date_time else: vjs = journey_filter.get_qualified_journeys(responses) if request["clockwise"]: request['datetime'] = self.next_journey_datetime(vjs, request["clockwise"]) else: request['datetime'] = self.previous_journey_datetime(vjs, request["clockwise"]) if request['datetime'] is None: logger = logging.getLogger(__name__) logger.error("In response next_request_date_time does not exist") return None #TODO forbid ODTs return request @staticmethod def __get_best_for_criteria(journeys, criteria): return min_from_criteria(filter(has_pt, journeys), [criteria, duration_crit, transfers_crit, nonTC_crit]) def get_best(self, journeys, clockwise): if clockwise: return self.__get_best_for_criteria(journeys, arrival_crit) else: return self.__get_best_for_criteria(journeys, departure_crit) def next_journey_datetime(self, journeys, clockwise): """ to get the next journey, we add one second to the departure of the 'best found' journey """ best = self.get_best(journeys, clockwise) if best is None: return None one_second = 1 return best.departure_date_time + one_second def previous_journey_datetime(self, journeys, clockwise): """ to get the next journey, we add one second to the arrival of the 'best found' journey """ best = self.get_best(journeys, clockwise) if best is None: return None one_second = 1 return best.arrival_date_time - one_second def get_entrypoint_detail(self, entrypoint, instance): logging.debug("calling autocomplete {} for {}".format(instance.autocomplete, entrypoint)) detail = instance.autocomplete.get_object_by_uri(entrypoint, instances=[instance]) if detail: return detail if not isinstance(instance.autocomplete, GeocodeJson): bragi = global_autocomplete.get('bragi') if bragi: # if the instance's autocomplete is not a geocodejson autocomplete, we also check in the # global autocomplete instance return bragi.get_object_by_uri(entrypoint, instances=[instance]) return None
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import delete_accounting_dimension class TestAccountingDimension(unittest.TestCase): def setUp(self): frappe.set_user("Administrator") if not frappe.db.exists("Accounting Dimension", {"document_type": "Department"}): dimension = frappe.get_doc({ "doctype": "Accounting Dimension", "document_type": "Department", }).insert() else: dimension1 = frappe.get_doc("Accounting Dimension", "Department") dimension1.disabled = 0 dimension1.save() if not frappe.db.exists("Accounting Dimension", {"document_type": "Location"}): dimension1 = frappe.get_doc({ "doctype": "Accounting Dimension", "document_type": "Location", "mandatory_for_pl": 1 }).insert() else: dimension1 = frappe.get_doc("Accounting Dimension", "Location") dimension1.disabled = 0 dimension1.mandatory_for_pl = 1 dimension1.save() def test_dimension_against_sales_invoice(self): si = create_sales_invoice(do_not_save=1) si.location = "Block 1" si.append("items", { "item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC", "qty": 1, "rate": 100, "income_account": "Sales - _TC", "expense_account": "Cost of Goods Sold - _TC", "cost_center": "_Test Cost Center - _TC", "department": "_Test Department - _TC", "location": "Block 1" }) si.save() si.submit() gle = frappe.get_doc("GL Entry", {"voucher_no": si.name, "account": "Sales - _TC"}) self.assertEqual(gle.department, "_Test Department - _TC") def test_dimension_against_journal_entry(self): je = make_journal_entry("Sales - _TC", "Sales Expenses - _TC", 500, save=False) je.accounts[0].update({"department": "_Test Department - _TC"}) je.accounts[1].update({"department": "_Test Department - _TC"}) je.accounts[0].update({"location": "Block 1"}) je.accounts[1].update({"location": "Block 1"}) je.save() je.submit() gle = frappe.get_doc("GL Entry", {"voucher_no": je.name, "account": "Sales - _TC"}) gle1 = frappe.get_doc("GL Entry", {"voucher_no": je.name, "account": "Sales Expenses - _TC"}) self.assertEqual(gle.get('department'), "_Test Department - _TC") self.assertEqual(gle1.get('department'), "_Test Department - _TC") def test_mandatory(self): si = create_sales_invoice(do_not_save=1) si.append("items", { "item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC", "qty": 1, "rate": 100, "income_account": "Sales - _TC", "expense_account": "Cost of Goods Sold - _TC", "cost_center": "_Test Cost Center - _TC", "location": "" }) si.save() self.assertRaises(frappe.ValidationError, si.submit) def tearDown(self): disable_dimension() def disable_dimension(): dimension1 = frappe.get_doc("Accounting Dimension", "Department") dimension1.disabled = 1 dimension1.save() dimension2 = frappe.get_doc("Accounting Dimension", "Location") dimension2.mandatory_for_pl = 0 dimension2.disabled = 1 dimension2.save() fix: Test case fixes # -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import delete_accounting_dimension class TestAccountingDimension(unittest.TestCase): def setUp(self): frappe.set_user("Administrator") if not frappe.db.exists("Accounting Dimension", {"document_type": "Department"}): dimension = frappe.get_doc({ "doctype": "Accounting Dimension", "document_type": "Department", }).insert() else: dimension1 = frappe.get_doc("Accounting Dimension", "Department") dimension1.disabled = 0 dimension1.save() if not frappe.db.exists("Accounting Dimension", {"document_type": "Location"}): dimension1 = frappe.get_doc({ "doctype": "Accounting Dimension", "document_type": "Location", "mandatory_for_pl": 1 }).insert() else: dimension1 = frappe.get_doc("Accounting Dimension", "Location") dimension1.disabled = 0 dimension1.mandatory_for_pl = 1 dimension1.save() def test_dimension_against_sales_invoice(self): si = create_sales_invoice(do_not_save=1) si.location = "Block 1" si.append("items", { "item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC", "qty": 1, "rate": 100, "income_account": "Sales - _TC", "expense_account": "Cost of Goods Sold - _TC", "cost_center": "_Test Cost Center - _TC", "department": "_Test Department - _TC", "location": "Block 1" }) si.save() si.submit() gle = frappe.get_doc("GL Entry", {"voucher_no": si.name, "account": "Sales - _TC"}) self.assertEqual(gle.get('department'), "_Test Department - _TC") def test_dimension_against_journal_entry(self): je = make_journal_entry("Sales - _TC", "Sales Expenses - _TC", 500, save=False) je.accounts[0].update({"department": "_Test Department - _TC"}) je.accounts[1].update({"department": "_Test Department - _TC"}) je.accounts[0].update({"location": "Block 1"}) je.accounts[1].update({"location": "Block 1"}) je.save() je.submit() gle = frappe.get_doc("GL Entry", {"voucher_no": je.name, "account": "Sales - _TC"}) gle1 = frappe.get_doc("GL Entry", {"voucher_no": je.name, "account": "Sales Expenses - _TC"}) self.assertEqual(gle.get('department'), "_Test Department - _TC") self.assertEqual(gle1.get('department'), "_Test Department - _TC") def test_mandatory(self): si = create_sales_invoice(do_not_save=1) si.append("items", { "item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC", "qty": 1, "rate": 100, "income_account": "Sales - _TC", "expense_account": "Cost of Goods Sold - _TC", "cost_center": "_Test Cost Center - _TC", "location": "" }) si.save() self.assertRaises(frappe.ValidationError, si.submit) def tearDown(self): disable_dimension() def disable_dimension(): dimension1 = frappe.get_doc("Accounting Dimension", "Department") dimension1.disabled = 1 dimension1.save() dimension2 = frappe.get_doc("Accounting Dimension", "Location") dimension2.mandatory_for_pl = 0 dimension2.disabled = 1 dimension2.save()
import json import time import requests import glob2 from django.core.management.base import BaseCommand from django.contrib.gis import geos from django.contrib.gis.gdal import DataSource, GDALException from organisations.models import ( OrganisationDivision, DivisionGeography, Organisation, ) from organisations.utils import create_geom_from_curie_list from organisations.constants import POLICE_AREA_NAME_TO_GSS class Command(BaseCommand): def handle(self, **options): # TODO take as an ARG or config self.import_boundary_line( "/Users/symroe/Projects/democracyclub/data/**/*.shp") self.import_from_mapit() self.import_from_dgu() self.create_police_areas() def import_boundary_line(self, base_path): LAYERS_BY_GSS = {} LAYERS_BY_UNIT_ID = {} for file_path in glob2.glob(base_path): print(file_path) ignore = [ 'high_water_polyline.shp', 'parish_region.shp', ] if file_path.split('/')[-1] in ignore: continue try: ds = DataSource(file_path) except GDALException: # This is very strange – sometimes the above will fail the # first time, but not the second. Seen on OS X with GDAL # 2.2.0 ds = DataSource(file_path) for layer in ds[0]: code = None if b'WardCode' in layer.fields: code = str(layer['WardCode']) if b'PC_ID' in layer.fields: code = str(layer['PC_ID']) if b'CODE' in layer.fields: code = str(layer['CODE']) if code: LAYERS_BY_GSS[str(code)] = layer if b'UNIT_ID' in layer.fields: LAYERS_BY_UNIT_ID[str(layer['UNIT_ID'])] = layer def _process_qs(qs, obj_type="division"): for obj in qs: if obj_type == "organisation": code_type, code = ('gss', obj.gss) else: code_type, code = obj.geography_curie.split(':') code = str(code) if code_type in ["gss", "unit_id"]: try: if code in LAYERS_BY_GSS: layer = LAYERS_BY_GSS[code] elif code in LAYERS_BY_UNIT_ID: layer = LAYERS_BY_UNIT_ID[code] else: raise KeyError poly = self.clean_poly(layer.geom.geos) kwargs = { 'geography': poly, obj_type: obj } DivisionGeography.objects.create(**kwargs) except KeyError: pass _process_qs(OrganisationDivision.objects.filter(geography=None)) _process_qs(Organisation.objects.filter( geography=None), obj_type="organisation") def clean_poly(self, poly, srid=27700): if not poly.srid: poly.set_srid(srid) poly = poly.transform(4326, clone=True) if isinstance(poly, geos.Polygon): poly = geos.MultiPolygon(poly) return poly def import_from_mapit(self): def _process_qs(qs, obj_type="division"): count = qs.count() for i, obj in enumerate(qs): print("{} of {}: {} ({})".format( i, count, obj.name, getattr( obj, 'geography_curie', obj.format_geography_link()) )) initial_req = requests.get(obj.format_geography_link()) geo_json_url = "{}.geojson".format(initial_req.url) req = requests.get(geo_json_url) if req.status_code != 200: print("Not found in MaPit: {}".format(initial_req.url)) continue json_data = req.text poly = self.clean_poly(geos.GEOSGeometry(json_data)) kwargs = { 'geography': poly, obj_type: obj, } DivisionGeography.objects.create(**kwargs) time.sleep(1) _process_qs(OrganisationDivision.objects.filter( geography=None).exclude(mapit_generation_high=None)) _process_qs(Organisation.objects.filter( geography=None,).exclude(gss=""), obj_type="organisation") def import_from_dgu(self): def _process_qs(qs, obj_type="division"): count = qs.count() for i, obj in enumerate(qs): print("{} of {}: {} ({})".format( i, count, obj.name, getattr( obj, 'geography_curie', obj.format_geography_link()) )) if obj_type == "organisation": code_type, code = ('gss', obj.gss) else: code_type, code = obj.geography_curie.split(':') code = str(code) if code_type == "gss": geo_json_url = "{}/{}.json".format( "http://statistics.data.gov.uk/boundaries", code ) json_data = requests.get(geo_json_url).json()['geometry'] json_data = json.dumps(json_data) poly = self.clean_poly(geos.GEOSGeometry(json_data)) kwargs = { 'geography': poly, obj_type: obj, } DivisionGeography.objects.create(**kwargs) time.sleep(1) _process_qs(OrganisationDivision.objects.filter( geography=None).exclude(mapit_generation_high=None)) _process_qs(Organisation.objects.filter( geography=None,).exclude(gss=""), obj_type="organisation") def create_police_areas(self): for force_name, codes in POLICE_AREA_NAME_TO_GSS.items(): codes = ["gss:{}".format(x) for x in codes] poly = self.clean_poly(create_geom_from_curie_list(codes)) print(force_name) org = Organisation.objects.get( slug=force_name, organisation_type="police_area") if hasattr(org, 'geography'): org.geography.geography = poly org.geography.save() else: geog = DivisionGeography.objects.create( organisation=org, geography=poly ) Move BOUNADY_PATH to settings import os import json import time import requests import glob2 from django.core.management.base import BaseCommand from django.conf import settings from django.contrib.gis import geos from django.contrib.gis.gdal import DataSource, GDALException from organisations.models import ( OrganisationDivision, DivisionGeography, Organisation, ) from organisations.utils import create_geom_from_curie_list from organisations.constants import POLICE_AREA_NAME_TO_GSS class Command(BaseCommand): def handle(self, **options): self.import_boundary_line( os.path.join( settings.BOUNADY_PATH, "official_boundaries/**/*.shp" )) self.import_from_mapit() self.import_from_dgu() self.create_police_areas() def import_boundary_line(self, base_path): LAYERS_BY_GSS = {} LAYERS_BY_UNIT_ID = {} for file_path in glob2.glob(base_path): print(file_path) ignore = [ 'high_water_polyline.shp', 'parish_region.shp', ] if file_path.split('/')[-1] in ignore: continue try: ds = DataSource(file_path) except GDALException: # This is very strange – sometimes the above will fail the # first time, but not the second. Seen on OS X with GDAL # 2.2.0 ds = DataSource(file_path) for layer in ds[0]: code = None if b'WardCode' in layer.fields: code = str(layer['WardCode']) if b'PC_ID' in layer.fields: code = str(layer['PC_ID']) if b'CODE' in layer.fields: code = str(layer['CODE']) if code: LAYERS_BY_GSS[str(code)] = layer if b'UNIT_ID' in layer.fields: LAYERS_BY_UNIT_ID[str(layer['UNIT_ID'])] = layer def _process_qs(qs, obj_type="division"): for obj in qs: if obj_type == "organisation": code_type, code = ('gss', obj.gss) else: code_type, code = obj.geography_curie.split(':') code = str(code) if code_type in ["gss", "unit_id"]: try: if code in LAYERS_BY_GSS: layer = LAYERS_BY_GSS[code] elif code in LAYERS_BY_UNIT_ID: layer = LAYERS_BY_UNIT_ID[code] else: raise KeyError poly = self.clean_poly(layer.geom.geos) kwargs = { 'geography': poly, obj_type: obj } DivisionGeography.objects.create(**kwargs) except KeyError: pass _process_qs(OrganisationDivision.objects.filter(geography=None)) _process_qs(Organisation.objects.filter( geography=None), obj_type="organisation") def clean_poly(self, poly, srid=27700): if not poly.srid: poly.set_srid(srid) poly = poly.transform(4326, clone=True) if isinstance(poly, geos.Polygon): poly = geos.MultiPolygon(poly) return poly def import_from_mapit(self): def _process_qs(qs, obj_type="division"): count = qs.count() for i, obj in enumerate(qs): print("{} of {}: {} ({})".format( i, count, obj.name, getattr( obj, 'geography_curie', obj.format_geography_link()) )) initial_req = requests.get(obj.format_geography_link()) geo_json_url = "{}.geojson".format(initial_req.url) req = requests.get(geo_json_url) if req.status_code != 200: print("Not found in MaPit: {}".format(initial_req.url)) continue json_data = req.text poly = self.clean_poly(geos.GEOSGeometry(json_data)) kwargs = { 'geography': poly, obj_type: obj, } DivisionGeography.objects.create(**kwargs) time.sleep(1) _process_qs(OrganisationDivision.objects.filter( geography=None).exclude(mapit_generation_high=None)) _process_qs(Organisation.objects.filter( geography=None,).exclude(gss=""), obj_type="organisation") def import_from_dgu(self): def _process_qs(qs, obj_type="division"): count = qs.count() for i, obj in enumerate(qs): print("{} of {}: {} ({})".format( i, count, obj.name, getattr( obj, 'geography_curie', obj.format_geography_link()) )) if obj_type == "organisation": code_type, code = ('gss', obj.gss) else: code_type, code = obj.geography_curie.split(':') code = str(code) if code_type == "gss": geo_json_url = "{}/{}.json".format( "http://statistics.data.gov.uk/boundaries", code ) json_data = requests.get(geo_json_url).json()['geometry'] json_data = json.dumps(json_data) poly = self.clean_poly(geos.GEOSGeometry(json_data)) kwargs = { 'geography': poly, obj_type: obj, } DivisionGeography.objects.create(**kwargs) time.sleep(1) _process_qs(OrganisationDivision.objects.filter( geography=None).exclude(mapit_generation_high=None)) _process_qs(Organisation.objects.filter( geography=None,).exclude(gss=""), obj_type="organisation") def create_police_areas(self): for force_name, codes in POLICE_AREA_NAME_TO_GSS.items(): codes = ["gss:{}".format(x) for x in codes] poly = self.clean_poly(create_geom_from_curie_list(codes)) print(force_name) org = Organisation.objects.get( slug=force_name, organisation_type="police_area") if hasattr(org, 'geography'): org.geography.geography = poly org.geography.save() else: geog = DivisionGeography.objects.create( organisation=org, geography=poly )
from time import sleep from copy import copy import logging from threading import Event #logging.basicConfig(level=logging.DEBUG) def to_be_foreground(func): #A safety check wrapper so that certain functions don't get called if refresher is not the one active def wrapper(self, *args, **kwargs): if self.in_foreground: return func(self, *args, **kwargs) else: print(func.__name__+" misbehaves") return wrapper class Refresher(): """Implements a state where display is refreshed from time to time, updating the screen with information from a function. """ refresh_function = None refresh_interval = 0 display_callback = None in_foreground = False name = "" keymap = None def __init__(self, refresh_function, i, o, refresh_interval=1, keymap=None, name="Refresher"): """Initialises the Refresher object. Args: * ``refresh_function``: a function which returns data to be displayed on the screen upon being called, in the format accepted by ``screen.display_data()`` * ``i``, ``o``: input&output device objects Kwargs: * ``keymap``: Keymap entries you want to set while Refresher is active * ``name``: Refresher name which can be used internally and for debugging. """ self.i = i self.o = o self.name = name self.refresh_interval = refresh_interval self.refresh_function = refresh_function self.set_keymap(keymap if keymap else {}) self.in_background = Event() def to_foreground(self): """ Is called when refresher's ``activate()`` method is used, sets flags and performs all the actions so that refresher can display its contents and receive keypresses.""" logging.info("refresher {0} in foreground".format(self.name)) self.in_background.set() self.in_foreground = True self.refresh() self.activate_keymap() def to_background(self): """ Signals ``activate`` to finish executing """ self.in_foreground = False logging.info("refresher {0} in background".format(self.name)) def activate(self): """ A method which is called when refresher needs to start operating. Is blocking, sets up input&output devices, renders the refresher, periodically calls the refresh function&refreshes the screen while self.in_foreground is True, while refresher callbacks are executed from the input device thread.""" logging.info("refresher {0} activated".format(self.name)) self.to_foreground() sleep_time = 0.01 counter = 0 rts_ratio = self.refresh_interval/sleep_time while self.in_background.isSet(): if self.in_foreground: if counter == rts_ratio: counter = 0 if counter == 0: self.refresh() counter += 1 sleep(sleep_time) logging.debug(self.name+" exited") return True def deactivate(self): """ Deactivates the refresher completely, exiting it.""" self.in_foreground = False self.in_background.clear() logging.info("refresher {0} deactivated".format(self.name)) def print_name(self): """ A debug method. Useful for hooking up to an input event so that you can see which refresher is currently active. """ logging.info("Active refresher is {0}".format(self.name)) def process_callback(self, func): """ Decorates a function to be used by Refresher element. |Is typically used as a wrapper for a callback from input event processing thread. |After callback's execution is finished, sets the keymap again and refreshes the refresher.""" def wrapper(*args, **kwargs): self.to_background() func(*args, **kwargs) logging.debug("Executed wrapped function: {}".format(func.__name__)) if self.in_background.isSet(): self.to_foreground() wrapper.__name__ == func.__name__ return wrapper def process_keymap(self, keymap): """Sets the keymap. In future, will allow per-system keycode-to-callback tweaking using a config file. """ logging.debug("{}: processing keymap - {}".format(self.name, keymap)) for key in keymap: callback = self.process_callback(keymap[key]) keymap[key] = callback if not "KEY_LEFT" in keymap: keymap["KEY_LEFT"] = self.deactivate if not "KEY_RIGHT" in keymap: keymap["KEY_RIGHT"] = self.print_name return keymap def set_keymap(self, keymap): """Generate and sets the input device's keycode-to-callback mapping. Re-starts the input device because of passing-variables-between-threads issues.""" self.keymap = self.process_keymap(keymap) @to_be_foreground def activate_keymap(self): self.i.stop_listen() self.i.clear_keymap() self.i.keymap = self.keymap self.i.listen() @to_be_foreground def refresh(self): logging.debug("{0}: refreshed data on display".format(self.name)) self.o.display_data(*self.refresh_function()) Added missing description for refresh_interval kwarg from time import sleep from copy import copy import logging from threading import Event #logging.basicConfig(level=logging.DEBUG) def to_be_foreground(func): #A safety check wrapper so that certain functions don't get called if refresher is not the one active def wrapper(self, *args, **kwargs): if self.in_foreground: return func(self, *args, **kwargs) else: print(func.__name__+" misbehaves") return wrapper class Refresher(): """Implements a state where display is refreshed from time to time, updating the screen with information from a function. """ refresh_function = None refresh_interval = 0 display_callback = None in_foreground = False name = "" keymap = None def __init__(self, refresh_function, i, o, refresh_interval=1, keymap=None, name="Refresher"): """Initialises the Refresher object. Args: * ``refresh_function``: a function which returns data to be displayed on the screen upon being called, in the format accepted by ``screen.display_data()`` * ``i``, ``o``: input&output device objects Kwargs: * ``refresh_interval``: Time between display refreshes (and, accordingly, ``refresh_function`` calls) * ``keymap``: Keymap entries you want to set while Refresher is active * ``name``: Refresher name which can be used internally and for debugging. """ self.i = i self.o = o self.name = name self.refresh_interval = refresh_interval self.refresh_function = refresh_function self.set_keymap(keymap if keymap else {}) self.in_background = Event() def to_foreground(self): """ Is called when refresher's ``activate()`` method is used, sets flags and performs all the actions so that refresher can display its contents and receive keypresses.""" logging.info("refresher {0} in foreground".format(self.name)) self.in_background.set() self.in_foreground = True self.refresh() self.activate_keymap() def to_background(self): """ Signals ``activate`` to finish executing """ self.in_foreground = False logging.info("refresher {0} in background".format(self.name)) def activate(self): """ A method which is called when refresher needs to start operating. Is blocking, sets up input&output devices, renders the refresher, periodically calls the refresh function&refreshes the screen while self.in_foreground is True, while refresher callbacks are executed from the input device thread.""" logging.info("refresher {0} activated".format(self.name)) self.to_foreground() sleep_time = 0.01 counter = 0 rts_ratio = self.refresh_interval/sleep_time while self.in_background.isSet(): if self.in_foreground: if counter == rts_ratio: counter = 0 if counter == 0: self.refresh() counter += 1 sleep(sleep_time) logging.debug(self.name+" exited") return True def deactivate(self): """ Deactivates the refresher completely, exiting it.""" self.in_foreground = False self.in_background.clear() logging.info("refresher {0} deactivated".format(self.name)) def print_name(self): """ A debug method. Useful for hooking up to an input event so that you can see which refresher is currently active. """ logging.info("Active refresher is {0}".format(self.name)) def process_callback(self, func): """ Decorates a function to be used by Refresher element. |Is typically used as a wrapper for a callback from input event processing thread. |After callback's execution is finished, sets the keymap again and refreshes the refresher.""" def wrapper(*args, **kwargs): self.to_background() func(*args, **kwargs) logging.debug("Executed wrapped function: {}".format(func.__name__)) if self.in_background.isSet(): self.to_foreground() wrapper.__name__ == func.__name__ return wrapper def process_keymap(self, keymap): """Sets the keymap. In future, will allow per-system keycode-to-callback tweaking using a config file. """ logging.debug("{}: processing keymap - {}".format(self.name, keymap)) for key in keymap: callback = self.process_callback(keymap[key]) keymap[key] = callback if not "KEY_LEFT" in keymap: keymap["KEY_LEFT"] = self.deactivate if not "KEY_RIGHT" in keymap: keymap["KEY_RIGHT"] = self.print_name return keymap def set_keymap(self, keymap): """Generate and sets the input device's keycode-to-callback mapping. Re-starts the input device because of passing-variables-between-threads issues.""" self.keymap = self.process_keymap(keymap) @to_be_foreground def activate_keymap(self): self.i.stop_listen() self.i.clear_keymap() self.i.keymap = self.keymap self.i.listen() @to_be_foreground def refresh(self): logging.debug("{0}: refreshed data on display".format(self.name)) self.o.display_data(*self.refresh_function())
from django.http import HttpResponse from django.shortcuts import get_object_or_404 from invoice.models import Invoice from invoice.pdf import draw_pdf def pdf_view(request, pk): invoice = get_object_or_404(Invoice, pk=pk) filename = 'Invoice-%s.pdf' % invoice.invoice_id response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'inline; filename="%s"' % filename draw_pdf(response, invoice) return response Force pdf to download from django.http import HttpResponse from django.shortcuts import get_object_or_404 from invoice.models import Invoice from invoice.pdf import draw_pdf def pdf_view(request, pk): invoice = get_object_or_404(Invoice, pk=pk) filename = 'Invoice-%s.pdf' % invoice.invoice_id response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s"' % filename draw_pdf(response, invoice) return response
import copy import os from os.path import join from types import DictType, BooleanType, StringTypes, ListType, TupleType from .exceptions import AmbiguousEnvVar, UncastableEnvVar from .util import debug class NestedEnv(Adapter): """ Custom etcaetera adapter for handling env vars (more flexibly than Env). """ def __init__(self, config, prefix=None): """ Initialize this adapter with a handle to a live Config object. :param config: An already-loaded Config object which can be introspected for its keys. :param str prefix: A prefix string used when seeking env vars; see `.Config`. """ super(NestedEnv, self).__init__() self._config = config self._prefix = prefix self.data = {} def load(self, formatter=None): # NOTE: This accepts a formatter argument because that's the API. # However we don't use it (or the centrally defined one) because we # have specific requirements for how keys are treated in this adapter. # Meh! # Obtain allowed env var -> existing value map env_vars = self._crawl(key_path=[], env_vars={}) debug("Scanning for env vars according to prefix: {1!r}, mapping: {0!r}".format(env_vars, self._prefix)) # Check for actual env var (honoring prefix) and try to set for env_var, key_path in env_vars.iteritems(): real_var = (self._prefix or "") + env_var if real_var in os.environ: self._path_set(key_path, os.environ[real_var]) def _crawl(self, key_path, env_vars): """ Examine config at location ``key_path`` & return potential env vars. Uses ``env_vars`` dict to determine if a conflict exists, and raises an exception if so. This dict is of the following form:: { 'EXPECTED_ENV_VAR_HERE': ['actual', 'nested', 'key_path'], ... } Returns another dictionary of new keypairs as per above. """ new_vars = {} obj = self._path_get(key_path) # Sub-dict -> recurse if hasattr(obj, 'keys') and hasattr(obj, '__getitem__'): for key in obj.keys(): merged_vars = dict(env_vars, **new_vars) merged_path = key_path + [key] crawled = self._crawl(merged_path, merged_vars) # Handle conflicts for key in crawled: if key in new_vars: err = "Found >1 source for {0}" raise AmbiguousEnvVar(err.format(key)) # Merge and continue new_vars.update(crawled) # Other -> is leaf, no recursion else: new_vars[self._to_env_var(key_path)] = key_path return new_vars def _to_env_var(self, key_path): return '_'.join(key_path).upper() def _path_get(self, key_path): # Gets are from self._config because that's what determines valid env # vars and/or values for typecasting. obj = self._config for key in key_path: obj = obj[key] return obj def _path_set(self, key_path, value): # Sets are to self.data since that's what we are presenting to the # outer config object and debugging. obj = self.data for key in key_path[:-1]: if key not in obj: obj[key] = {} obj = obj[key] old = self._path_get(key_path) new_ = self._cast(old, value) obj[key_path[-1]] = new_ def _cast(self, old, new_): if isinstance(old, BooleanType): return new_ not in ('0', '') elif isinstance(old, StringTypes): return new_ elif old is None: return new_ elif isinstance(old, (ListType, TupleType)): err = "Can't adapt an environment string into a {0}!" err = err.format(type(old)) raise UncastableEnvVar(err) else: return old.__class__(new_) class ExclusiveFile(Adapter): """ File-loading config adapter that looks for one of N possible suffixes. For example, ``ExclusiveFile(prefix='/etc/invoke', suffixes=['yaml', 'json'])`` behaves similar to loading both of ``File('/etc/invoke.yaml')`` + ``File('/etc/invoke.json')``, with the distinction that if ``/etc/invoke.yaml`` is succesfully loaded, the JSON file is **not** loaded at all. (This means that the order of the ``suffixes`` parameter matters.) This provides an unambiguous config source-loading process, simplifying troubleshooting and (hopefully) reduces potential for confusion. :param str prefix: Everything but the file extension, e.g. ``/etc/invoke`` to load up files like ``/etc/invoke.yaml``. :param iterable suffixes: Optional iterable of file extensions like ``"yaml"`` or ``"json"``. Do not include any leading periods (i.e. don't say ``ExclusiveFile('/etc/invoke', '.yaml')``). Defaults to ``('yaml', 'json', 'py')``. """ def __init__(self, prefix, suffixes=None): if suffixes is None: suffixes = ('yaml', 'json', 'py') self.prefix = prefix self.suffixes = suffixes self.adapters = [ File( "{0}.{1}".format(prefix, x), python_uppercase=False, strict=False ) for x in suffixes ] self.data = {} self.loaded = None def __str__(self): return "ExclusiveFile({0}.{{{1}}})".format(self.prefix, ','.join(self.suffixes)) def load(self, formatter=None): for adapter in self.adapters: adapter.load(formatter=formatter) # Simply offload data from the 1st one to be found. # If none are found, our data remains empty as initialized. if adapter.found: self.data = adapter.data self.loaded = adapter.filepath return class DataProxy(object): """ Helper class implementing nested dict+attr access for `.Config`. """ # Attributes which get proxied through to inner etc.Config obj. _proxies = tuple(""" clear get has_key items iteritems iterkeys itervalues keys pop popitem setdefault update values """.split()) + tuple("__{0}__".format(x) for x in """ cmp contains iter sizeof """.split()) # Alt constructor used so we aren't getting in the way of Config's real # __init__(). @classmethod def from_data(cls, data): obj = cls() obj.config = data return obj def __getattr__(self, key): try: return self._get(key) except KeyError: # Proxy most special vars to config for dict procotol. if key in self._proxies: return getattr(self.config, key) # Otherwise, raise useful AttributeError to follow getattr proto. err = "No attribute or config key found for {0!r}".format(key) attrs = [x for x in dir(self.__class__) if not x.startswith('_')] err += "\n\nValid real attributes: {0!r}".format(attrs) err += "\n\nValid keys: {0!r}".format(self.config.keys()) raise AttributeError(err) def __hasattr__(self, key): return key in self.config or key in self._proxies def __iter__(self): # For some reason Python is ignoring our __hasattr__ when determining # whether we support __iter__. BOO return iter(self.config) def __eq__(self, other): # Can't proxy __eq__ because the RHS will always be an obj of the # current class, not the proxied-to class, and that causes # NotImplemented. return self.config == other.config def __len__(self): # Can't proxy __len__ either apparently? ugh return len(self.config) def __setitem__(self, key, value): # ... or __setitem__? thanks for nothing Python >:( self.config[key] = value def __delitem__(self, key): # OK this is really getting annoying del self.config[key] def __getitem__(self, key): return self._get(key) def _get(self, key): value = self.config[key] if isinstance(value, DictType): value = DataProxy.from_data(value) return value def __str__(self): return str(self.config) def __unicode__(self): return unicode(self.config) def __repr__(self): return repr(self.config) # TODO: copy()? class Config(DataProxy): """ Invoke's primary configuration handling class. See :doc:`/concepts/configuration` for details on the configuration system this class implements, including the :ref:`configuration hierarchy <config-hierarchy>`. The rest of this class' documentation assumes familiarity with that document. Lifecycle --------- Configuration data is constructed piecemeal starting at initialization time and config sources are loaded lazily upon request. For example, pure-Python configuration does not load from the filesystem or shell environment:: c = Config(defaults={'foo': 'bar'}) c.foo # No action taken, defaults are the only thing consulted If filesystem paths prefixes are given, they are scanned at access time and merged into the final config:: c = Config(system_prefix='/etc/invoke') c.foo # Attempts to load files like /etc/invoke.yaml c.foo # No filesystem action taken this time The merged config is regenerated any time config sources are updated, such as when Invoke's core machinery tells the default config object that it's time to load data from the shell environment:: c = Config(system_prefix='/etc/invoke') c.foo # Merging (and file load) occurs c.foo # No merging nor file loading - cache only c.load_shell_env() # Merging (but no file loads - only env) c.foo # Again, no merging or file loading takes place Access ------ Configuration values may be accessed using dict syntax:: config['foo'] or attribute syntax:: config.foo .. warning:: Any "real" attributes (methods, etc) on `Config` take precedence over settings values - so if you have top level settings named ``clone``, ``defaults``, etc, you *must* use dict syntax to access it. Nesting works the same way - dict config values are turned into objects which honor both the dictionary protocol and the attribute-access method:: config['foo']['bar'] config.foo.bar Non-data attributes & methods ----------------------------- This class implements the entire dictionary protocol: methods such as ``keys``, ``values``, ``items``, ``pop`` and so forth should all function as they do on regular dicts. Individual configuration 'levels' and their source locations (if applicable) may be accessed via attributes such as `.project`/`.project_file` and so forth - see the documentation for individual members below for details. """ #: Path to loaded project-related config file, if any. project_file = None #: Data loaded from `.project_file`, if any. project = {} def __init__(self, defaults=None, overrides=None, system_prefix=None, user_prefix=None, project_home=None, env_prefix=None, runtime_path=None): """ Creates a new config object. :param dict defaults: A dict containing default (lowest level) config data. Default: ``{}``. :param dict overrides: A dict containing override-level config data. Default: ``{}``. :param str system_prefix: Path & partial filename for the global config file location. Should include everything but the dot & file extension. Default: ``/etc/invoke`` (e.g. ``/etc/invoke.yaml`` or ``/etc/invoke.json``). :param str user_prefix: Like ``system_prefix`` but for the per-user config file. Default: ``~/.invoke`` (e.g. ``~/.invoke.yaml``). :param str project_home: Optional directory path location of the currently loaded `.Collection` (as loaded by `.Loader`). When non-empty, will trigger seeking of per-project config files in this location + ``invoke.(yaml|json|py)``. :param str env_prefix: Environment variable seek prefix; optional, defaults to ``None``. When not ``None``, only environment variables beginning with this value will be loaded. If it is set, the keys will have the prefix stripped out before processing, so e.g. ``env_prefix='INVOKE_'`` means users must set ``INVOKE_MYSETTING`` in the shell to affect the ``"mysetting"`` setting. :param str runtime_path: Optional file path to a runtime configuration file. Used to fill the penultimate slot in the config hierarchy. Should be a full file path to an existing file, not a directory path, or a prefix. """ # Setup if defaults is None: defaults = {} if overrides is None: overrides = {} if global_prefix is None: global_prefix = '/etc/invoke' if user_prefix is None: user_prefix = '~/.invoke' # Store env prefix for use in load() when we parse the environment self.env_prefix = env_prefix c = EtcConfig(formatter=noop) # Explicit adapter set if adapters is not None: c.register(*adapters) # The Hierarchy else: # Level 1 is absolute defaults. # Reinforce 'noop' here, Defaults calls load() in init() c.register(Defaults(defaults, formatter=noop)) # Level 2 is collection-driven, set via argument to load() later # (because they can only come at execution time and may differ for # each task invoked). # Levels 3-5: global, user, & project config files c.register(ExclusiveFile(prefix=global_prefix)) c.register(ExclusiveFile(prefix=user_prefix)) if project_home is not None: c.register(ExclusiveFile(prefix=join(project_home, "invoke"))) else: c.register(Dummy()) # Level 6: environment variables. See `load()` - must be done as # late as possible to 'see' all other defined keys. # Level 7: Runtime config file if runtime_path is not None: # Give python_uppercase in case it's a .py. Is a safe no-op # otherwise. c.register(File(runtime_path, python_uppercase=False)) else: c.register(Dummy()) # Level 8 is Overrides, typically runtime flag values c.register(Overrides(overrides, formatter=noop)) # Assign to member self.config = c def load_shell_env(self): """ Load values from the shell environment, then trigger a config merge. This method is idempotent and does nothing if ``.shell`` is already non-``None``. `.load_shell_env` is intended for execution late in a `.Config` object's lifecycle, once all other sources have been merged. Loading from the shell is not terrifically expensive, but must be done at a specific point in time to ensure the "only valid options" behavior works correctly. See :ref:`env-vars` for details on this design decision and other info re: how environment variables are scanned and loaded. """ pass def set_collection(self, data): """ Update collection-driven config data, then trigger a config merge. This method is idempotent and does nothing if ``.collection`` is already non-``None``. `.set_collection` is intended for use by the core task execution machinery, which is responsible for obtaining per-task collection-driven data. See :ref:`collection-configuration` for details. """ pass def load(self, collection=None): """ Performs loading and merging of all config sources. See :ref:`config-hierarchy` for details on load order and file locations. :param dict collection: A dict containing collection-driven config data. Default: ``{}``. """ # Pull in defaults (we do so at this level because typically we won't # know about collection-level default values until closer to runtime. if collection is None: collection = {} # NOTE: can't use etc.AdapterSet.appendleft here, it is buggy, no time # to fix right now. Just insert at position 1 after the Defaults we # already know is there. self.config.adapters.insert(1, Basic(collection)) # Now that we have all other sources defined, we can load the Env # adapter. This sadly requires a 'pre-load' call to .load() so config # files get slurped up. self.config.load() env = NestedEnv(config=self.config, prefix=self.env_prefix) # Must break encapsulation a tiny bit here to ensure env vars come # before runtime config files in the hierarchy. It's the least bad way # right now given etc.Config's api. self.config.adapters.insert(len(self.config.adapters) - 2, env) # Re-load() so that our values get applied in the right slot in the # hierarchy. self.config.load() debug("Loading & merging config adapters in order...") for adapter in self.config.adapters: if isinstance(adapter, File) and not adapter.found: debug("Didn't see any {0}, skipping".format(adapter)) elif isinstance(adapter, ExclusiveFile): if adapter.loaded is None: debug("Didn't see any of {0}, skipping".format( adapter)) else: debug("{0} loaded {1}, got {2!r}".format( adapter, adapter.loaded, adapter.data)) else: # Wrap adapter in dict() so defaultdicts print nicer debug("Loaded {0}, got {1!r}".format( adapter, dict(adapter.data))) debug("Final merged config: {0!r}".format(self.config)) def clone(self): """ Return a copy of this configuration object. The new object will be identical in terms of configured sources and any loaded/merged data, but will be a distinct object with no shared mutable state. """ # New config w/ formatter preserved c = EtcConfig(formatter=self.config.formatter) # New adapters, ditto + deepcopy internal data adapters = [] for old in self.config.adapters: c.register(_clone_adapter(old)) # Then deepcopy loaded data in case already loaded (we don't # necessarily know at this point if loading has occurred). c.update(copy.deepcopy(dict(self.config))) # All set new = Config(env_prefix=self.env_prefix) new.config = c return new def _clone_adapter(old): if isinstance(old, (Defaults, Overrides)): new = old.__class__(formatter=old.formatter) elif isinstance(old, File): new = File( filepath=old.filepath, python_uppercase=old.python_uppercase, formatter=old.formatter, ) elif isinstance(old, ExclusiveFile): new = ExclusiveFile( prefix=old.prefix, suffixes=old.suffixes, ) elif isinstance(old, NestedEnv): new = NestedEnv(old._config) elif isinstance(old, Dummy): new = Dummy() elif isinstance(old, Basic): new = Basic(old.data) else: raise TypeError("No idea how to clone {0}!".format(old.__class__)) new.data = copy.deepcopy(old.data) return new Overhaul `Config.__init__` to envision new attribute layout import copy import os from os.path import join from types import DictType, BooleanType, StringTypes, ListType, TupleType from .exceptions import AmbiguousEnvVar, UncastableEnvVar from .util import debug class NestedEnv(object): """ Custom etcaetera adapter for handling env vars (more flexibly than Env). """ def __init__(self, config, prefix=None): """ Initialize this adapter with a handle to a live Config object. :param config: An already-loaded Config object which can be introspected for its keys. :param str prefix: A prefix string used when seeking env vars; see `.Config`. """ super(NestedEnv, self).__init__() self._config = config self._prefix = prefix self.data = {} def load(self, formatter=None): # NOTE: This accepts a formatter argument because that's the API. # However we don't use it (or the centrally defined one) because we # have specific requirements for how keys are treated in this adapter. # Meh! # Obtain allowed env var -> existing value map env_vars = self._crawl(key_path=[], env_vars={}) debug("Scanning for env vars according to prefix: {1!r}, mapping: {0!r}".format(env_vars, self._prefix)) # Check for actual env var (honoring prefix) and try to set for env_var, key_path in env_vars.iteritems(): real_var = (self._prefix or "") + env_var if real_var in os.environ: self._path_set(key_path, os.environ[real_var]) def _crawl(self, key_path, env_vars): """ Examine config at location ``key_path`` & return potential env vars. Uses ``env_vars`` dict to determine if a conflict exists, and raises an exception if so. This dict is of the following form:: { 'EXPECTED_ENV_VAR_HERE': ['actual', 'nested', 'key_path'], ... } Returns another dictionary of new keypairs as per above. """ new_vars = {} obj = self._path_get(key_path) # Sub-dict -> recurse if hasattr(obj, 'keys') and hasattr(obj, '__getitem__'): for key in obj.keys(): merged_vars = dict(env_vars, **new_vars) merged_path = key_path + [key] crawled = self._crawl(merged_path, merged_vars) # Handle conflicts for key in crawled: if key in new_vars: err = "Found >1 source for {0}" raise AmbiguousEnvVar(err.format(key)) # Merge and continue new_vars.update(crawled) # Other -> is leaf, no recursion else: new_vars[self._to_env_var(key_path)] = key_path return new_vars def _to_env_var(self, key_path): return '_'.join(key_path).upper() def _path_get(self, key_path): # Gets are from self._config because that's what determines valid env # vars and/or values for typecasting. obj = self._config for key in key_path: obj = obj[key] return obj def _path_set(self, key_path, value): # Sets are to self.data since that's what we are presenting to the # outer config object and debugging. obj = self.data for key in key_path[:-1]: if key not in obj: obj[key] = {} obj = obj[key] old = self._path_get(key_path) new_ = self._cast(old, value) obj[key_path[-1]] = new_ def _cast(self, old, new_): if isinstance(old, BooleanType): return new_ not in ('0', '') elif isinstance(old, StringTypes): return new_ elif old is None: return new_ elif isinstance(old, (ListType, TupleType)): err = "Can't adapt an environment string into a {0}!" err = err.format(type(old)) raise UncastableEnvVar(err) else: return old.__class__(new_) class ExclusiveFile(object): """ File-loading config adapter that looks for one of N possible suffixes. For example, ``ExclusiveFile(prefix='/etc/invoke', suffixes=['yaml', 'json'])`` behaves similar to loading both of ``File('/etc/invoke.yaml')`` + ``File('/etc/invoke.json')``, with the distinction that if ``/etc/invoke.yaml`` is succesfully loaded, the JSON file is **not** loaded at all. (This means that the order of the ``suffixes`` parameter matters.) This provides an unambiguous config source-loading process, simplifying troubleshooting and (hopefully) reduces potential for confusion. :param str prefix: Everything but the file extension, e.g. ``/etc/invoke`` to load up files like ``/etc/invoke.yaml``. :param iterable suffixes: Optional iterable of file extensions like ``"yaml"`` or ``"json"``. Do not include any leading periods (i.e. don't say ``ExclusiveFile('/etc/invoke', '.yaml')``). Defaults to ``('yaml', 'json', 'py')``. """ def __init__(self, prefix, suffixes=None): if suffixes is None: suffixes = ('yaml', 'json', 'py') self.prefix = prefix self.suffixes = suffixes self.adapters = [ File( "{0}.{1}".format(prefix, x), python_uppercase=False, strict=False ) for x in suffixes ] self.data = {} self.loaded = None def __str__(self): return "ExclusiveFile({0}.{{{1}}})".format(self.prefix, ','.join(self.suffixes)) def load(self, formatter=None): for adapter in self.adapters: adapter.load(formatter=formatter) # Simply offload data from the 1st one to be found. # If none are found, our data remains empty as initialized. if adapter.found: self.data = adapter.data self.loaded = adapter.filepath return class DataProxy(object): """ Helper class implementing nested dict+attr access for `.Config`. """ # Attributes which get proxied through to inner etc.Config obj. _proxies = tuple(""" clear get has_key items iteritems iterkeys itervalues keys pop popitem setdefault update values """.split()) + tuple("__{0}__".format(x) for x in """ cmp contains iter sizeof """.split()) # Alt constructor used so we aren't getting in the way of Config's real # __init__(). @classmethod def from_data(cls, data): obj = cls() obj.config = data return obj def __getattr__(self, key): try: return self._get(key) except KeyError: # Proxy most special vars to config for dict procotol. if key in self._proxies: return getattr(self.config, key) # Otherwise, raise useful AttributeError to follow getattr proto. err = "No attribute or config key found for {0!r}".format(key) attrs = [x for x in dir(self.__class__) if not x.startswith('_')] err += "\n\nValid real attributes: {0!r}".format(attrs) err += "\n\nValid keys: {0!r}".format(self.config.keys()) raise AttributeError(err) def __hasattr__(self, key): return key in self.config or key in self._proxies def __iter__(self): # For some reason Python is ignoring our __hasattr__ when determining # whether we support __iter__. BOO return iter(self.config) def __eq__(self, other): # Can't proxy __eq__ because the RHS will always be an obj of the # current class, not the proxied-to class, and that causes # NotImplemented. return self.config == other.config def __len__(self): # Can't proxy __len__ either apparently? ugh return len(self.config) def __setitem__(self, key, value): # ... or __setitem__? thanks for nothing Python >:( self.config[key] = value def __delitem__(self, key): # OK this is really getting annoying del self.config[key] def __getitem__(self, key): return self._get(key) def _get(self, key): value = self.config[key] if isinstance(value, DictType): value = DataProxy.from_data(value) return value def __str__(self): return str(self.config) def __unicode__(self): return unicode(self.config) def __repr__(self): return repr(self.config) # TODO: copy()? class Config(DataProxy): """ Invoke's primary configuration handling class. See :doc:`/concepts/configuration` for details on the configuration system this class implements, including the :ref:`configuration hierarchy <config-hierarchy>`. The rest of this class' documentation assumes familiarity with that document. Lifecycle --------- Configuration data is constructed piecemeal starting at initialization time and config sources are loaded lazily upon request. For example, pure-Python configuration does not load from the filesystem or shell environment:: c = Config(defaults={'foo': 'bar'}) c.foo # No action taken, defaults are the only thing consulted If filesystem paths prefixes are given, they are scanned at access time and merged into the final config:: c = Config(system_prefix='/etc/invoke') c.foo # Attempts to load files like /etc/invoke.yaml c.foo # No filesystem action taken this time The merged config is regenerated any time config sources are updated, such as when Invoke's core machinery tells the default config object that it's time to load data from the shell environment:: c = Config(system_prefix='/etc/invoke') c.foo # Merging (and file load) occurs c.foo # No merging nor file loading - cache only c.load_shell_env() # Merging (but no file loads - only env) c.foo # Again, no merging or file loading takes place Access ------ Configuration values may be accessed using dict syntax:: config['foo'] or attribute syntax:: config.foo .. warning:: Any "real" attributes (methods, etc) on `Config` take precedence over settings values - so if you have top level settings named ``clone``, ``defaults``, etc, you *must* use dict syntax to access it. Nesting works the same way - dict config values are turned into objects which honor both the dictionary protocol and the attribute-access method:: config['foo']['bar'] config.foo.bar Non-data attributes & methods ----------------------------- This class implements the entire dictionary protocol: methods such as ``keys``, ``values``, ``items``, ``pop`` and so forth should all function as they do on regular dicts. Individual configuration 'levels' and their source locations (if applicable) may be accessed via attributes such as `.project`/`.project_file` and so forth - see the documentation for individual members below for details. """ def __init__(self, defaults=None, overrides=None, system_prefix=None, user_prefix=None, project_home=None, env_prefix=None, runtime_path=None): """ Creates a new config object. :param dict defaults: A dict containing default (lowest level) config data. Default: ``{}``. :param dict overrides: A dict containing override-level config data. Default: ``{}``. :param str system_prefix: Path & partial filename for the global config file location. Should include everything but the dot & file extension. Default: ``/etc/invoke`` (e.g. ``/etc/invoke.yaml`` or ``/etc/invoke.json``). :param str user_prefix: Like ``system_prefix`` but for the per-user config file. Default: ``~/.invoke`` (e.g. ``~/.invoke.yaml``). :param str project_home: Optional directory path location of the currently loaded `.Collection` (as loaded by `.Loader`). When non-empty, will trigger seeking of per-project config files in this location + ``invoke.(yaml|json|py)``. :param str env_prefix: Environment variable seek prefix; optional, defaults to ``None``. When not ``None``, only environment variables beginning with this value will be loaded. If it is set, the keys will have the prefix stripped out before processing, so e.g. ``env_prefix='INVOKE_'`` means users must set ``INVOKE_MYSETTING`` in the shell to affect the ``"mysetting"`` setting. :param str runtime_path: Optional file path to a runtime configuration file. Used to fill the penultimate slot in the config hierarchy. Should be a full file path to an existing file, not a directory path, or a prefix. """ # Technically an implementation detail - do not expose in public API. # Stores merged configs and is accessed via DataProxy. self.config = None #: Default configuration values, typically hardcoded in the #: CLI/execution machinery. self.defaults = {} if defaults is None else defaults #: Collection-driven config data, gathered from the collection tree #: containing the currently executing task. self.collection = {} #: Path prefix searched for the system config file. self.system_prefix = ('/etc/invoke' if system_prefix is None else system_prefix) #: Path to loaded system config file, if any. self.system_path = None #: Data loaded from the system config file. self.system = {} #: Path prefix searched for per-user config files. self.user_prefix = '~/.invoke' if user_prefix is None else user_prefix #: Path to loaded user config file, if any. self.user_path = None #: Data loaded from the per-user config file. self.user = {} #: Parent directory of the current root tasks file, if applicable. self.project_home = project_home #: Path to loaded per-project config file, if any. self.project_path = None #: Data loaded from the per-project config file. self.project = {} #: Environment variable name prefix # TODO: make this INVOKE_ and update tests, just deal self.env_prefix = '' if env_prefix is None else env_prefix #: Config data loaded from the shell environment. self.env = {} #: Path to the user-specified runtime config file. self.runtime_path = runtime_path # Data loaded from the runtime config file. self.runtime = {} #: Overrides - highest possible config level. Typically filled in from #: command-line flags. self.overrides = {} if overrides is None else overrides def load_shell_env(self): """ Load values from the shell environment, then trigger a config merge. This method is idempotent and does nothing if ``.shell`` is already non-``None``. `.load_shell_env` is intended for execution late in a `.Config` object's lifecycle, once all other sources have been merged. Loading from the shell is not terrifically expensive, but must be done at a specific point in time to ensure the "only valid options" behavior works correctly. See :ref:`env-vars` for details on this design decision and other info re: how environment variables are scanned and loaded. """ pass def set_collection(self, data): """ Update collection-driven config data, then trigger a config merge. This method is idempotent and does nothing if ``.collection`` is already non-``None``. `.set_collection` is intended for use by the core task execution machinery, which is responsible for obtaining per-task collection-driven data. See :ref:`collection-configuration` for details. """ pass def load(self, collection=None): """ Performs loading and merging of all config sources. See :ref:`config-hierarchy` for details on load order and file locations. :param dict collection: A dict containing collection-driven config data. Default: ``{}``. """ # Pull in defaults (we do so at this level because typically we won't # know about collection-level default values until closer to runtime. if collection is None: collection = {} # NOTE: can't use etc.AdapterSet.appendleft here, it is buggy, no time # to fix right now. Just insert at position 1 after the Defaults we # already know is there. self.config.adapters.insert(1, Basic(collection)) # Now that we have all other sources defined, we can load the Env # adapter. This sadly requires a 'pre-load' call to .load() so config # files get slurped up. self.config.load() env = NestedEnv(config=self.config, prefix=self.env_prefix) # Must break encapsulation a tiny bit here to ensure env vars come # before runtime config files in the hierarchy. It's the least bad way # right now given etc.Config's api. self.config.adapters.insert(len(self.config.adapters) - 2, env) # Re-load() so that our values get applied in the right slot in the # hierarchy. self.config.load() debug("Loading & merging config adapters in order...") for adapter in self.config.adapters: if isinstance(adapter, File) and not adapter.found: debug("Didn't see any {0}, skipping".format(adapter)) elif isinstance(adapter, ExclusiveFile): if adapter.loaded is None: debug("Didn't see any of {0}, skipping".format( adapter)) else: debug("{0} loaded {1}, got {2!r}".format( adapter, adapter.loaded, adapter.data)) else: # Wrap adapter in dict() so defaultdicts print nicer debug("Loaded {0}, got {1!r}".format( adapter, dict(adapter.data))) debug("Final merged config: {0!r}".format(self.config)) def clone(self): """ Return a copy of this configuration object. The new object will be identical in terms of configured sources and any loaded/merged data, but will be a distinct object with no shared mutable state. """ # New config w/ formatter preserved c = EtcConfig(formatter=self.config.formatter) # New adapters, ditto + deepcopy internal data adapters = [] for old in self.config.adapters: c.register(_clone_adapter(old)) # Then deepcopy loaded data in case already loaded (we don't # necessarily know at this point if loading has occurred). c.update(copy.deepcopy(dict(self.config))) # All set new = Config(env_prefix=self.env_prefix) new.config = c return new def _clone_adapter(old): if isinstance(old, (Defaults, Overrides)): new = old.__class__(formatter=old.formatter) elif isinstance(old, File): new = File( filepath=old.filepath, python_uppercase=old.python_uppercase, formatter=old.formatter, ) elif isinstance(old, ExclusiveFile): new = ExclusiveFile( prefix=old.prefix, suffixes=old.suffixes, ) elif isinstance(old, NestedEnv): new = NestedEnv(old._config) elif isinstance(old, Dummy): new = Dummy() elif isinstance(old, Basic): new = Basic(old.data) else: raise TypeError("No idea how to clone {0}!".format(old.__class__)) new.data = copy.deepcopy(old.data) return new
#! /usr/bin/python # -*- coding: utf-8 -*- """ Module is used for visualization of segmentation stored in pkl file. """ import sys import os.path import logging logger = logging.getLogger(__name__) import argparse if sys.version_info < (3, 0): import urllib as urllibr else: import urllib.request as urllibr import scipy import numpy as np import zipfile import glob import os.path as op import io3d # you can get hash from command line with: # python imtools/sample_data.py -v sliver_training_001 # vessels.pkl nejprve vytvoří prázný adresář s názvem vessels.pkl, pak jej při rozbalování zase smaže data_urls= { "head": ["http://147.228.240.61/queetech/sample-data/head.zip", "89e9b60fd23257f01c4a1632ff7bb800", "matlab"] , "jatra_06mm_jenjatra": ["http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip", "jatra_06mm_jenjatra/*.dcm"], "jatra_5mm": ["http://147.228.240.61/queetech/sample-data/jatra_5mm.zip", '1b9039ffe1ff9af9caa344341c8cec03', "jatra_06mm/*.dcm"], "exp": ["http://147.228.240.61/queetech/sample-data/exp.zip", '74f2c10b17b6bd31bd03662df6cf884d'], "sliver_training_001": ["http://147.228.240.61/queetech/sample-data/sliver_training_001.zip","d64235727c0adafe13d24bfb311d1ed0","liver*001.*"], "volumetrie": ["http://147.228.240.61/queetech/sample-data/volumetrie.zip","6b2a2da67874ba526e2fe00a78dd19c9"], "vessels.pkl": ["http://147.228.240.61/queetech/sample-data/vessels.pkl.zip","698ef2bc345bb616f8d4195048538ded"], "biodur_sample": ["http://147.228.240.61/queetech/sample-data/biodur_sample.zip","d459dd5b308ca07d10414b3a3a9000ea"], "gensei_slices": ["http://147.228.240.61/queetech/sample-data/gensei_slices.zip", "ef93b121add8e4a133bb086e9e6491c9"], "exp_small": ["http://147.228.240.61/queetech/sample-data/exp_small.zip", "0526ba8ea363fe8b5227f5807b7aaca7"], "vincentka": ["http://147.228.240.61/queetech/vincentka.zip", "a30fdabaa39c5ce032a3223ed30b88e3"], "vincentka_sample": ["http://147.228.240.61/queetech/sample-data/vincentka_sample.zip"], "donut": "http://147.228.240.61/queetech/sample-data/donut.zip", # není nutné pole, stačí jen string # "exp_small": "http://147.228.240.61/queetech/sample-data/exp_small.zip", } def download(dataset_label=None, destination_dir="."): """ Download sample data by data label. Labels can be listed by sample_data.data_urls.keys() :param dataset_label: label of data. If it is set to None, all data are downloaded :param destination_dir: output dir for data :return: """ try: os.mkdir(destination_dir) except: pass if dataset_label is None: dataset_label=data_urls.keys() if type(dataset_label) == str: dataset_label = [dataset_label] for label in dataset_label: # make all data:url have length 3 data_url = data_urls[label] if type(data_url) == str: # back compatibility data_url = [data_url] data_url.extend([None, None]) data_url = data_url[:3] url, expected_hash, hash_path = data_url if hash_path is None: hash_path = label try: computed_hash = checksum(os.path.join(destination_dir, hash_path)) except: # there is probably no checksumdir module logger.warning("problem with sample_data.checksum()") computed_hash = None logger.info("dataset '" + label + "'") logger.info("expected hash: '" + str(expected_hash) + "'") logger.info("computed hash: '" + str(computed_hash) + "'") if (computed_hash is not None) and (expected_hash == computed_hash): logger.info("match ok - no download needed") else: logger.info("downloading") downzip(url, destination=destination_dir) logger.info("finished") downloaded_hash = checksum(os.path.join(destination_dir, hash_path)) logger.info("downloaded hash: '" + str(downloaded_hash) + "'") if downloaded_hash != expected_hash: logger.warning("downloaded hash is different from expected hash\n" + \ "expected hash: '" + str(expected_hash) + "'\n" + \ "downloaded hash: '" + str(downloaded_hash) + "'\n") def get(dataset_label, id, destination_dir="."): """ Get the 3D data from specified dataset with specified id. Download data if necessary. :param dataset_label: :param id: integer or wildcards file pattern :param destination_dir: :return: """ datap = [] return datap def checksum(path, hashfunc='md5'): """ Return checksum given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: :param hashfunc: :return: """ import checksumdir hash_func = checksumdir.HASH_FUNCS.get(hashfunc) if not hash_func: raise NotImplementedError('{} not implemented.'.format(hashfunc)) if os.path.isdir(path): return checksumdir.dirhash(path, hashfunc=hashfunc) hashvalues = [] path_list = glob.glob(path) logger.debug("path_list " + str(path_list)) for path in path_list: if os.path.isfile(path): hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func)) logger.debug(str(hashvalues)) hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func) return hash def generate_donut(): """ Generate donut like shape with stick inside :return: datap with keys data3d, segmentation and voxelsize_mm """ import numpy as np segmentation = np.zeros([20, 30, 40]) # generate test data segmentation[6:10, 7:24, 10:37] = 1 segmentation[6:10, 7, 10] = 0 segmentation[6:10, 23, 10] = 0 segmentation[6:10, 7, 36] = 0 segmentation[6:10, 23, 36] = 0 segmentation[2:18, 12:19, 18:28] = 2 data3d = segmentation * 100 + np.random.random(segmentation.shape) * 30 voxelsize_mm=[3,2,1] import io3d datap = { 'data3d': data3d, 'segmentation': segmentation, 'voxelsize_mm': voxelsize_mm } # io3d.write(datap, "donut.pklz") return datap def generate_abdominal(size = 100, liver_intensity=100, noise_intensity=20, portal_vein_intensity=130, spleen_intensity=90): boundary = int(size/4) voxelsize_mm = [1.0, 1.5, 1.5] slab = { 'liver': 1, 'porta': 2, 'spleen': 17 } segmentation = np.zeros([size, size, size], dtype=np.uint8) segmentation[boundary:-boundary, boundary:-2*boundary, 2*boundary:-boundary] = 1 segmentation[:, boundary*2:boundary*2+5, boundary*2:boundary*2+5] = 2 segmentation[:, boundary*2:boundary*2+5, boundary*2:boundary*2+5] = 2 segmentation[:, -5:, -boundary:] = 17 seeds = np.zeros([size, size, size], dtype=np.uint8) seeds[ boundary + 1 : boundary + 4, boundary + 1 : boundary + 4, 2 * boundary + 1 : 2 * boundary + 4 ] = 1 noise = (np.random.random(segmentation.shape) * noise_intensity).astype(np.int) data3d = np.zeros(segmentation.shape, dtype=np.int) data3d [segmentation == 1] = liver_intensity data3d [segmentation == 2] = portal_vein_intensity data3d [segmentation == 17] = spleen_intensity data3d += noise datap = { 'data3d': data3d, 'segmentation': segmentation, 'voxelsize_mm': voxelsize_mm, 'seeds': seeds, 'slab': slab } return datap def sliver_reader(filename_end_mask="*[0-9].mhd", sliver_reference_dir="~/data/medical/orig/sliver07/training/", read_orig=True, read_seg=False): """ Generator for reading sliver data from directory structure. :param filename_end_mask: file selection can be controlled with this parameter :param sliver_reference_dir: directory with sliver .mhd and .raw files :param read_orig: read image data if is set True :param read_seg: read segmentation data if is set True :return: numeric_label, vs_mm, oname, orig_data, rname, ref_data """ sliver_reference_dir = op.expanduser(sliver_reference_dir) orig_fnames = glob.glob(sliver_reference_dir + "*orig" + filename_end_mask) ref_fnames = glob.glob(sliver_reference_dir + "*seg"+ filename_end_mask) orig_fnames.sort() ref_fnames.sort() output = [] for i in range(0, len(orig_fnames)): oname = orig_fnames[i] rname = ref_fnames[i] vs_mm = None ref_data= None orig_data = None if read_orig: orig_data, metadata = io3d.datareader.read(oname) vs_mm = metadata['voxelsize_mm'] if read_seg: ref_data, metadata = io3d.datareader.read(rname) vs_mm = metadata['voxelsize_mm'] import re numeric_label = re.search(".*g(\d+)", oname).group(1) out = (numeric_label, vs_mm, oname, orig_data, rname, ref_data) yield out def main(): logger = logging.getLogger() logger.setLevel(logging.WARNING) ch = logging.StreamHandler() logger.addHandler(ch) #logger.debug('input params') # input parser parser = argparse.ArgumentParser( description= "Work on dataset") parser.add_argument( "-l", "--labels", metavar="N", nargs="+", default=None, help='Get sample data') parser.add_argument( '-L', '--print_labels', action="store_true", default=False, help='print all available labels') parser.add_argument( '-c', '--checksum', # action="store_true", default=None, help='Get hash for requested path') parser.add_argument( '-v', '--verbatim', action="store_true", default=False, help='more messages') parser.add_argument( '-d', '--debug', # action="store_true", default=None, help='set debug level') parser.add_argument( '-o', '--destination_dir', default=".", help='set output directory') args = parser.parse_args() # if args.get_sample_data == False and args.install == False and args.build_gco == False: ## default setup is install and get sample data # args.get_sample_data = True # args.install = True # args.build_gco = False if args.verbatim: # logger.setLevel(logging.DEBUG) logger.setLevel(logging.INFO) if args.debug is not None: logger.setLevel(int(args.debug)) if args.checksum is not None: print(checksum(args.checksum)) if args.labels is None: return download(args.labels, destination_dir=args.destination_dir) #submodule_update() def remove(local_file_name): try: os.remove(local_file_name) except Exception as e: print ("Cannot remove file '" + local_file_name + "'. Please remove\ it manually.") print (e) def downzip(url, destination='./sample_data/'): """ Download, unzip and delete. """ # url = "http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip" logmsg = "downloading from '" + url + "'" print(logmsg) logger.debug(logmsg) local_file_name = os.path.join(destination, 'tmp.zip') urllibr.urlretrieve(url, local_file_name) datafile = zipfile.ZipFile(local_file_name) datafile.extractall(destination) remove(local_file_name) if __name__ == "__main__": main() todo added #! /usr/bin/python # -*- coding: utf-8 -*- """ Module is used for visualization of segmentation stored in pkl file. """ import sys import os.path import logging logger = logging.getLogger(__name__) import argparse if sys.version_info < (3, 0): import urllib as urllibr else: import urllib.request as urllibr import scipy import numpy as np import zipfile import glob import os.path as op import io3d # you can get hash from command line with: # python imtools/sample_data.py -v sliver_training_001 # vessels.pkl nejprve vytvoří prázný adresář s názvem vessels.pkl, pak jej při rozbalování zase smaže data_urls= { "head": ["http://147.228.240.61/queetech/sample-data/head.zip", "89e9b60fd23257f01c4a1632ff7bb800", "matlab"] , "jatra_06mm_jenjatra": ["http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip", "jatra_06mm_jenjatra/*.dcm"], "jatra_5mm": ["http://147.228.240.61/queetech/sample-data/jatra_5mm.zip", '1b9039ffe1ff9af9caa344341c8cec03', "jatra_06mm/*.dcm"], "exp": ["http://147.228.240.61/queetech/sample-data/exp.zip", '74f2c10b17b6bd31bd03662df6cf884d'], "sliver_training_001": ["http://147.228.240.61/queetech/sample-data/sliver_training_001.zip","d64235727c0adafe13d24bfb311d1ed0","liver*001.*"], "volumetrie": ["http://147.228.240.61/queetech/sample-data/volumetrie.zip","6b2a2da67874ba526e2fe00a78dd19c9"], "vessels.pkl": ["http://147.228.240.61/queetech/sample-data/vessels.pkl.zip","698ef2bc345bb616f8d4195048538ded"], "biodur_sample": ["http://147.228.240.61/queetech/sample-data/biodur_sample.zip","d459dd5b308ca07d10414b3a3a9000ea"], "gensei_slices": ["http://147.228.240.61/queetech/sample-data/gensei_slices.zip", "ef93b121add8e4a133bb086e9e6491c9"], "exp_small": ["http://147.228.240.61/queetech/sample-data/exp_small.zip", "0526ba8ea363fe8b5227f5807b7aaca7"], "vincentka": ["http://147.228.240.61/queetech/vincentka.zip", "a30fdabaa39c5ce032a3223ed30b88e3"], "vincentka_sample": ["http://147.228.240.61/queetech/sample-data/vincentka_sample.zip"], "donut": "http://147.228.240.61/queetech/sample-data/donut.zip", # není nutné pole, stačí jen string # "exp_small": "http://147.228.240.61/queetech/sample-data/exp_small.zip", } def download(dataset_label=None, destination_dir="."): """ Download sample data by data label. Labels can be listed by sample_data.data_urls.keys() :param dataset_label: label of data. If it is set to None, all data are downloaded :param destination_dir: output dir for data :return: """ try: os.mkdir(destination_dir) except: pass if dataset_label is None: dataset_label=data_urls.keys() if type(dataset_label) == str: dataset_label = [dataset_label] for label in dataset_label: # make all data:url have length 3 data_url = data_urls[label] if type(data_url) == str: # back compatibility data_url = [data_url] data_url.extend([None, None]) data_url = data_url[:3] url, expected_hash, hash_path = data_url if hash_path is None: hash_path = label try: computed_hash = checksum(os.path.join(destination_dir, hash_path)) except: # there is probably no checksumdir module logger.warning("problem with sample_data.checksum()") computed_hash = None logger.info("dataset '" + label + "'") logger.info("expected hash: '" + str(expected_hash) + "'") logger.info("computed hash: '" + str(computed_hash) + "'") if (computed_hash is not None) and (expected_hash == computed_hash): logger.info("match ok - no download needed") else: logger.info("downloading") downzip(url, destination=destination_dir) logger.info("finished") downloaded_hash = checksum(os.path.join(destination_dir, hash_path)) logger.info("downloaded hash: '" + str(downloaded_hash) + "'") if downloaded_hash != expected_hash: logger.warning("downloaded hash is different from expected hash\n" + \ "expected hash: '" + str(expected_hash) + "'\n" + \ "downloaded hash: '" + str(downloaded_hash) + "'\n") def get(dataset_label, id, destination_dir="."): """ Get the 3D data from specified dataset with specified id. Download data if necessary. :param dataset_label: :param id: integer or wildcards file pattern :param destination_dir: :return: """ # @TODO implement datap = [] return datap def checksum(path, hashfunc='md5'): """ Return checksum given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: :param hashfunc: :return: """ import checksumdir hash_func = checksumdir.HASH_FUNCS.get(hashfunc) if not hash_func: raise NotImplementedError('{} not implemented.'.format(hashfunc)) if os.path.isdir(path): return checksumdir.dirhash(path, hashfunc=hashfunc) hashvalues = [] path_list = glob.glob(path) logger.debug("path_list " + str(path_list)) for path in path_list: if os.path.isfile(path): hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func)) logger.debug(str(hashvalues)) hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func) return hash def generate_donut(): """ Generate donut like shape with stick inside :return: datap with keys data3d, segmentation and voxelsize_mm """ import numpy as np segmentation = np.zeros([20, 30, 40]) # generate test data segmentation[6:10, 7:24, 10:37] = 1 segmentation[6:10, 7, 10] = 0 segmentation[6:10, 23, 10] = 0 segmentation[6:10, 7, 36] = 0 segmentation[6:10, 23, 36] = 0 segmentation[2:18, 12:19, 18:28] = 2 data3d = segmentation * 100 + np.random.random(segmentation.shape) * 30 voxelsize_mm=[3,2,1] import io3d datap = { 'data3d': data3d, 'segmentation': segmentation, 'voxelsize_mm': voxelsize_mm } # io3d.write(datap, "donut.pklz") return datap def generate_abdominal(size = 100, liver_intensity=100, noise_intensity=20, portal_vein_intensity=130, spleen_intensity=90): boundary = int(size/4) voxelsize_mm = [1.0, 1.5, 1.5] slab = { 'liver': 1, 'porta': 2, 'spleen': 17 } segmentation = np.zeros([size, size, size], dtype=np.uint8) segmentation[boundary:-boundary, boundary:-2*boundary, 2*boundary:-boundary] = 1 segmentation[:, boundary*2:boundary*2+5, boundary*2:boundary*2+5] = 2 segmentation[:, boundary*2:boundary*2+5, boundary*2:boundary*2+5] = 2 segmentation[:, -5:, -boundary:] = 17 seeds = np.zeros([size, size, size], dtype=np.uint8) seeds[ boundary + 1 : boundary + 4, boundary + 1 : boundary + 4, 2 * boundary + 1 : 2 * boundary + 4 ] = 1 noise = (np.random.random(segmentation.shape) * noise_intensity).astype(np.int) data3d = np.zeros(segmentation.shape, dtype=np.int) data3d [segmentation == 1] = liver_intensity data3d [segmentation == 2] = portal_vein_intensity data3d [segmentation == 17] = spleen_intensity data3d += noise datap = { 'data3d': data3d, 'segmentation': segmentation, 'voxelsize_mm': voxelsize_mm, 'seeds': seeds, 'slab': slab } return datap def sliver_reader(filename_end_mask="*[0-9].mhd", sliver_reference_dir="~/data/medical/orig/sliver07/training/", read_orig=True, read_seg=False): """ Generator for reading sliver data from directory structure. :param filename_end_mask: file selection can be controlled with this parameter :param sliver_reference_dir: directory with sliver .mhd and .raw files :param read_orig: read image data if is set True :param read_seg: read segmentation data if is set True :return: numeric_label, vs_mm, oname, orig_data, rname, ref_data """ sliver_reference_dir = op.expanduser(sliver_reference_dir) orig_fnames = glob.glob(sliver_reference_dir + "*orig" + filename_end_mask) ref_fnames = glob.glob(sliver_reference_dir + "*seg"+ filename_end_mask) orig_fnames.sort() ref_fnames.sort() output = [] for i in range(0, len(orig_fnames)): oname = orig_fnames[i] rname = ref_fnames[i] vs_mm = None ref_data= None orig_data = None if read_orig: orig_data, metadata = io3d.datareader.read(oname) vs_mm = metadata['voxelsize_mm'] if read_seg: ref_data, metadata = io3d.datareader.read(rname) vs_mm = metadata['voxelsize_mm'] import re numeric_label = re.search(".*g(\d+)", oname).group(1) out = (numeric_label, vs_mm, oname, orig_data, rname, ref_data) yield out def main(): logger = logging.getLogger() logger.setLevel(logging.WARNING) ch = logging.StreamHandler() logger.addHandler(ch) #logger.debug('input params') # input parser parser = argparse.ArgumentParser( description= "Work on dataset") parser.add_argument( "-l", "--labels", metavar="N", nargs="+", default=None, help='Get sample data') parser.add_argument( '-L', '--print_labels', action="store_true", default=False, help='print all available labels') parser.add_argument( '-c', '--checksum', # action="store_true", default=None, help='Get hash for requested path') parser.add_argument( '-v', '--verbatim', action="store_true", default=False, help='more messages') parser.add_argument( '-d', '--debug', # action="store_true", default=None, help='set debug level') parser.add_argument( '-o', '--destination_dir', default=".", help='set output directory') args = parser.parse_args() # if args.get_sample_data == False and args.install == False and args.build_gco == False: ## default setup is install and get sample data # args.get_sample_data = True # args.install = True # args.build_gco = False if args.verbatim: # logger.setLevel(logging.DEBUG) logger.setLevel(logging.INFO) if args.debug is not None: logger.setLevel(int(args.debug)) if args.checksum is not None: print(checksum(args.checksum)) if args.labels is None: return download(args.labels, destination_dir=args.destination_dir) #submodule_update() def remove(local_file_name): try: os.remove(local_file_name) except Exception as e: print ("Cannot remove file '" + local_file_name + "'. Please remove\ it manually.") print (e) def downzip(url, destination='./sample_data/'): """ Download, unzip and delete. """ # url = "http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip" logmsg = "downloading from '" + url + "'" print(logmsg) logger.debug(logmsg) local_file_name = os.path.join(destination, 'tmp.zip') urllibr.urlretrieve(url, local_file_name) datafile = zipfile.ZipFile(local_file_name) datafile.extractall(destination) remove(local_file_name) if __name__ == "__main__": main()
""" panels Contains blender UI panels to allow editing of custom data """ import bpy class DataPanel(object): bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "data" class EDMDataPanel(DataPanel, bpy.types.Panel): bl_idname = "OBJECT_PT_edmtools" bl_label = "EDM Tools" @classmethod def poll(cls, context): return context.object.type == 'EMPTY' or context.object.type == "MESH" def draw(self, context): if context.object.type == "EMPTY": self.layout.prop(context.object.edm, "is_connector") elif context.object.type == "MESH": self.layout.prop(context.object.edm, "is_renderable") self.layout.prop(context.object.edm, "is_collision_shell") # self.layout.prop(context.object.edm, "damage_argument") class EDMEmptyLODPanel(DataPanel, bpy.types.Panel): bl_idname = "OBJECT_PT_edmLOD" bl_label = "LOD Root" @classmethod def poll(cls, context): return context.object.type == "EMPTY" def draw_header(self, context): self.layout.prop(context.object.edm, "is_lod_root", text="") def draw(self, context): if not context.object.edm.is_lod_root: return # Sort LOD children by the LOD distance children = sorted(context.object.children, key=lambda x: (x.edm.lod_min_distance, x.edm.lod_max_distance)) for i, child in enumerate(children): box = self.layout.box() row = box.row() row.label(text=child.name, icon="OBJECT_DATA") row.prop(child.edm, "nouse_lod_distance") box.prop(child.edm, "lod_min_distance") row = box.row() row.active = not child.edm.nouse_lod_distance row.prop(child.edm, "lod_max_distance") class DopeActionProperties(bpy.types.Panel): """Creates a Panel in the Object properties window""" bl_label = "EDM Action Properties" bl_idname = "OBJECT_PT_dope_action" bl_space_type = 'DOPESHEET_EDITOR' bl_region_type = 'UI' bl_context = "action" @classmethod def poll(self, context): try: return context.object.animation_data.action != None except AttributeError: return False def draw(self, context): row = self.layout.row() row.prop(context.object.animation_data.action, "argument") class EDMMaterialPanel(bpy.types.Panel): bl_label = "EDM Material Properties" bl_idname = "SCENE_PT_edm_materials" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "material" @classmethod def poll(self, context): return context.object.active_material != None def draw(self, context): layout = self.layout layout.label(text="EDM Base material:") layout.prop(context.object.active_material, "edm_material", text="") layout.prop(context.object.active_material, "edm_blending", text="Opacity") def draw_timeline_argument_property(self, context): scene = context.scene layout = self.layout layout.prop(scene, "active_edm_argument", text="Argument") def register(): bpy.utils.register_class(EDMDataPanel) bpy.utils.register_class(EDMEmptyLODPanel) bpy.utils.register_class(DopeActionProperties) # bpy.types.TIME_HT_header.append(draw_timeline_argument_property) def unregister(): # bpy.types.TIME_HT_header.remove(draw_timeline_argument_property) bpy.utils.unregister_class(DopeActionProperties) bpy.utils.unregister_class(EDMEmptyLODPanel) bpy.utils.unregister_class(EDMDataPanel) # import bpy # #bpy.types.Object.is_connector = bpy.props.BoolProperty( # ## default=False, # # name="Is Connector?", # # description="Is this empty a connector object?") # # def register(): # bpy.utils.register_class(HelloWorldPanel) # def unregister(): # bpy.utils.unregister_class(HelloWorldPanel) # if __name__ == "__main__": # register() Hide the 'max' LOD distance if not using """ panels Contains blender UI panels to allow editing of custom data """ import bpy class DataPanel(object): bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "data" class EDMDataPanel(DataPanel, bpy.types.Panel): bl_idname = "OBJECT_PT_edmtools" bl_label = "EDM Tools" @classmethod def poll(cls, context): return context.object.type == 'EMPTY' or context.object.type == "MESH" def draw(self, context): if context.object.type == "EMPTY": self.layout.prop(context.object.edm, "is_connector") elif context.object.type == "MESH": self.layout.prop(context.object.edm, "is_renderable") self.layout.prop(context.object.edm, "is_collision_shell") # self.layout.prop(context.object.edm, "damage_argument") class EDMEmptyLODPanel(DataPanel, bpy.types.Panel): bl_idname = "OBJECT_PT_edmLOD" bl_label = "LOD Root" @classmethod def poll(cls, context): return context.object.type == "EMPTY" def draw_header(self, context): self.layout.prop(context.object.edm, "is_lod_root", text="") def draw(self, context): if not context.object.edm.is_lod_root: return # Sort LOD children by the LOD distance children = sorted(context.object.children, key=lambda x: (x.edm.lod_min_distance, x.edm.lod_max_distance)) for i, child in enumerate(children): box = self.layout.box() row = box.row() row.label(text=child.name, icon="OBJECT_DATA") row.prop(child.edm, "nouse_lod_distance") box.prop(child.edm, "lod_min_distance") if not child.edm.nouse_lod_distance: row = box.row() row.active = not child.edm.nouse_lod_distance row.prop(child.edm, "lod_max_distance") class DopeActionProperties(bpy.types.Panel): """Creates a Panel in the Object properties window""" bl_label = "EDM Action Properties" bl_idname = "OBJECT_PT_dope_action" bl_space_type = 'DOPESHEET_EDITOR' bl_region_type = 'UI' bl_context = "action" @classmethod def poll(self, context): try: return context.object.animation_data.action != None except AttributeError: return False def draw(self, context): row = self.layout.row() row.prop(context.object.animation_data.action, "argument") class EDMMaterialPanel(bpy.types.Panel): bl_label = "EDM Material Properties" bl_idname = "SCENE_PT_edm_materials" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "material" @classmethod def poll(self, context): return context.object.active_material != None def draw(self, context): layout = self.layout layout.label(text="EDM Base material:") layout.prop(context.object.active_material, "edm_material", text="") layout.prop(context.object.active_material, "edm_blending", text="Opacity") def draw_timeline_argument_property(self, context): scene = context.scene layout = self.layout layout.prop(scene, "active_edm_argument", text="Argument") def register(): bpy.utils.register_class(EDMDataPanel) bpy.utils.register_class(EDMEmptyLODPanel) bpy.utils.register_class(DopeActionProperties) # bpy.types.TIME_HT_header.append(draw_timeline_argument_property) def unregister(): # bpy.types.TIME_HT_header.remove(draw_timeline_argument_property) bpy.utils.unregister_class(DopeActionProperties) bpy.utils.unregister_class(EDMEmptyLODPanel) bpy.utils.unregister_class(EDMDataPanel) # import bpy # #bpy.types.Object.is_connector = bpy.props.BoolProperty( # ## default=False, # # name="Is Connector?", # # description="Is this empty a connector object?") # # def register(): # bpy.utils.register_class(HelloWorldPanel) # def unregister(): # bpy.utils.unregister_class(HelloWorldPanel) # if __name__ == "__main__": # register()
Added diversity extraction script
# coding=utf-8 # Copyright 2019 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Trax layers library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import jax import numpy as onp from tensor2tensor.trax import backend from tensor2tensor.trax.backend import numpy as np from tensor2tensor.trax.layers import base from tensor2tensor.trax.layers import initializers as init @base.layer() def Relu(x, **unused_kwargs): return np.maximum(x, np.zeros_like(x)) @base.layer() def ParametricRelu(x, a=1., **unused_kwargs): return np.maximum(a * x, np.zeros_like(x)) @base.layer() def LeakyRelu(x, a=0.01, **unused_kwargs): return np.where(x >= 0, x, a * x) @base.layer() def Elu(x, a=1., **unused_kwargs): return np.where(x > 0, x, a * np.expm1(x)) @base.layer() def Selu(x, alpha=1.6732632423543772848170429916717, lmbda=1.0507009873554804934193349852946): return lmbda * np.where(x > 0, x, alpha * np.expm1(x)) @base.layer() def Gelu(x, **unused_kwargs): return x * backend.erf(x) @base.layer() def Sigmoid(x, **unused_kwargs): return backend.expit(x) @base.layer() def Tanh(x, **unused_kwargs): return np.tanh(x) @base.layer() def HardSigmoid(x, **unused_kwargs): """Linear approximation to sigmoid.""" return np.maximum(0, np.minimum(1, (1 + x))) @base.layer() def HardTanh(x, **unused_kwargs): """Linear approximation to tanh.""" return np.maximum(-1, np.minimum(1, x)) @base.layer() def Exp(x, **unused_kwargs): return np.exp(x) @base.layer() def LogSoftmax(x, axis=-1, **unused_kwargs): """Apply log softmax to x: log-normalize along the given axis.""" return x - backend.logsumexp(x, axis, keepdims=True) @base.layer() def Softmax(x, axis=-1, **unused_kwargs): """Apply softmax to x: exponentiate and normalize along the given axis.""" return np.exp(x - backend.logsumexp(x, axis, keepdims=True)) @base.layer() def Softplus(x, **unused_kwargs): return np.logaddexp(x, 0.) @base.layer() def ToFloat(x, **unused_kwargs): return x.astype(onp.float32) class Dense(base.Layer): """A dense (a.k.a. fully-connected, affine) layer.""" def __init__(self, n_units, kernel_initializer=init.GlorotUniformInitializer(), bias_initializer=init.RandomNormalInitializer(1e-6)): super(Dense, self).__init__() self._n_units = n_units self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer def forward(self, x, params=(), state=(), **kwargs): del kwargs w, b = params return np.dot(x, w) + b, state def new_params_and_state(self, input_shape, input_dtype, rng): del input_dtype rng1, rng2 = backend.random.split(rng, 2) w = self._kernel_initializer((input_shape[-1], self._n_units), rng1) b = self._bias_initializer((self._n_units,), rng2) return (w, b), () class Embedding(base.Layer): """Layer constructor function for an embedding layer.""" def __init__(self, d_feature, vocab_size, kernel_initializer=init.GlorotUniformInitializer()): super(Embedding, self).__init__() self._d_feature = d_feature # feature dimensionality self._vocab_size = vocab_size self._kernel_initializer = kernel_initializer def forward(self, x, params=(), state=(), **kwargs): del kwargs return np.take(params, x, axis=0), state def new_params_and_state(self, input_shape, input_dtype, rng): del input_shape, input_dtype out_dim = (self._vocab_size, self._d_feature) params = self._kernel_initializer(out_dim, rng) return params, () # Flatten. @base.layer() def Flatten(x, n_axes_to_keep=1, **unused_kwargs): if n_axes_to_keep >= len(x.shape): raise ValueError("n_axes_to_keep[%d] should be less than input's rank[%d]" % (n_axes_to_keep, len(x.shape))) return np.reshape(x, (x.shape[:n_axes_to_keep] + (-1,))) class Dropout(base.Layer): """Dropout.""" def __init__(self, rate=0.0, name='dropout', mode='train'): super(Dropout, self).__init__() self._initial_rate = rate # TODO(lukaszkaiser): remove the name property by the end of September'19. # It's only needed for a specific purpose in the short term, will go. self._name = 'dropout_' + name self._mode = mode def new_params_and_state(self, input_shape, input_dtype, rng): del input_shape, input_dtype, rng params = () state = {self._name: np.array(self._initial_rate)} return params, state def forward(self, x, params=(), state=(), rng=None, **kwargs): """Execute dropout.""" del kwargs rate = self._initial_rate if isinstance(state, dict) and self._name in state: rate = state[self._name] if rng is None: msg = ('Dropout layer requires apply_fn to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, inputs)`, call ' 'it like `Dropout(params, inputs, rng=key)`.') raise ValueError(msg) if self._mode != 'train': return x, state keep = backend.random.bernoulli(rng, 1.0 - rate, x.shape) return np.where(keep, x / (1.0 - rate), np.zeros_like(x)), state @base.layer() def Div(x, divisor=1.0, **unused_kwargs): return x / divisor @base.layer() def AddConstant(x, constant=0.0, **unused_kwargs): return x + constant @base.layer() def MulConstant(x, params, constant=1.0, **unused_kwargs): del params return x * constant def one_hot(x, size, dtype=np.float32): # pylint: disable=invalid-name """Make a n+1 dim one-hot array from n dim int-categorical array.""" arange_size = np.arange(size) if backend.get_name() == 'jax': # Work around a jax broadcasting issue. arange_size = jax.lax.tie_in(x, arange_size) return np.array(x[..., np.newaxis] == arange_size, dtype) # Mean. @base.layer() def Mean(x, axis=-1, keepdims=False, **unused_kwargs): return np.mean(x, axis=axis, keepdims=keepdims) def log_gaussian_pdf(x, mu, sigma): # pylint: disable=invalid-name """Compute log N(x | mu, sigma).""" a = mu.shape[-1] * np.log(2 * np.pi) _, b = np.linalg.slogdet(sigma) y = np.linalg.solve(sigma, x - mu) y = np.expand_dims(y, axis=-1) xm = np.expand_dims(x - mu, axis=-2) c = np.matmul(xm, y) c = np.squeeze(np.squeeze(c, axis=-1), axis=-1) return -0.5 * (a + b + c) def log_gaussian_diag_pdf(x, mu, diag_sigma): # pylint: disable=invalid-name """Compute log N(x | mu, eye(diag_sigma)).""" a = mu.shape[-1] * np.log(2 * np.pi) b = np.sum(np.log(diag_sigma), axis=-1) y = x - mu / diag_sigma y = np.expand_dims(y, axis=-1) xm = np.expand_dims(x - mu, axis=-2) c = np.matmul(xm, y) c = np.squeeze(np.squeeze(c, axis=-1), axis=-1) return -0.5 * (a + b + c) def multigaussian_loss(preds, targets, ngauss=1): # pylint: disable=invalid-name """Compute mixture of gaussians loss.""" ndims = targets.shape[-1] logits = preds[:, :ngauss] mus = preds[:, ngauss:ngauss*(ndims + 1)] sigmas = preds[:, ngauss(ndims + 1):] sigmas = sigmas * sigmas + 1e-6 # Make positive. loglogits = logits - backend.logsumexp(logits, axis=-1, keepdims=True) mus = np.reshape(mus, [-1, ngauss, ndims]) sigmas = np.reshape(sigmas, [-1, ngauss, ndims]) targets = np.reshape(targets, [-1, 1, ndims]) glogprobs = log_gaussian_diag_pdf(targets, mus, sigmas) return backend.logsumexp(loglogits + glogprobs, axis=-1) Remove unused params arg from MulConstant. PiperOrigin-RevId: 272685588 # coding=utf-8 # Copyright 2019 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Trax layers library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import jax import numpy as onp from tensor2tensor.trax import backend from tensor2tensor.trax.backend import numpy as np from tensor2tensor.trax.layers import base from tensor2tensor.trax.layers import initializers as init @base.layer() def Relu(x, **unused_kwargs): return np.maximum(x, np.zeros_like(x)) @base.layer() def ParametricRelu(x, a=1., **unused_kwargs): return np.maximum(a * x, np.zeros_like(x)) @base.layer() def LeakyRelu(x, a=0.01, **unused_kwargs): return np.where(x >= 0, x, a * x) @base.layer() def Elu(x, a=1., **unused_kwargs): return np.where(x > 0, x, a * np.expm1(x)) @base.layer() def Selu(x, alpha=1.6732632423543772848170429916717, lmbda=1.0507009873554804934193349852946): return lmbda * np.where(x > 0, x, alpha * np.expm1(x)) @base.layer() def Gelu(x, **unused_kwargs): return x * backend.erf(x) @base.layer() def Sigmoid(x, **unused_kwargs): return backend.expit(x) @base.layer() def Tanh(x, **unused_kwargs): return np.tanh(x) @base.layer() def HardSigmoid(x, **unused_kwargs): """Linear approximation to sigmoid.""" return np.maximum(0, np.minimum(1, (1 + x))) @base.layer() def HardTanh(x, **unused_kwargs): """Linear approximation to tanh.""" return np.maximum(-1, np.minimum(1, x)) @base.layer() def Exp(x, **unused_kwargs): return np.exp(x) @base.layer() def LogSoftmax(x, axis=-1, **unused_kwargs): """Apply log softmax to x: log-normalize along the given axis.""" return x - backend.logsumexp(x, axis, keepdims=True) @base.layer() def Softmax(x, axis=-1, **unused_kwargs): """Apply softmax to x: exponentiate and normalize along the given axis.""" return np.exp(x - backend.logsumexp(x, axis, keepdims=True)) @base.layer() def Softplus(x, **unused_kwargs): return np.logaddexp(x, 0.) @base.layer() def ToFloat(x, **unused_kwargs): return x.astype(onp.float32) class Dense(base.Layer): """A dense (a.k.a. fully-connected, affine) layer.""" def __init__(self, n_units, kernel_initializer=init.GlorotUniformInitializer(), bias_initializer=init.RandomNormalInitializer(1e-6)): super(Dense, self).__init__() self._n_units = n_units self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer def forward(self, x, params=(), state=(), **kwargs): del kwargs w, b = params return np.dot(x, w) + b, state def new_params_and_state(self, input_shape, input_dtype, rng): del input_dtype rng1, rng2 = backend.random.split(rng, 2) w = self._kernel_initializer((input_shape[-1], self._n_units), rng1) b = self._bias_initializer((self._n_units,), rng2) return (w, b), () class Embedding(base.Layer): """Layer constructor function for an embedding layer.""" def __init__(self, d_feature, vocab_size, kernel_initializer=init.GlorotUniformInitializer()): super(Embedding, self).__init__() self._d_feature = d_feature # feature dimensionality self._vocab_size = vocab_size self._kernel_initializer = kernel_initializer def forward(self, x, params=(), state=(), **kwargs): del kwargs return np.take(params, x, axis=0), state def new_params_and_state(self, input_shape, input_dtype, rng): del input_shape, input_dtype out_dim = (self._vocab_size, self._d_feature) params = self._kernel_initializer(out_dim, rng) return params, () # Flatten. @base.layer() def Flatten(x, n_axes_to_keep=1, **unused_kwargs): if n_axes_to_keep >= len(x.shape): raise ValueError("n_axes_to_keep[%d] should be less than input's rank[%d]" % (n_axes_to_keep, len(x.shape))) return np.reshape(x, (x.shape[:n_axes_to_keep] + (-1,))) class Dropout(base.Layer): """Dropout.""" def __init__(self, rate=0.0, name='dropout', mode='train'): super(Dropout, self).__init__() self._initial_rate = rate # TODO(lukaszkaiser): remove the name property by the end of September'19. # It's only needed for a specific purpose in the short term, will go. self._name = 'dropout_' + name self._mode = mode def new_params_and_state(self, input_shape, input_dtype, rng): del input_shape, input_dtype, rng params = () state = {self._name: np.array(self._initial_rate)} return params, state def forward(self, x, params=(), state=(), rng=None, **kwargs): """Execute dropout.""" del kwargs rate = self._initial_rate if isinstance(state, dict) and self._name in state: rate = state[self._name] if rng is None: msg = ('Dropout layer requires apply_fn to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, inputs)`, call ' 'it like `Dropout(params, inputs, rng=key)`.') raise ValueError(msg) if self._mode != 'train': return x, state keep = backend.random.bernoulli(rng, 1.0 - rate, x.shape) return np.where(keep, x / (1.0 - rate), np.zeros_like(x)), state @base.layer() def Div(x, divisor=1.0, **unused_kwargs): return x / divisor @base.layer() def AddConstant(x, constant=0.0, **unused_kwargs): return x + constant @base.layer() def MulConstant(x, constant=1.0, **unused_kwargs): return x * constant def one_hot(x, size, dtype=np.float32): # pylint: disable=invalid-name """Make a n+1 dim one-hot array from n dim int-categorical array.""" arange_size = np.arange(size) if backend.get_name() == 'jax': # Work around a jax broadcasting issue. arange_size = jax.lax.tie_in(x, arange_size) return np.array(x[..., np.newaxis] == arange_size, dtype) # Mean. @base.layer() def Mean(x, axis=-1, keepdims=False, **unused_kwargs): return np.mean(x, axis=axis, keepdims=keepdims) def log_gaussian_pdf(x, mu, sigma): # pylint: disable=invalid-name """Compute log N(x | mu, sigma).""" a = mu.shape[-1] * np.log(2 * np.pi) _, b = np.linalg.slogdet(sigma) y = np.linalg.solve(sigma, x - mu) y = np.expand_dims(y, axis=-1) xm = np.expand_dims(x - mu, axis=-2) c = np.matmul(xm, y) c = np.squeeze(np.squeeze(c, axis=-1), axis=-1) return -0.5 * (a + b + c) def log_gaussian_diag_pdf(x, mu, diag_sigma): # pylint: disable=invalid-name """Compute log N(x | mu, eye(diag_sigma)).""" a = mu.shape[-1] * np.log(2 * np.pi) b = np.sum(np.log(diag_sigma), axis=-1) y = x - mu / diag_sigma y = np.expand_dims(y, axis=-1) xm = np.expand_dims(x - mu, axis=-2) c = np.matmul(xm, y) c = np.squeeze(np.squeeze(c, axis=-1), axis=-1) return -0.5 * (a + b + c) def multigaussian_loss(preds, targets, ngauss=1): # pylint: disable=invalid-name """Compute mixture of gaussians loss.""" ndims = targets.shape[-1] logits = preds[:, :ngauss] mus = preds[:, ngauss:ngauss*(ndims + 1)] sigmas = preds[:, ngauss(ndims + 1):] sigmas = sigmas * sigmas + 1e-6 # Make positive. loglogits = logits - backend.logsumexp(logits, axis=-1, keepdims=True) mus = np.reshape(mus, [-1, ngauss, ndims]) sigmas = np.reshape(sigmas, [-1, ngauss, ndims]) targets = np.reshape(targets, [-1, 1, ndims]) glogprobs = log_gaussian_diag_pdf(targets, mus, sigmas) return backend.logsumexp(loglogits + glogprobs, axis=-1)
# vim: set fileencoding=utf-8 : import ioc.exceptions, ioc.helper import re, exceptions import importlib, inspect from ioc.proxy import Proxy class Extension(object): def load(self, config, container_builder): pass def post_load(self, container_builder, container): pass def pre_build(self, container_builder, container): pass def post_build(self, container_builder, container): pass def start(self, container): pass class Reference(object): def __init__(self, id): self.id = id class WeakReference(Reference): pass class Definition(object): def __init__(self, clazz=None, arguments=None, kwargs=None): self.clazz = clazz self.arguments = arguments or {} self.kwargs = kwargs or {} self.method_calls = [] self.property_calls = [] self.tags = {} def add_call(self, method, arguments=None, kwargs=None): self.method_calls.append([ method, arguments or [], kwargs or {} ]) def add_tag(self, name, options=None): if name not in self.tags: self.tags[name] = [] self.tags[name].append(options or {}) def has_tag(self, name): return name in self.tags def get_tag(self, name): if not self.has_tag(name): return [] return self.tags[name] class ParameterHolder(object): def __init__(self, parameters=None): self._parameters = parameters or {} self._frozen = False def set(self, key, value): if self._frozen: raise ioc.exceptions.ParameterHolderIsFrozen(key) self._parameters[key] = value def get(self, key): if key in self._parameters: return self._parameters[key] raise ioc.exceptions.UnknownParameter(key) def remove(self, key): del self._parameters[key] def has(self, key): return key in self._parameters def all(self): return self._parameters def freeze(self): self._frozen = True def is_frozen(self): return self._frozen == True class ParameterResolver(object): def __init__(self, logger=None): self.re = re.compile("%%|%([^%\s]+)%") self.logger = logger self.stack = [] def _resolve(self, parameter, parameter_holder): if isinstance(parameter, (tuple)): parameter = list(parameter) for key in ioc.helper.get_keys(parameter): parameter[key] = self.resolve(parameter[key], parameter_holder) return tuple(parameter) if ioc.helper.is_iterable(parameter): for key in ioc.helper.get_keys(parameter): parameter[key] = self.resolve(parameter[key], parameter_holder) return parameter if not type(parameter) == str: return parameter if parameter[0:1] == '%' and parameter[-1] == '%' and parameter_holder.has(parameter[1:-1]): # if self.logger: # self.logger.debug(" >> Match parameter: %s" % parameter[1:-1]) return self.resolve(parameter_holder.get(parameter[1:-1]), parameter_holder) def replace(matchobj): if matchobj.group(0) == '%%': return '%' return self.resolve(parameter_holder.get(matchobj.group(1)), parameter_holder) # if self.logger: # self.logger.debug(" >> Start resolving parameter: %s" % parameter) parameter, nums = re.subn(self.re, replace, parameter) # print parameter return parameter def resolve(self, parameter, parameter_holder): if parameter in self.stack: raise ioc.exceptions.RecursiveParameterResolutionError(" -> ".join(self.stack) + " -> " + parameter) parameter = ioc.helper.deepcopy(parameter) self.stack.append(parameter) value = self._resolve(parameter, parameter_holder) self.stack.pop() return value class Container(object): def __init__(self): self.services = {} self.parameters = ParameterHolder() self.stack = [] def has(self, id): return id in self.services def add(self, id, service): self.services[id] = service def get(self, id): if id not in self.services: raise ioc.exceptions.UnknownService(id) return self.services[id] class ContainerBuilder(Container): def __init__(self, logger=None): self.services = {} self.parameters = ParameterHolder() self.stack = [] self.logger = logger self.parameter_resolver = ioc.component.ParameterResolver(logger=logger) self.extensions = {} def add_extension(self, name, config): self.extensions[name] = config def get_ids_by_tag(self, name): return [id for id, definition in self.services.iteritems() if definition.has_tag(name)] def build_container(self, container): if self.logger: self.logger.debug("Start building the container") extensions = [] container.add("service_container", container) self.parameters.set('ioc.extensions', self.extensions.keys()) for name, config in self.extensions.iteritems(): name = "%s.di.Extension" % name if self.logger: self.logger.debug("Load extension %s" % name) extension = self.get_class(Definition(name))() extension.load(config, self) extensions.append(extension) for extension in extensions: extension.post_load(self, container) for extension in extensions: extension.pre_build(self, container) # resolve services for id, definition in self.services.iteritems(): self.get_service(id, definition, container) for extension in extensions: extension.post_build(self, container) if self.logger: self.logger.debug("Building container is over!") self.logger.debug("Starting resolving all parameters!") for name, value in self.parameters.all().iteritems(): container.parameters.set( name, self.parameter_resolver.resolve(value, self.parameters) ) if self.logger: self.logger.debug("End resolving all parameters!") if container.has('ioc.extra.event_dispatcher'): container.get('ioc.extra.event_dispatcher').dispatch('ioc.container.built', { 'container': container, 'container_builder': self }) def get_class(self, definition): clazz = self.parameter_resolver.resolve(definition.clazz, self.parameters) if isinstance(clazz, list): module = clazz[0] function = clazz[1] else: module = ".".join(clazz.split(".")[0:-1]) function = clazz.split(".")[-1] module = importlib.import_module(module) function = function.split(".") clazz = getattr(module, function[0]) if len(function) == 2: return getattr(clazz, function[1]) return clazz def get_instance(self, definition, container): klass = self.get_class(definition) if self.logger: self.logger.debug("Create instance for %s" % klass) if inspect.isclass(klass) or inspect.isfunction(klass) or inspect.ismethod(klass): args = self.set_services(definition.arguments, container) kwargs = self.set_services(definition.kwargs, container) instance = klass(*args, **kwargs) else: # module object ... instance = klass for call in definition.method_calls: method, args, kwargs = call if self.logger: self.logger.debug(" > Call method: %s on class: %s" % (method, instance)) attr = getattr(instance, method) if not attr: # handle property definition setattr(instance, method, self.set_services(args, container)[0]) else: attr(*self.set_services(args, container), **self.set_services(kwargs, container)) if self.logger: self.logger.debug("End creating instance %s" % instance) return instance def get_service(self, id, definition, container): if self.logger: self.logger.debug("Get service: id=%s, class=%s" % (id, definition.clazz)) if container.has(id): return container.get(id) if id in self.stack: if self.logger: self.logger.error("ioc.exceptions.CyclicReference: " + " -> ".join(self.stack) + " -> " + id) raise ioc.exceptions.CyclicReference(" -> ".join(self.stack) + " -> " + id) self.stack.append(id) instance = self.get_instance(definition, container) container.add(id, instance) self.stack.pop() return instance def set_service(self, value, container): if isinstance(value, (Reference, WeakReference)) and container.has(value.id): return container.get(value.id) if isinstance(value, (Reference, WeakReference)) and not self.has(value.id): raise ioc.exceptions.UnknownService(value.id) if isinstance(value, WeakReference) and not container.has(value.id): return Proxy(container, value.id) if isinstance(value, Reference) and not container.has(value.id): return self.get_service(value.id, self.get(value.id), container) if isinstance(value, Reference) and container.has(value.id): return container.get(value.id) if isinstance(value, Definition): return self.get_instance(value, container) if ioc.helper.is_iterable(value): return self.set_services(value, container) if isinstance(value, (tuple)): return tuple(self.set_services(list(value), container)) return self.parameter_resolver.resolve(value, self.parameters) def set_services(self, arguments, container): for pos in ioc.helper.get_keys(arguments): arguments[pos] = self.set_service(arguments[pos], container) return arguments fix method signature # vim: set fileencoding=utf-8 : import ioc.exceptions, ioc.helper from ioc.proxy import Proxy import importlib, inspect, re class Extension(object): def load(self, config, container_builder): pass def post_load(self, container_builder): pass def pre_build(self, container_builder, container): pass def post_build(self, container_builder, container): pass def start(self, container): pass class Reference(object): def __init__(self, id): self.id = id class WeakReference(Reference): pass class Definition(object): def __init__(self, clazz=None, arguments=None, kwargs=None): self.clazz = clazz self.arguments = arguments or {} self.kwargs = kwargs or {} self.method_calls = [] self.property_calls = [] self.tags = {} def add_call(self, method, arguments=None, kwargs=None): self.method_calls.append([ method, arguments or [], kwargs or {} ]) def add_tag(self, name, options=None): if name not in self.tags: self.tags[name] = [] self.tags[name].append(options or {}) def has_tag(self, name): return name in self.tags def get_tag(self, name): if not self.has_tag(name): return [] return self.tags[name] class ParameterHolder(object): def __init__(self, parameters=None): self._parameters = parameters or {} self._frozen = False def set(self, key, value): if self._frozen: raise ioc.exceptions.ParameterHolderIsFrozen(key) self._parameters[key] = value def get(self, key): if key in self._parameters: return self._parameters[key] raise ioc.exceptions.UnknownParameter(key) def remove(self, key): del self._parameters[key] def has(self, key): return key in self._parameters def all(self): return self._parameters def freeze(self): self._frozen = True def is_frozen(self): return self._frozen == True class ParameterResolver(object): def __init__(self, logger=None): self.re = re.compile("%%|%([^%\s]+)%") self.logger = logger self.stack = [] def _resolve(self, parameter, parameter_holder): if isinstance(parameter, (tuple)): parameter = list(parameter) for key in ioc.helper.get_keys(parameter): parameter[key] = self.resolve(parameter[key], parameter_holder) return tuple(parameter) if ioc.helper.is_iterable(parameter): for key in ioc.helper.get_keys(parameter): parameter[key] = self.resolve(parameter[key], parameter_holder) return parameter if not type(parameter) == str: return parameter if parameter[0:1] == '%' and parameter[-1] == '%' and parameter_holder.has(parameter[1:-1]): # if self.logger: # self.logger.debug(" >> Match parameter: %s" % parameter[1:-1]) return self.resolve(parameter_holder.get(parameter[1:-1]), parameter_holder) def replace(matchobj): if matchobj.group(0) == '%%': return '%' return self.resolve(parameter_holder.get(matchobj.group(1)), parameter_holder) # if self.logger: # self.logger.debug(" >> Start resolving parameter: %s" % parameter) parameter, nums = re.subn(self.re, replace, parameter) # print parameter return parameter def resolve(self, parameter, parameter_holder): if parameter in self.stack: raise ioc.exceptions.RecursiveParameterResolutionError(" -> ".join(self.stack) + " -> " + parameter) parameter = ioc.helper.deepcopy(parameter) self.stack.append(parameter) value = self._resolve(parameter, parameter_holder) self.stack.pop() return value class Container(object): def __init__(self): self.services = {} self.parameters = ParameterHolder() self.stack = [] def has(self, id): return id in self.services def add(self, id, service): self.services[id] = service def get(self, id): if id not in self.services: raise ioc.exceptions.UnknownService(id) return self.services[id] class ContainerBuilder(Container): def __init__(self, logger=None): self.services = {} self.parameters = ParameterHolder() self.stack = [] self.logger = logger self.parameter_resolver = ioc.component.ParameterResolver(logger=logger) self.extensions = {} def add_extension(self, name, config): self.extensions[name] = config def get_ids_by_tag(self, name): return [id for id, definition in self.services.iteritems() if definition.has_tag(name)] def build_container(self, container): if self.logger: self.logger.debug("Start building the container") extensions = [] container.add("service_container", container) self.parameters.set('ioc.extensions', self.extensions.keys()) for name, config in self.extensions.iteritems(): name = "%s.di.Extension" % name if self.logger: self.logger.debug("Load extension %s" % name) extension = self.get_class(Definition(name))() extension.load(config, self) extensions.append(extension) for extension in extensions: extension.post_load(self) for extension in extensions: extension.pre_build(self, container) # resolve services for id, definition in self.services.iteritems(): self.get_service(id, definition, container) for extension in extensions: extension.post_build(self, container) if self.logger: self.logger.debug("Building container is over!") self.logger.debug("Starting resolving all parameters!") for name, value in self.parameters.all().iteritems(): container.parameters.set( name, self.parameter_resolver.resolve(value, self.parameters) ) if self.logger: self.logger.debug("End resolving all parameters!") if container.has('ioc.extra.event_dispatcher'): container.get('ioc.extra.event_dispatcher').dispatch('ioc.container.built', { 'container': container, 'container_builder': self }) def get_class(self, definition): clazz = self.parameter_resolver.resolve(definition.clazz, self.parameters) if isinstance(clazz, list): module = clazz[0] function = clazz[1] else: module = ".".join(clazz.split(".")[0:-1]) function = clazz.split(".")[-1] module = importlib.import_module(module) function = function.split(".") clazz = getattr(module, function[0]) if len(function) == 2: return getattr(clazz, function[1]) return clazz def get_instance(self, definition, container): klass = self.get_class(definition) if self.logger: self.logger.debug("Create instance for %s" % klass) if inspect.isclass(klass) or inspect.isfunction(klass) or inspect.ismethod(klass): args = self.set_services(definition.arguments, container) kwargs = self.set_services(definition.kwargs, container) instance = klass(*args, **kwargs) else: # module object ... instance = klass for call in definition.method_calls: method, args, kwargs = call if self.logger: self.logger.debug(" > Call method: %s on class: %s" % (method, instance)) attr = getattr(instance, method) if not attr: # handle property definition setattr(instance, method, self.set_services(args, container)[0]) else: attr(*self.set_services(args, container), **self.set_services(kwargs, container)) if self.logger: self.logger.debug("End creating instance %s" % instance) return instance def get_service(self, id, definition, container): if self.logger: self.logger.debug("Get service: id=%s, class=%s" % (id, definition.clazz)) if container.has(id): return container.get(id) if id in self.stack: if self.logger: self.logger.error("ioc.exceptions.CyclicReference: " + " -> ".join(self.stack) + " -> " + id) raise ioc.exceptions.CyclicReference(" -> ".join(self.stack) + " -> " + id) self.stack.append(id) instance = self.get_instance(definition, container) container.add(id, instance) self.stack.pop() return instance def set_service(self, value, container): if isinstance(value, (Reference, WeakReference)) and container.has(value.id): return container.get(value.id) if isinstance(value, (Reference, WeakReference)) and not self.has(value.id): raise ioc.exceptions.UnknownService(value.id) if isinstance(value, WeakReference) and not container.has(value.id): return Proxy(container, value.id) if isinstance(value, Reference) and not container.has(value.id): return self.get_service(value.id, self.get(value.id), container) if isinstance(value, Reference) and container.has(value.id): return container.get(value.id) if isinstance(value, Definition): return self.get_instance(value, container) if ioc.helper.is_iterable(value): return self.set_services(value, container) if isinstance(value, (tuple)): return tuple(self.set_services(list(value), container)) return self.parameter_resolver.resolve(value, self.parameters) def set_services(self, arguments, container): for pos in ioc.helper.get_keys(arguments): arguments[pos] = self.set_service(arguments[pos], container) return arguments
import tensorflow as tf import numpy as np from data_sets.data_sets import DataSets def ranked(x): # x will be a numpy array with the contents of the placeholder below return np.argsort(x, axis=0) def main(): steps = 20 data_set = DataSets.get_followers() data_set -= 1 n_raw = data_set.max(axis=0).max() + 1 beta = tf.constant(0.85, tf.float32) n = tf.constant(n_raw, tf.float32) a = tf.Variable(tf.transpose( tf.scatter_nd(data_set.values.tolist(), data_set.shape[0] * [1.0], [n_raw, n_raw])), tf.float64) v = tf.Variable(tf.fill([n_raw, 1], tf.pow(n, -1))) o_degree = tf.reduce_sum(a, 0) condition = tf.not_equal(o_degree, 0) transition = tf.transpose( tf.where(condition, tf.transpose(beta * tf.div(a, o_degree) + (1 - beta) / n), tf.fill([n_raw, n_raw], tf.pow(n, -1)))) page_rank = tf.matmul(transition, v, a_is_sparse=True) run_iteration = tf.assign(v, page_rank) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for step in range(steps): sess.run(run_iteration) print(sess.run(v)) print(sess.run(tf.transpose(tf.py_func(ranked, [-v], tf.int64))[0])) tf.summary.FileWriter('logs/.', sess.graph) pass if __name__ == '__main__': main() Working on pagerank improvements import tensorflow as tf import numpy as np from data_sets.data_sets import DataSets def ranked(x): # x will be a numpy array with the contents of the placeholder below return np.argsort(x, axis=0) def main(): steps = 20 data_set = DataSets.get_wiki_vote() data_set -= 1 n_raw = data_set.max(axis=0).max() + 1 beta = tf.constant(0.85, tf.float32, name="Beta") n = tf.constant(n_raw, tf.float32, name="NodeCounts") a = tf.Variable(tf.transpose( tf.scatter_nd(data_set.values.tolist(), data_set.shape[0] * [1.0], [n_raw, n_raw])), tf.float64, name="AdjacencyMatrix") v = tf.Variable(tf.fill([n_raw, 1], tf.pow(n, -1)), name="PageRankVector") o_degree = tf.reduce_sum(a, 0) condition = tf.not_equal(o_degree, 0) transition = tf.transpose( tf.where(condition, tf.transpose(beta * tf.div(a, o_degree) + (1 - beta) / n), tf.fill([n_raw, n_raw], tf.pow(n, -1)))) page_rank = tf.matmul(transition, v, a_is_sparse=True) run_iteration = tf.assign(v, page_rank) ranks = tf.transpose(tf.py_func(ranked, [-v], tf.int64))[0] init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for step in range(steps): sess.run(run_iteration) print(sess.run(v)) print(sess.run(ranks)) np.savetxt('logs/test.csv', sess.run(ranks), fmt='%i') tf.summary.FileWriter('logs/.', sess.graph) pass if __name__ == '__main__': main()
improvement(k8s-local): cache cert manager images
class Roman(object): def __init__(self, number): self.number = number self.modern_convert() convert_table = {} def modern_convert(self): number = self.number solution = [] while True: if number >= 1000: solution.append("M") number -= 1000 elif number >= 500: solution.append("D") number -= 500 elif number >= 100: solution.append("C") number -= 100 elif number >=50: solution.append("L") number -= 50 elif number >= 10: solution.append("X") number -= 10 elif number >= 5: solution.append("V") number -= 5 elif number >= 1: soution.append("I") number -= 1 else: break print "".join(solution) return number = Roman(15) Add loops in __init__ for continuous convert class Roman(object): def __init__(self, number): self.number = int(number) choice = raw_input("Type Y or N for modern Roman Numeral Convert: ").lower() while True: if choice == "y": print "You made it" elif choice == "n": self.old_roman_convert() break else: print "Please Type Y or N!" (self, self.number) play_again = raw_input("Do you want to enter another number? Please type yes or no: ").lower() if play_again == "no": print "Thanks for Playing!" else: Roman(raw_input("Enter another number! ")) def old_roman_convert(self): number = self.number solution = [] while True: if number >= 1000: solution.append("M") number -= 1000 elif number >= 500: solution.append("D") number -= 500 elif number >= 100: solution.append("C") number -= 100 elif number >=50: solution.append("L") number -= 50 elif number >= 10: solution.append("X") number -= 10 elif number >= 5: solution.append("V") number -= 5 elif number >= 1: soution.append("I") number -= 1 else: break print "".join(solution) return number = Roman(raw_input("Enter a number to be converted into Roman Numberal Form: "))
from django.utils.translation import ugettext_lazy from django.core.exceptions import ImproperlyConfigured from annoying.functions import get_config fdow_default = 0 # Sunday # Look for FIRST_DAY_OF_WEEK as a locale setting fdow = ugettext_lazy('FIRST_DAY_OF_WEEK') try: FIRST_DAY_OF_WEEK = int(fdow) except ValueError: # Let's try our settings fdow = get_config('FIRST_DAY_OF_WEEK', fdow_default) FIRST_DAY_OF_WEEK = int(fdow) except ValueError: raise ImproperlyConfigured("FIRST_DAY_OF_WEEK must be an integer between 0 and 6") AUTH_USER_MODEL = get_config('AUTH_USER_MODEL') # whether to display cancelled occurrences # (if they are displayed then they have a css class "cancelled") # this controls behaviour of Period.classify_occurrence method SHOW_CANCELLED_OCCURRENCES = get_config('SHOW_CANCELLED_OCCURRENCES', False) # Callable used to check if a user has edit permissions to event # (and occurrence). Used by check_edit_permission decorator # if ob==None we check permission to add occurrence CHECK_EVENT_PERM_FUNC = get_config('CHECK_EVENT_PERM_FUNC', None) if not CHECK_EVENT_PERM_FUNC: CHECK_EVENT_PERM_FUNC = get_config('CHECK_PERMISSION_FUNC', None) if not CHECK_EVENT_PERM_FUNC: def check_event_permission(ob, user): return user.is_authenticated() CHECK_EVENT_PERM_FUNC = check_event_permission # Callable used to check if a user has edit permissions to calendar CHECK_CALENDAR_PERM_FUNC = get_config('CHECK_CALENDAR_PERM_FUNC', None) if not CHECK_CALENDAR_PERM_FUNC: def check_calendar_permission(ob, user): return user.is_authenticated() CHECK_CALENDAR_PERM_FUNC = check_calendar_permission # Callable used to customize the event list given for a calendar and user # (e.g. all events on that calendar, those events plus another calendar's events, # or the events filtered based on user permissions) # Imports have to be placed within the function body to avoid circular imports GET_EVENTS_FUNC = get_config('GET_EVENTS_FUNC', None) if not GET_EVENTS_FUNC: def get_events(request, calendar): return calendar.event_set.all() GET_EVENTS_FUNC = get_events # URL to redirect to to after an occurrence is canceled OCCURRENCE_CANCEL_REDIRECT = get_config('OCCURRENCE_CANCEL_REDIRECT', None) Further fix for Django 1.7 Force the __proxy__ to be a concrete string from django.utils.translation import ugettext_lazy from django.core.exceptions import ImproperlyConfigured from annoying.functions import get_config fdow_default = 0 # Sunday # Look for FIRST_DAY_OF_WEEK as a locale setting fdow = ugettext_lazy('FIRST_DAY_OF_WEEK') try: FIRST_DAY_OF_WEEK = int(str(fdow)) except ValueError: # Let's try our settings fdow = get_config('FIRST_DAY_OF_WEEK', fdow_default) FIRST_DAY_OF_WEEK = int(fdow) except ValueError: raise ImproperlyConfigured("FIRST_DAY_OF_WEEK must be an integer between 0 and 6") AUTH_USER_MODEL = get_config('AUTH_USER_MODEL') # whether to display cancelled occurrences # (if they are displayed then they have a css class "cancelled") # this controls behaviour of Period.classify_occurrence method SHOW_CANCELLED_OCCURRENCES = get_config('SHOW_CANCELLED_OCCURRENCES', False) # Callable used to check if a user has edit permissions to event # (and occurrence). Used by check_edit_permission decorator # if ob==None we check permission to add occurrence CHECK_EVENT_PERM_FUNC = get_config('CHECK_EVENT_PERM_FUNC', None) if not CHECK_EVENT_PERM_FUNC: CHECK_EVENT_PERM_FUNC = get_config('CHECK_PERMISSION_FUNC', None) if not CHECK_EVENT_PERM_FUNC: def check_event_permission(ob, user): return user.is_authenticated() CHECK_EVENT_PERM_FUNC = check_event_permission # Callable used to check if a user has edit permissions to calendar CHECK_CALENDAR_PERM_FUNC = get_config('CHECK_CALENDAR_PERM_FUNC', None) if not CHECK_CALENDAR_PERM_FUNC: def check_calendar_permission(ob, user): return user.is_authenticated() CHECK_CALENDAR_PERM_FUNC = check_calendar_permission # Callable used to customize the event list given for a calendar and user # (e.g. all events on that calendar, those events plus another calendar's events, # or the events filtered based on user permissions) # Imports have to be placed within the function body to avoid circular imports GET_EVENTS_FUNC = get_config('GET_EVENTS_FUNC', None) if not GET_EVENTS_FUNC: def get_events(request, calendar): return calendar.event_set.all() GET_EVENTS_FUNC = get_events # URL to redirect to to after an occurrence is canceled OCCURRENCE_CANCEL_REDIRECT = get_config('OCCURRENCE_CANCEL_REDIRECT', None)
Update linkscraper.py
__version__ = '0.1.2' from os import environ from flask import Flask from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView from flask.ext.login import LoginManager, current_user from flask.ext.migrate import Migrate from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() login_manager = LoginManager() class AuthedModelView(ModelView): def is_accessible(self): return current_user.is_authenticated() def create_app(config=None): """ This needs some tidying up. To avoid circular imports we import everything here but it makes this method a bit more gross. """ # Initialise the app from home.config import TEMPLATE_FOLDER, STATIC_FOLDER app = Flask(__name__, static_folder=STATIC_FOLDER, template_folder=TEMPLATE_FOLDER) app.config['SECRET_KEY'] = 'ssh, its a secret.' # Load the default config, the specified config file and then any # overwrites that are manually passed in. app.config.from_object('home.config') if 'HOME_SETTINGS' in environ: app.config.from_envvar('HOME_SETTINGS') app.config.from_object(config) # Register the web front end and the API. from home.dash.web import web from home.dash.api import api app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') login_manager.init_app(app) login_manager.login_view = 'Dashboard Web.login' @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # Initialise the migrations app, we want to store all migrations within # the project directory for easier packaging. Migrate(app, db, directory=app.config['MIGRATE_DIRECTORY']) # Wire up the models to flask admin from home.ts.models import Graph, Series, Device, DeviceSeries, Area from home.dash.models import User admin = Admin(app) admin.add_view(AuthedModelView(Area, db.session)) admin.add_view(AuthedModelView(Device, db.session)) admin.add_view(AuthedModelView(Series, db.session)) admin.add_view(AuthedModelView(DeviceSeries, db.session)) admin.add_view(AuthedModelView(Graph, db.session)) admin.add_view(AuthedModelView(User, db.session)) # Wire up the database to the app so it gets the config. db.init_app(app) return app Tag 0.1.3 __version__ = '0.1.3' from os import environ from flask import Flask from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView from flask.ext.login import LoginManager, current_user from flask.ext.migrate import Migrate from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() login_manager = LoginManager() class AuthedModelView(ModelView): def is_accessible(self): return current_user.is_authenticated() def create_app(config=None): """ This needs some tidying up. To avoid circular imports we import everything here but it makes this method a bit more gross. """ # Initialise the app from home.config import TEMPLATE_FOLDER, STATIC_FOLDER app = Flask(__name__, static_folder=STATIC_FOLDER, template_folder=TEMPLATE_FOLDER) app.config['SECRET_KEY'] = 'ssh, its a secret.' # Load the default config, the specified config file and then any # overwrites that are manually passed in. app.config.from_object('home.config') if 'HOME_SETTINGS' in environ: app.config.from_envvar('HOME_SETTINGS') app.config.from_object(config) # Register the web front end and the API. from home.dash.web import web from home.dash.api import api app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') login_manager.init_app(app) login_manager.login_view = 'Dashboard Web.login' @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # Initialise the migrations app, we want to store all migrations within # the project directory for easier packaging. Migrate(app, db, directory=app.config['MIGRATE_DIRECTORY']) # Wire up the models to flask admin from home.ts.models import Graph, Series, Device, DeviceSeries, Area from home.dash.models import User admin = Admin(app) admin.add_view(AuthedModelView(Area, db.session)) admin.add_view(AuthedModelView(Device, db.session)) admin.add_view(AuthedModelView(Series, db.session)) admin.add_view(AuthedModelView(DeviceSeries, db.session)) admin.add_view(AuthedModelView(Graph, db.session)) admin.add_view(AuthedModelView(User, db.session)) # Wire up the database to the app so it gets the config. db.init_app(app) return app
#! /usr/bin/python # -*- coding: utf-8 -*- # © 2010-2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Name lookup in Odoo for incoming and outgoing calls with an Asterisk IPBX This script is designed to be used as an AGI on an Asterisk IPBX... BUT I advise you to use a wrapper around this script to control the execution time. Why ? Because if the script takes too much time to execute or get stucks (in the XML-RPC request for example), then the incoming phone call will also get stucks and you will miss a call ! The simplest solution I found is to use the "timeout" shell command to call this script, for example : # timeout 2s get_name_agi.py <OPTIONS> See my 2 sample wrappers "set_name_incoming_timeout.sh" and "set_name_outgoing_timeout.sh" It's probably a good idea to create a user in Odoo dedicated to this task. This user only needs to be part of the group "Phone CallerID", which has read access on the 'res.partner' and other objects with phone numbers and names. Note that this script can be used without Odoo, with just the geolocalisation feature : for that, don't use option --server ; only use --geoloc This script can be used both on incoming and outgoing calls : 1) INCOMING CALLS When executed from the dialplan on an incoming phone call, it will lookup in Odoo's partners and other objects with phone numbers (leads, employees, etc...), and, if it finds the phone number, it will get the corresponding name of the person and use this name as CallerID name for the incoming call. Requires the "base_phone" module available from https://github.com/OCA/connector-telephony Asterisk dialplan example : [from-extern] exten = _0141981242,1,AGI(/usr/local/bin/set_name_incoming_timeout.sh) same = n,Dial(SIP/10, 30) same = n,Answer same = n,Voicemail(10@default,u) same = n,Hangup 2) OUTGOING CALLS When executed from the dialplan on an outgoing call, it will lookup in Odoo the name corresponding to the phone number that is called by the user and it will update the name of the callee on the screen of the phone of the caller. For that, it uses the CONNECTEDLINE dialplan function of Asterisk See the following page for more info: https://wiki.asterisk.org/wiki/display/AST/Manipulating+Party+ID+Information It is not possible to set the CONNECTEDLINE directly from an AGI script, (at least not with Asterisk 11) so the AGI script sets a variable "connectedlinename" that can then be read from the dialplan and passed as parameter to the CONNECTEDLINE function. Here is the code that I used on the pre-process subroutine "odoo-out-call" of the Outgoing Call of my Xivo server : [odoo-out-call] exten = s,1,AGI(/var/lib/asterisk/agi-bin/set_name_outgoing_timeout.sh) same = n,Set(CONNECTEDLINE(name,i)=${connectedlinename}) same = n,Set(CONNECTEDLINE(name-pres,i)=allowed) same = n,Set(CONNECTEDLINE(num,i)=${XIVO_DSTNUM}) same = n,Set(CONNECTEDLINE(num-pres)=allowed) same = n,Return() Of course, you should adapt this example to the Asterisk server you are using. """ import xmlrpclib import sys from optparse import OptionParser __author__ = "Alexis de Lattre <alexis.delattre@akretion.com>" __date__ = "June 2015" __version__ = "0.6" # Name that will be displayed if there is no match # and no geolocalisation. Set it to False if you don't want # to have a 'not_found_name' when nothing is found not_found_name = False # Define command line options options = [ {'names': ('-s', '--server'), 'dest': 'server', 'type': 'string', 'action': 'store', 'default': False, 'help': 'DNS or IP address of the Odoo server. Default = none ' '(will not try to connect to Odoo)'}, {'names': ('-p', '--port'), 'dest': 'port', 'type': 'int', 'action': 'store', 'default': 8069, 'help': "Port of Odoo's XML-RPC interface. Default = 8069"}, {'names': ('-e', '--ssl'), 'dest': 'ssl', 'help': "Use SSL connections instead of clear connections. " "Default = no, use clear XML-RPC or JSON-RPC", 'action': 'store_true', 'default': False}, {'names': ('-j', '--jsonrpc'), 'dest': 'jsonrpc', 'help': "Use JSON-RPC instead of the default protocol XML-RPC. " "Default = no, use XML-RPC", 'action': 'store_true', 'default': False}, {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string', 'action': 'store', 'default': 'odoo', 'help': "Odoo database name. Default = 'odoo'"}, {'names': ('-u', '--user-id'), 'dest': 'userid', 'type': 'int', 'action': 'store', 'default': 2, 'help': "Odoo user ID to use when connecting to Odoo in " "XML-RPC. Default = 2"}, {'names': ('-t', '--username'), 'dest': 'username', 'type': 'string', 'action': 'store', 'default': 'demo', 'help': "Odoo username to use when connecting to Odoo in " "JSON-RPC. Default = demo"}, {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string', 'action': 'store', 'default': 'demo', 'help': "Password of the Odoo user. Default = 'demo'"}, {'names': ('-a', '--ascii'), 'dest': 'ascii', 'action': 'store_true', 'default': False, 'help': "Convert name from UTF-8 to ASCII. Default = no, keep UTF-8"}, {'names': ('-n', '--notify'), 'dest': 'notify', 'action': 'store_true', 'default': False, 'help': "Notify Odoo users via a pop-up (requires the Odoo " "module 'base_phone_popup'). If you use this option, you must pass " "the logins of the Odoo users to notify as argument to the " "script. Default = no"}, {'names': ('-g', '--geoloc'), 'dest': 'geoloc', 'action': 'store_true', 'default': False, 'help': "Try to geolocate phone numbers unknown to Odoo. This " "features requires the 'phonenumbers' Python lib. To install it, " "run 'sudo pip install phonenumbers' Default = no"}, {'names': ('-l', '--geoloc-lang'), 'dest': 'lang', 'type': 'string', 'action': 'store', 'default': "en", 'help': "Language in which the name of the country and city name " "will be displayed by the geolocalisation database. Use the 2 " "letters ISO code of the language. Default = 'en'"}, {'names': ('-c', '--geoloc-country'), 'dest': 'country', 'type': 'string', 'action': 'store', 'default': "FR", 'help': "2 letters ISO code for your country e.g. 'FR' for France. " "This will be used by the geolocalisation system to parse the phone " "number of the calling party. Default = 'FR'"}, {'names': ('-o', '--outgoing'), 'dest': 'outgoing', 'action': 'store_true', 'default': False, 'help': "Update the Connected Line ID name on outgoing calls via a " "call to the Asterisk function CONNECTEDLINE(), instead of updating " "the Caller ID name on incoming calls. Default = no."}, {'names': ('-i', '--outgoing-agi-variable'), 'dest': 'outgoing_agi_var', 'type': 'string', 'action': 'store', 'default': "extension", 'help': "Enter the name of the AGI variable (without the 'agi_' " "prefix) from which the script will get the phone number dialed by " "the user on outgoing calls. For example, with Xivo, you should " "specify 'dnid' as the AGI variable. Default = 'extension'"}, {'names': ('-m', '--max-size'), 'dest': 'max_size', 'type': 'int', 'action': 'store', 'default': 40, 'help': "If the name has more characters this maximum size, cut it " "to this maximum size. Default = 40"}, ] def stdout_write(string): '''Wrapper on sys.stdout.write''' sys.stdout.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace')) sys.stdout.flush() # When we output a command, we get an answer "200 result=1" on stdin # Purge stdin to avoid these Asterisk error messages : # utils.c ast_carefulwrite: write() returned error: Broken pipe sys.stdin.readline() return True def stderr_write(string): '''Wrapper on sys.stderr.write''' sys.stderr.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace')) sys.stdout.flush() return True def geolocate_phone_number(number, my_country_code, lang): import phonenumbers import phonenumbers.geocoder res = '' phonenum = phonenumbers.parse(number, my_country_code.upper()) city = phonenumbers.geocoder.description_for_number(phonenum, lang.lower()) country_code = phonenumbers.region_code_for_number(phonenum) # We don't display the country name when it's my own country if country_code == my_country_code.upper(): if city: res = city else: # Convert country code to country name country = phonenumbers.geocoder._region_display_name( country_code, lang.lower()) if country and city: res = country + ' ' + city elif country and not city: res = country return res def convert_to_ascii(my_unicode): '''Convert to ascii, with clever management of accents (é -> e, è -> e)''' import unicodedata if isinstance(my_unicode, unicode): my_unicode_with_ascii_chars_only = ''.join(( char for char in unicodedata.normalize('NFD', my_unicode) if unicodedata.category(char) != 'Mn')) return str(my_unicode_with_ascii_chars_only) # If the argument is already of string type, return it with the same value elif isinstance(my_unicode, str): return my_unicode else: return False def main(options, arguments): # print 'options = %s' % options # print 'arguments = %s' % arguments # AGI passes parameters to the script on standard input stdinput = {} while 1: input_line = sys.stdin.readline() if not input_line: break line = input_line.strip() try: variable, value = line.split(':') except: break if variable[:4] != 'agi_': # All AGI parameters start with 'agi_' stderr_write("bad stdin variable : %s\n" % variable) continue variable = variable.strip() value = value.strip() if variable and value: stdinput[variable] = value stderr_write("full AGI environnement :\n") for variable in stdinput.keys(): stderr_write("%s = %s\n" % (variable, stdinput.get(variable))) if options.outgoing: phone_number = stdinput.get('agi_%s' % options.outgoing_agi_var) stdout_write('VERBOSE "Dialed phone number is %s"\n' % phone_number) else: # If we already have a "True" caller ID name # i.e. not just digits, but a real name, then we don't try to # connect to Odoo or geoloc, we just keep it if ( stdinput.get('agi_calleridname') and not stdinput.get('agi_calleridname').isdigit() and stdinput.get('agi_calleridname').lower() not in ['asterisk', 'unknown', 'anonymous'] and not options.notify): stdout_write( 'VERBOSE "Incoming CallerID name is %s"\n' % stdinput.get('agi_calleridname')) stdout_write( 'VERBOSE "As it is a real name, we do not change it"\n') return True phone_number = stdinput.get('agi_callerid') stderr_write('stdout encoding = %s\n' % sys.stdout.encoding or 'utf-8') if not isinstance(phone_number, str): stdout_write('VERBOSE "Phone number is empty"\n') exit(0) # Match for particular cases and anonymous phone calls # To test anonymous call in France, dial 3651 + number if not phone_number.isdigit(): stdout_write( 'VERBOSE "Phone number (%s) is not a digit"\n' % phone_number) exit(0) stdout_write('VERBOSE "Phone number = %s"\n' % phone_number) if options.notify and not arguments: stdout_write( 'VERBOSE "When using the notify option, you must give arguments ' 'to the script"\n') exit(0) if options.notify: method = 'incall_notify_by_login' else: method = 'get_name_from_phone_number' res = False # Yes, this script can be used without "-s odoo_server" ! if options.server and options.jsonrpc: import odoorpc proto = options.ssl and 'jsonrpc+ssl' or 'jsonrpc' stdout_write( 'VERBOSE "Starting %s request on Odoo %s:%d database ' '%s username %s"\n' % ( proto.upper(), options.server, options.port, options.database, options.username)) try: odoo = odoorpc.ODOO(options.server, proto, options.port) odoo.login(options.database, options.username, options.password) if options.notify: res = odoo.execute( 'phone.common', method, phone_number, arguments) else: res = odoo.execute('phone.common', method, phone_number) stdout_write('VERBOSE "Called method %s"\n' % method) except: stdout_write( 'VERBOSE "Could not connect to Odoo in JSON-RPC"\n') elif options.server: proto = options.ssl and 'https' or 'http' stdout_write( 'VERBOSE "Starting %s XML-RPC request on Odoo %s:%d ' 'database %s user ID %d"\n' % ( proto, options.server, options.port, options.database, options.userid)) sock = xmlrpclib.ServerProxy( '%s://%s:%d/xmlrpc/object' % (proto, options.server, options.port)) try: if options.notify: res = sock.execute( options.database, options.userid, options.password, 'phone.common', method, phone_number, arguments) else: res = sock.execute( options.database, options.userid, options.password, 'phone.common', method, phone_number) stdout_write('VERBOSE "Called method %s"\n' % method) except: stdout_write('VERBOSE "Could not connect to Odoo in XML-RPC"\n') # To simulate a long execution of the XML-RPC request # import time # time.sleep(5) # Function to limit the size of the name if res: if len(res) > options.max_size: res = res[0:options.max_size] elif options.geoloc: # if the number is not found in Odoo, we try to geolocate stdout_write( 'VERBOSE "Trying to geolocate with country %s and lang %s"\n' % (options.country, options.lang)) res = geolocate_phone_number( phone_number, options.country, options.lang) else: # if the number is not found in Odoo and geoloc is off, # we put 'not_found_name' as Name stdout_write('VERBOSE "Phone number not found in Odoo"\n') res = not_found_name # All SIP phones should support UTF-8... # but in case you have analog phones over TDM # or buggy phones, you should use the command line option --ascii if options.ascii: res = convert_to_ascii(res) stdout_write('VERBOSE "Name = %s"\n' % res) if res: if options.outgoing: stdout_write('SET VARIABLE connectedlinename "%s"\n' % res) else: stdout_write('SET CALLERID "%s"<%s>\n' % (res, phone_number)) return True if __name__ == '__main__': usage = "Usage: get_name_agi.py [options] login1 login2 login3 ..." epilog = "Script written by Alexis de Lattre. " "Published under the GNU AGPL licence." description = "This is an AGI script that sends a query to Odoo. " "It can also be used without Odoo to geolocate phone numbers " "of incoming calls." parser = OptionParser(usage=usage, epilog=epilog, description=description) for option in options: param = option['names'] del option['names'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments) Improve AGI script using a dedicated lib #! /usr/bin/python # -*- coding: utf-8 -*- # © 2010-2018 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Name lookup in Odoo for incoming and outgoing calls with an Asterisk IPBX This script is designed to be used as an AGI on an Asterisk IPBX... BUT I advise you to use a wrapper around this script to control the execution time. Why ? Because if the script takes too much time to execute or get stucks (in the XML-RPC request for example), then the incoming phone call will also get stucks and you will miss a call ! The simplest solution I found is to use the "timeout" shell command to call this script, for example : # timeout 2s get_name_agi.py <OPTIONS> See my 2 sample wrappers "set_name_incoming_timeout.sh" and "set_name_outgoing_timeout.sh" It's probably a good idea to create a user in Odoo dedicated to this task. This user only needs to be part of the group "Phone CallerID", which has read access on the 'res.partner' and other objects with phone numbers and names. Note that this script can be used without Odoo, with just the geolocalisation feature : for that, don't use option --server ; only use --geoloc This script can be used both on incoming and outgoing calls : 1) INCOMING CALLS When executed from the dialplan on an incoming phone call, it will lookup in Odoo's partners and other objects with phone numbers (leads, employees, etc...), and, if it finds the phone number, it will get the corresponding name of the person and use this name as CallerID name for the incoming call. Requires the "base_phone" module available from https://github.com/OCA/connector-telephony Asterisk dialplan example : [from-extern] exten = _0141981242,1,AGI(/usr/local/bin/set_name_incoming_timeout.sh) same = n,Dial(SIP/10, 30) same = n,Answer same = n,Voicemail(10@default,u) same = n,Hangup 2) OUTGOING CALLS When executed from the dialplan on an outgoing call, it will lookup in Odoo the name corresponding to the phone number that is called by the user and it will update the name of the callee on the screen of the phone of the caller. For that, it uses the CONNECTEDLINE dialplan function of Asterisk See the following page for more info: https://wiki.asterisk.org/wiki/display/AST/Manipulating+Party+ID+Information It is not possible to set the CONNECTEDLINE directly from an AGI script, (at least not with Asterisk 11) so the AGI script sets a variable "connectedlinename" that can then be read from the dialplan and passed as parameter to the CONNECTEDLINE function. Here is the code that I used on the pre-process subroutine "odoo-out-call" of the Outgoing Call of my Xivo server : [odoo-out-call] exten = s,1,AGI(/var/lib/asterisk/agi-bin/set_name_outgoing_timeout.sh) same = n,Set(CONNECTEDLINE(name,i)=${connectedlinename}) same = n,Set(CONNECTEDLINE(name-pres,i)=allowed) same = n,Set(CONNECTEDLINE(num,i)=${XIVO_DSTNUM}) same = n,Set(CONNECTEDLINE(num-pres)=allowed) same = n,Return() Of course, you should adapt this example to the Asterisk server you are using. """ import xmlrpclib import sys from optparse import OptionParser from asterisk import agi as agilib # pip install pyst2 __author__ = "Alexis de Lattre <alexis.delattre@akretion.com>" __date__ = "February 2018" __version__ = "0.6" # Name that will be displayed if there is no match # and no geolocalisation. Set it to False if you don't want # to have a 'not_found_name' when nothing is found not_found_name = False # Define command line options options = [ {'names': ('-s', '--server'), 'dest': 'server', 'type': 'string', 'action': 'store', 'default': False, 'help': 'DNS or IP address of the Odoo server. Default = none ' '(will not try to connect to Odoo)'}, {'names': ('-p', '--port'), 'dest': 'port', 'type': 'int', 'action': 'store', 'default': 8069, 'help': "Port of Odoo's XML-RPC interface. Default = 8069"}, {'names': ('-e', '--ssl'), 'dest': 'ssl', 'help': "Use SSL connections instead of clear connections. " "Default = no, use clear XML-RPC or JSON-RPC", 'action': 'store_true', 'default': False}, {'names': ('-j', '--jsonrpc'), 'dest': 'jsonrpc', 'help': "Use JSON-RPC instead of the default protocol XML-RPC. " "Default = no, use XML-RPC", 'action': 'store_true', 'default': False}, {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string', 'action': 'store', 'default': 'odoo', 'help': "Odoo database name. Default = 'odoo'"}, {'names': ('-u', '--user-id'), 'dest': 'userid', 'type': 'int', 'action': 'store', 'default': 2, 'help': "Odoo user ID to use when connecting to Odoo in " "XML-RPC. Default = 2"}, {'names': ('-t', '--username'), 'dest': 'username', 'type': 'string', 'action': 'store', 'default': 'demo', 'help': "Odoo username to use when connecting to Odoo in " "JSON-RPC. Default = demo"}, {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string', 'action': 'store', 'default': 'demo', 'help': "Password of the Odoo user. Default = 'demo'"}, {'names': ('-a', '--ascii'), 'dest': 'ascii', 'action': 'store_true', 'default': False, 'help': "Convert name from UTF-8 to ASCII. Default = no, keep UTF-8"}, {'names': ('-n', '--notify'), 'dest': 'notify', 'action': 'store_true', 'default': False, 'help': "Notify Odoo users via a pop-up (requires the Odoo " "module 'base_phone_popup'). If you use this option, you must pass " "the logins of the Odoo users to notify as argument to the " "script. Default = no"}, {'names': ('-g', '--geoloc'), 'dest': 'geoloc', 'action': 'store_true', 'default': False, 'help': "Try to geolocate phone numbers unknown to Odoo. This " "features requires the 'phonenumbers' Python lib. To install it, " "run 'sudo pip install phonenumbers' Default = no"}, {'names': ('-l', '--geoloc-lang'), 'dest': 'lang', 'type': 'string', 'action': 'store', 'default': "en", 'help': "Language in which the name of the country and city name " "will be displayed by the geolocalisation database. Use the 2 " "letters ISO code of the language. Default = 'en'"}, {'names': ('-c', '--geoloc-country'), 'dest': 'country', 'type': 'string', 'action': 'store', 'default': "FR", 'help': "2 letters ISO code for your country e.g. 'FR' for France. " "This will be used by the geolocalisation system to parse the phone " "number of the calling party. Default = 'FR'"}, {'names': ('-o', '--outgoing'), 'dest': 'outgoing', 'action': 'store_true', 'default': False, 'help': "Update the Connected Line ID name on outgoing calls via a " "call to the Asterisk function CONNECTEDLINE(), instead of updating " "the Caller ID name on incoming calls. Default = no."}, {'names': ('-i', '--outgoing-agi-variable'), 'dest': 'outgoing_agi_var', 'type': 'string', 'action': 'store', 'default': "extension", 'help': "Enter the name of the AGI variable (without the 'agi_' " "prefix) from which the script will get the phone number dialed by " "the user on outgoing calls. For example, with Xivo, you should " "specify 'dnid' as the AGI variable. Default = 'extension'"}, {'names': ('-m', '--max-size'), 'dest': 'max_size', 'type': 'int', 'action': 'store', 'default': 40, 'help': "If the name has more characters this maximum size, cut it " "to this maximum size. Default = 40"}, ] def geolocate_phone_number(number, my_country_code, lang): import phonenumbers import phonenumbers.geocoder # Takes an enormous amount of time... res = '' phonenum = phonenumbers.parse(number, my_country_code.upper()) city = phonenumbers.geocoder.description_for_number(phonenum, lang.lower()) country_code = phonenumbers.region_code_for_number(phonenum) # We don't display the country name when it's my own country if country_code == my_country_code.upper(): if city: res = city else: # Convert country code to country name country = phonenumbers.geocoder._region_display_name( country_code, lang.lower()) if country and city: res = country + ' ' + city elif country and not city: res = country return res def convert_to_ascii(my_unicode): '''Convert to ascii, with clever management of accents (é -> e, è -> e)''' import unicodedata if isinstance(my_unicode, unicode): my_unicode_with_ascii_chars_only = ''.join(( char for char in unicodedata.normalize('NFD', my_unicode) if unicodedata.category(char) != 'Mn')) return str(my_unicode_with_ascii_chars_only) # If the argument is already of string type, return it with the same value elif isinstance(my_unicode, str): return my_unicode else: return False def main(options, arguments): # print 'options = %s' % options # print 'arguments = %s' % arguments agi = agilib.AGI() if options.outgoing: phone_number = agi.env['agi_%s' % options.outgoing_agi_var] agi.verbose("Dialed phone number is %s" % phone_number) else: # If we already have a "True" caller ID name # i.e. not just digits, but a real name, then we don't try to # connect to Odoo or geoloc, we just keep it if ( agi.env.get('agi_calleridname') and not agi.env['agi_calleridname'].isdigit() and agi.env['agi_calleridname'].lower() not in ['asterisk', 'unknown', 'anonymous'] and not options.notify): agi.verbose( "Incoming CallerID name is %s" % agi.env['agi_calleridname']) agi.verbose("As it is a real name, we do not change it") return True phone_number = agi.env['agi_callerid'] if not isinstance(phone_number, str): agi.verbose("Phone number is empty") exit(0) # Match for particular cases and anonymous phone calls # To test anonymous call in France, dial 3651 + number if not phone_number.isdigit(): agi.verbose("Phone number (%s) is not a digit" % phone_number) exit(0) agi.verbose("Phone number = %s" % phone_number) if options.notify and not arguments: agi.verbose( "When using the notify option, you must give arguments " "to the script") exit(0) if options.notify: method = 'incall_notify_by_login' else: method = 'get_name_from_phone_number' res = False # Yes, this script can be used without "-s odoo_server" ! if options.server and options.jsonrpc: import odoorpc proto = options.ssl and 'jsonrpc+ssl' or 'jsonrpc' agi.verbose( "Starting %s request on Odoo %s:%d database %s username %s" % ( proto.upper(), options.server, options.port, options.database, options.username)) try: odoo = odoorpc.ODOO(options.server, proto, options.port) odoo.login(options.database, options.username, options.password) if options.notify: res = odoo.execute( 'phone.common', method, phone_number, arguments) else: res = odoo.execute('phone.common', method, phone_number) agi.verbose("Called method %s" % method) except: agi.verbose("Could not connect to Odoo in JSON-RPC") elif options.server: proto = options.ssl and 'https' or 'http' agi.verbose( "Starting %s XML-RPC request on Odoo %s:%d " "database %s user ID %d" % ( proto, options.server, options.port, options.database, options.userid)) sock = xmlrpclib.ServerProxy( '%s://%s:%d/xmlrpc/object' % (proto, options.server, options.port)) try: if options.notify: res = sock.execute( options.database, options.userid, options.password, 'phone.common', method, phone_number, arguments) else: res = sock.execute( options.database, options.userid, options.password, 'phone.common', method, phone_number) agi.verbose("Called method %s" % method) except: agi.verbose("Could not connect to Odoo in XML-RPC") # To simulate a long execution of the XML-RPC request # import time # time.sleep(5) # Function to limit the size of the name if res: if len(res) > options.max_size: res = res[0:options.max_size] elif options.geoloc: # if the number is not found in Odoo, we try to geolocate agi.verbose( "Trying to geolocate with country %s and lang %s" % (options.country, options.lang)) res = geolocate_phone_number( phone_number, options.country, options.lang) else: # if the number is not found in Odoo and geoloc is off, # we put 'not_found_name' as Name agi.verbose("Phone number not found in Odoo") res = not_found_name # All SIP phones should support UTF-8... # but in case you have analog phones over TDM # or buggy phones, you should use the command line option --ascii if options.ascii: res = convert_to_ascii(res) agi.verbose("Name = %s" % res) if res: if options.outgoing: agi.set_variable('connectedlinename', res) else: agi.set_callerid('"%s"<%s>' % (res, phone_number)) return True if __name__ == '__main__': usage = "Usage: get_name_agi.py [options] login1 login2 login3 ..." epilog = "Script written by Alexis de Lattre. " "Published under the GNU AGPL licence." description = "This is an AGI script that sends a query to Odoo. " "It can also be used without Odoo to geolocate phone numbers " "of incoming calls." parser = OptionParser(usage=usage, epilog=epilog, description=description) for option in options: param = option['names'] del option['names'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
import numpy as np from copy import copy from copy import deepcopy from itertools import zip_longest import traceback from pycqed.utilities.general import temporary_value from pycqed.measurement.quantum_experiment import QuantumExperiment from pycqed.measurement.waveform_control.circuit_builder import CircuitBuilder from pycqed.measurement.waveform_control.block import Block, ParametricValue from pycqed.measurement.waveform_control.segment import UnresolvedPulse from pycqed.measurement.sweep_points import SweepPoints from pycqed.measurement.calibration.calibration_points import CalibrationPoints import pycqed.measurement.awg_sweep_functions as awg_swf import pycqed.analysis_v2.timedomain_analysis as tda from pycqed.instrument_drivers.meta_instrument.qubit_objects.QuDev_transmon \ import QuDev_transmon from pycqed.measurement import multi_qubit_module as mqm import logging log = logging.getLogger(__name__) # TODO: docstrings (list all kw at the highest level with reference to where # they are explained, explain all kw where they are processed) # TODO: add some comments that explain the way the code works class MultiTaskingExperiment(QuantumExperiment): kw_for_sweep_points = {} kw_for_task_keys = () def __init__(self, task_list, dev=None, qubits=None, operation_dict=None, **kw): self.task_list = task_list self.generate_kw_sweep_points(kw) # Try to get qubits or at least qb_names _, qb_names = self.extract_qubits(dev, qubits, operation_dict) # Filter to the ones that are needed qb_names = self.find_qubits_in_tasks(qb_names, task_list) # Initialize the QuantumExperiment super().__init__(dev=dev, qubits=qubits, operation_dict=operation_dict, filter_qb_names=qb_names, **kw) if 'sweep_points' in kw: self.sweep_points = kw.pop('sweep_points') self.cal_points = None self.cal_states = None self.exception = None self.all_main_blocks = [] self.data_to_fit = {} self.experiment_name = kw.pop( 'experiment_name', getattr(self, 'experiment_name', 'Experiment')) # The following is done because the respective call in the init of # QuantumExperiment does not capture all kw since many are explicit # arguments of the init there. kw.pop('exp_metadata', None) self.exp_metadata.update(kw) self.create_cal_points(**kw) def add_to_meas_obj_sweep_points_map(self, meas_objs, sweep_point): if 'meas_obj_sweep_points_map' not in self.exp_metadata: self.exp_metadata['meas_obj_sweep_points_map'] = {} if not isinstance(meas_objs, list): meas_objs = [meas_objs] for mo in meas_objs: if mo not in self.exp_metadata['meas_obj_sweep_points_map']: self.exp_metadata['meas_obj_sweep_points_map'][mo] = [] if sweep_point not in self.exp_metadata[ 'meas_obj_sweep_points_map'][mo]: self.exp_metadata['meas_obj_sweep_points_map'][mo].append( sweep_point) def get_meas_objs_from_task(self, task): return self.find_qubits_in_tasks(self.qb_names, [task]) def guess_label(self, **kw): if self.label is None: self.label = self.experiment_name if self.dev is not None: self.label += self.dev.get_msmt_suffix(self.meas_obj_names) else: # guess_label is called from run_measurement -> we have qubits self.label += mqm.get_multi_qubit_msmt_suffix(self.meas_objs) def run_measurement(self, **kw): # allow the user to overwrite the automatically generated list of # channels to upload self.channels_to_upload = kw.get('channels_to_upload', self.channels_to_upload) self.df_kwargs.update( {'nr_averages': max(qb.acq_averages() for qb in self.meas_objs)}) self.exp_metadata.update({ 'preparation_params': self.get_prep_params(), 'rotate': len(self.cal_states) != 0 and not self.classified, 'sweep_points': self.sweep_points, 'ro_qubits': self.meas_obj_names, 'data_to_fit': self.data_to_fit, }) if self.task_list is not None: self.exp_metadata.update({'task_list': self.task_list}) super().run_measurement(**kw) def create_cal_points(self, n_cal_points_per_state=1, cal_states='auto', for_ef=False, **kw): """ Creates a CalibrationPoints object based on the given parameters. :param n_cal_points_per_state: number of segments for each calibration state :param cal_states: str or tuple of str; the calibration states to measure :param for_ef: bool indicating whether to measure the |f> calibration state for each qubit :param kw: keyword arguments (to allow pass through kw even if it contains entries that are not needed) :return: CalibrationPoints object """ self.cal_states = CalibrationPoints.guess_cal_states( cal_states, for_ef=for_ef) self.cal_points = CalibrationPoints.multi_qubit( self.meas_obj_names, self.cal_states, n_per_state=n_cal_points_per_state) self.exp_metadata.update({'cal_points': repr(self.cal_points)}) def preprocess_task_list(self, **kw): given_sweep_points = self.sweep_points self.sweep_points = SweepPoints(from_dict_list=given_sweep_points) while len(self.sweep_points) < 2: self.sweep_points.add_sweep_dimension() preprocessed_task_list = [] for task in self.task_list: preprocessed_task_list.append( self.preprocess_task(task, self.sweep_points, given_sweep_points, **kw)) return preprocessed_task_list def preprocess_task(self, task, global_sweep_points, sweep_points=None, **kw): task = copy(task) # no deepcopy: might contain qubit objects prefix = task.get('prefix', None) if prefix is None: # try to guess one based on contained qubits prefix = '_'.join(self.find_qubits_in_tasks(self.qb_names, [task])) prefix += ('_' if prefix[-1] != '_' else '') task['prefix'] = prefix mo = self.get_meas_objs_from_task(task) for param in self.kw_for_task_keys: if param not in task: task[param] = kw.get(param, None) current_sweep_points = SweepPoints(from_dict_list=sweep_points) self.generate_kw_sweep_points(task) current_sweep_points.update( SweepPoints(from_dict_list=task['sweep_points'])) params_to_prefix = [d.keys() for d in task['sweep_points']] task['params_to_prefix'] = params_to_prefix task['sweep_points'] = current_sweep_points while len(current_sweep_points) < 2: current_sweep_points.add_sweep_dimension() while len(params_to_prefix) < 2: params_to_prefix.append([]) for gsp, csp, params in zip(global_sweep_points, current_sweep_points, params_to_prefix): for k in csp.keys(): if k in params: gsp[prefix + k] = csp[k] self.add_to_meas_obj_sweep_points_map(mo, prefix + k) else: self.add_to_meas_obj_sweep_points_map(mo, k) return task def parallel_sweep(self, preprocessed_task_list=(), block_func=None, **kw): """ Calls a block creation function for each task in a task list, puts these blocks in parallel and sweeps over the given sweep points. :param task_list: a list of dictionaries, each containing keyword arguments for block_func, plus a key 'prefix' with a unique prefix string, plus optionally a key 'params_to_prefix' created by preprocess_task indicating which sweep parameters have to be prefixed with the task prefix. :param block_func: a handle to a function that creates a block :param kw: keyword arguments are passed to sweep_n_dim :return: see sweep_n_dim """ parallel_blocks = [] for task in preprocessed_task_list: task = copy(task) prefix = task.pop('prefix') params_to_prefix = task.pop('params_to_prefix', None) if not 'block_func' in task: task['block_func'] = block_func new_block = task['block_func'](**task) if params_to_prefix is not None: new_block.prefix_parametric_values( prefix, [k for l in params_to_prefix for k in l]) parallel_blocks.append(new_block) self.all_main_blocks = self.simultaneous_blocks('all', parallel_blocks) if len(self.sweep_points[1]) == 0: # with this dummy soft sweep, exactly one sequence will be created # and the data format will be the same as for a true soft sweep self.sweep_points.add_sweep_parameter('dummy_sweep_param', [0]) # only measure meas_objs if 'ro_qubits' not in kw: op_codes = [p['op_code'] for p in self.all_main_blocks.pulses if 'op_code' in p] kw = copy(kw) kw['ro_qubits'] = [m for m in self.meas_obj_names if f'RO {m}' not in op_codes] return self.sweep_n_dim(self.sweep_points, body_block=self.all_main_blocks, cal_points=self.cal_points, **kw) @staticmethod def find_qubits_in_tasks(qubits, task_list, search_in_operations=True): qbs_dict = {qb if isinstance(qb, str) else qb.name: qb for qb in qubits} found_qubits = [] def append_qbs(found_qubits, candidate): if isinstance(candidate, QuDev_transmon): if candidate not in found_qubits: found_qubits.append(candidate) elif isinstance(candidate, str): if candidate in qbs_dict.keys(): if qbs_dict[candidate] not in found_qubits: found_qubits.append(qbs_dict[candidate]) elif ' ' in candidate and search_in_operations: append_qbs(found_qubits, candidate.split(' ')) elif isinstance(candidate, list): for v in candidate: append_qbs(found_qubits, v) else: return None for task in task_list: for v in task.values(): append_qbs(found_qubits, v) return found_qubits def create_meas_objs_list(self, task_list=None, **kw): if task_list is None: task_list = self.task_list if task_list is None: task_list = [{}] ro_qubits = kw.pop('ro_qubits', None) if ro_qubits is None: ro_qubits = [qb for task in task_list for qb in task.pop( 'ro_qubits', self.get_meas_objs_from_task(task))] else: ro_qubits += [qb for task in task_list for qb in task.pop('ro_qubits', [])] # unique and sort ro_qubits = [qb if isinstance(qb, str) else qb.name for qb in ro_qubits] ro_qubits = list(np.unique(ro_qubits)) ro_qubits.sort() self.meas_objs, self.meas_obj_names = self.get_qubits( 'all' if len(ro_qubits) == 0 else ro_qubits) def generate_kw_sweep_points(self, task): # instead of a task, a kw dict can also be passed task['sweep_points'] = SweepPoints( from_dict_list=task.get('sweep_points', None)) for k, vals in self.kw_for_sweep_points.items(): if isinstance(vals, dict): vals = [vals] for v in vals: v = copy(v) values_func = v.pop('values_func', None) if k in task and task[k] is not None: if values_func is not None: values = values_func(task[k]) elif isinstance(task[k], int): values = np.arange(task[k]) else: values = task[k] task['sweep_points'].add_sweep_parameter( values=values, **v) class CalibBuilder(MultiTaskingExperiment): def __init__(self, task_list, **kw): super().__init__(task_list=task_list, **kw) self.update = kw.pop('update', False) def max_pulse_length(self, pulse, sweep_points=None, given_pulse_length=None): pulse = copy(pulse) pulse['name'] = 'tmp' pulse['element_name'] = 'tmp' if given_pulse_length is not None: pulse['pulse_length'] = given_pulse_length p = UnresolvedPulse(pulse) return p.pulse_obj.length b = Block('tmp', [pulse]) sweep_points = deepcopy(sweep_points) if sweep_points is None: sweep_points = SweepPoints(from_dict_list=[{}, {}]) if len(sweep_points) == 1: sweep_points.add_sweep_dimension() for i in range(len(sweep_points)): if len(sweep_points[i]) == 0: sweep_points[i].update({'dummy': ([0], '', 'dummy')}) nr_sp_list = [len(list(d.values())[0][0]) for d in sweep_points] max_length = 0 for i in range(nr_sp_list[1]): for j in range(nr_sp_list[0]): pulses = b.build( sweep_dicts_list=sweep_points, sweep_index_list=[j, i]) p = UnresolvedPulse(pulses[1]) max_length = max(p.pulse_obj.length, max_length) return max_length def prepend_pulses_block(self, prepend_pulse_dicts): prepend_pulses = [] if prepend_pulse_dicts is not None: for i, pp in enumerate(prepend_pulse_dicts): prepend_pulse = self.get_pulse(pp['op_code']) prepend_pulse.update(pp) prepend_pulses += [prepend_pulse] return Block('prepend', prepend_pulses) @staticmethod def add_default_ramsey_sweep_points(sweep_points, **kw): sweep_points = SweepPoints(from_dict_list=sweep_points, min_length=2) if len(sweep_points[0]) > 0: nr_phases = sweep_points.length(0) // 2 else: nr_phases = kw.get('nr_phases', 6) hard_sweep_dict = SweepPoints() if 'phase' not in sweep_points[0]: hard_sweep_dict.add_sweep_parameter( 'phase', np.tile(np.linspace(0, 2 * np.pi, nr_phases) * 180 / np.pi, 2), 'deg') sweep_points.update(hard_sweep_dict + [{}]) return sweep_points class CPhase(CalibBuilder): """ class to measure the leakage and the phase acquired during a flux pulse conditioned on the state of another qubit (qbl). In this measurement, the phase from two Ramsey type measurements on qbr is measured, once with the control qubit in the excited state and once in the ground state. The conditional phase is calculated as the difference. Args: FIXME: add further args TODO :param cz_pulse_name: see CircuitBuilder :param n_cal_points_per_state: see CalibBuilder.get_cal_points() ... """ def __init__(self, task_list, sweep_points=None, **kw): try: self.experiment_name = 'CPhase_measurement' for task in task_list: for k in ['qbl', 'qbr']: if not isinstance(task[k], str): task[k] = task[k].name if not 'prefix' in task: task['prefix'] = f"{task['qbl']}{task['qbr']}_" kw['for_ef'] = kw.get('for_ef', True) super().__init__(task_list, sweep_points=sweep_points, **kw) self.cphases = None self.population_losses = None self.leakage = None self.cz_durations = {} self.cal_states_rotations = {} self.add_default_sweep_points(**kw) self.preprocessed_task_list = self.preprocess_task_list(**kw) self.sequences, self.mc_points = self.parallel_sweep( self.preprocessed_task_list, self.cphase_block, **kw) self.exp_metadata.update({ 'cz_durations': self.cz_durations, 'cal_states_rotations': self.cal_states_rotations, }) self.autorun(**kw) except Exception as x: self.exception = x traceback.print_exc() def add_default_sweep_points(self, **kw): self.sweep_points = self.add_default_ramsey_sweep_points( self.sweep_points, **kw) nr_phases = self.sweep_points.length(0) // 2 hard_sweep_dict = SweepPoints( 'pi_pulse_off', [0] * nr_phases + [1] * nr_phases) self.sweep_points.update(hard_sweep_dict + [{}]) def cphase_block(self, sweep_points, qbl, qbr, num_cz_gates=1, max_flux_length=None, prepend_pulse_dicts=None, **kw): """ TODO :param cz_pulse_name: task-specific prefix of CZ gates (overwrites global choice passed to the class init) ... """ hard_sweep_dict, soft_sweep_dict = sweep_points assert num_cz_gates % 2 != 0 pb = self.prepend_pulses_block(prepend_pulse_dicts) pulse_modifs = {'all': {'element_name': 'cphase_initial_rots_el'}} ir = self.block_from_ops('initial_rots', [f'X180 {qbl}', f'X90s {qbr}'] + kw.get('spectator_op_codes', []), pulse_modifs=pulse_modifs) ir.pulses[0]['pulse_off'] = ParametricValue(param='pi_pulse_off') fp = self.block_from_ops('flux', [f"{kw.get('cz_pulse_name', 'CZ')} " f"{qbl} {qbr}"] * num_cz_gates) # TODO here, we could do DD pulses (CH by 2020-06-19) # FIXME: currently, this assumes that only flux pulse parameters are # swept in the soft sweep. In fact, channels_to_upload should be # determined based on the sweep_points for k in ['channel', 'channel2']: if k in fp.pulses[0]: if fp.pulses[0][k] not in self.channels_to_upload: self.channels_to_upload.append(fp.pulses[0][k]) for k in soft_sweep_dict: for p in fp.pulses: p[k] = ParametricValue(k) if max_flux_length is not None: log.debug(f'max_flux_length = {max_flux_length * 1e9:.2f} ns, ' f'set by user') max_flux_length = self.max_pulse_length(fp.pulses[0], sweep_points, max_flux_length) pulse_modifs = {'all': {'element_name': 'cphase_final_rots_el'}} fr = self.block_from_ops('final_rots', [f'X180 {qbl}', f'X90s {qbr}'], pulse_modifs=pulse_modifs) fr.pulses[0]['pulse_delay'] = max_flux_length * num_cz_gates fr.pulses[0]['pulse_off'] = ParametricValue(param='pi_pulse_off') for k in hard_sweep_dict.keys(): if k != 'pi_pulse_on' and '=' not in k: fr.pulses[1][k] = ParametricValue(k) self.cz_durations.update({ fp.pulses[0]['op_code']: fr.pulses[0]['pulse_delay']}) self.cal_states_rotations.update({qbl: {'g': 0, 'e': 1, 'f': 2}, qbr: {'g': 0, 'e': 1}}) self.data_to_fit.update({qbl: 'pf', qbr: 'pe'}) fp_fr = self.simultaneous_blocks('sim', [fp, fr]) return self.sequential_blocks(f'cphase {qbl} {qbr}', [pb, ir, fp_fr]) def guess_label(self, **kw): predictive_label = kw.pop('predictive_label', False) if self.label is None: if predictive_label: self.label = 'Predictive_' + self.experiment_name else: self.label = self.experiment_name if self.classified: self.label += '_classified' if 'active' in self.get_prep_params()['preparation_type']: self.label += '_reset' # if num_cz_gates > 1: # label += f'_{num_cz_gates}_gates' for t in self.task_list: self.label += f"_{t['qbl']}{t['qbr']}" def get_meas_objs_from_task(self, task): return [task['qbl'], task['qbr']] def run_analysis(self, **kw): plot_all_traces = kw.get('plot_all_traces', True) plot_all_probs = kw.get('plot_all_probs', True) if self.classified: channel_map = {qb.name: [vn + ' ' + qb.instr_uhf() for vn in qb.int_avg_classif_det.value_names] for qb in self.meas_objs} else: channel_map = {qb.name: [vn + ' ' + qb.instr_uhf() for vn in qb.int_avg_det.value_names] for qb in self.meas_objs} self.analysis = tda.CPhaseLeakageAnalysis( qb_names=self.qb_names, options_dict={'TwoD': True, 'plot_all_traces': plot_all_traces, 'plot_all_probs': plot_all_probs, 'channel_map': channel_map}) self.cphases = {} self.population_losses = {} self.leakage = {} for task in self.task_list: self.cphases.update({task['prefix'][:-1]: self.analysis.proc_data_dict[ 'analysis_params_dict'][f"cphase_{task['qbr']}"]['val']}) self.population_losses.update( {task['prefix'][:-1]: self.analysis.proc_data_dict[ 'analysis_params_dict'][ f"population_loss_{task['qbr']}"]['val']}) self.leakage.update( {task['prefix'][:-1]: self.analysis.proc_data_dict[ 'analysis_params_dict'][ f"leakage_{task['qbl']}"]['val']}) return self.cphases, self.population_losses, self.leakage, \ self.analysis class DynamicPhase(CalibBuilder): def __init__(self, task_list, sweep_points=None, **kw): try: self.simultaneous = kw.get('simultaneous', False) self.reset_phases_before_measurement = kw.get( 'reset_phases_before_measurement', True) self.dynamic_phase_analysis = {} self.dyn_phases = {} self.old_dyn_phases = {} for task in task_list: if task.get('qubits_to_measure', None) is None: task['qubits_to_measure'] = task['op_code'].split(' ')[1:] else: # copy to not modify the caller's list task['qubits_to_measure'] = copy(task['qubits_to_measure']) for k, v in enumerate(task['qubits_to_measure']): if not isinstance(v, str): task['qubits_to_measure'][k] = v.name if 'prefix' not in task: task['prefix'] = task['op_code'].replace(' ', '') qbm_all = [task['qubits_to_measure'] for task in task_list] if not self.simultaneous and max([len(qbs) for qbs in qbm_all]) > 1: # create a child for each measurement task_lists = [] # the number of required children is the length of the # longest qubits_to_measure for z in zip_longest(*qbm_all): new_task_list = [] for task, new_qb in zip(task_list, z): if new_qb is not None: new_task = copy(task) new_task['qubits_to_measure'] = [new_qb] new_task_list.append(new_task) task_lists.append(new_task_list) # children should not update self.update = kw.pop('update', False) self.measurements = [DynamicPhase(tl, sweep_points, **kw) for tl in task_lists] if self.measurements[0].analyze: for m in self.measurements: for k, v in m.dyn_phases.items(): if k not in self.dyn_phases: self.dyn_phases[k] = {} self.dyn_phases[k].update(v) else: # this happens if we are in child or if simultaneous=True or # if only one qubit per task is measured self.measurements = [self] super().__init__(task_list, sweep_points=sweep_points, **kw) self.add_default_sweep_points(**kw) if self.reset_phases_before_measurement: for task in task_list: self.operation_dict[self.get_cz_operation_name( **task)]['basis_rotation'] = {} self.preprocessed_task_list = self.preprocess_task_list(**kw) self.sequences, self.mc_points = self.parallel_sweep( self.preprocessed_task_list, self.dynamic_phase_block, **kw) self.autorun(**kw) if self.update: assert self.dev is not None, \ "Update only works with device object provided." assert self.measurements[0].analyze, \ "Update is only allowed with analyze=True." assert len(self.measurements[0].mc_points[1]) == 1, \ "Update is only allowed without a soft sweep." for op, dp in self.dyn_phases.items(): op_split = op.split(' ') basis_rot_par = self.dev.get_pulse_par( *op_split, param='basis_rotation') if self.reset_phases_before_measurement: basis_rot_par(dp) else: not_updated = {k: v for k, v in basis_rot_par().items() if k not in dp} basis_rot_par().update(dp) if len(not_updated) > 0: log.warning(f'Not all basis_rotations stored in the ' f'pulse settings for {op} have been ' f'measured. Keeping the following old ' f'value(s): {not_updated}') except Exception as x: self.exception = x traceback.print_exc() def add_default_sweep_points(self, **kw): self.sweep_points = self.add_default_ramsey_sweep_points( self.sweep_points, **kw) nr_phases = self.sweep_points.length(0) // 2 hard_sweep_dict = SweepPoints( 'flux_pulse_off', [0] * nr_phases + [1] * nr_phases) self.sweep_points.update(hard_sweep_dict + [{}]) def guess_label(self, **kw): if self.label is None: self.label = f'Dynamic_phase_measurement' for task in self.task_list: self.label += "_" + task['prefix'] + "_" for qb_name in task['qubits_to_measure']: self.label += f"{qb_name}" def dynamic_phase_block(self, sweep_points, op_code, qubits_to_measure, prepend_pulse_dicts=None, **kw): assert (sum([qb in op_code.split(' ')[1:] for qb in qubits_to_measure]) <= 1), \ f"Dynamic phases of control and target qubit cannot be " \ f"measured simultaneously ({op_code})." hard_sweep_dict, soft_sweep_dict = sweep_points pb = self.prepend_pulses_block(prepend_pulse_dicts) pulse_modifs = { 'all': {'element_name': 'pi_half_start', 'ref_pulse': 'start'}} ir = self.block_from_ops('initial_rots', [f'X90 {qb}' for qb in qubits_to_measure], pulse_modifs=pulse_modifs) # calling op_replace_cz() allows to have a custom cz_pulse_name in kw fp = self.block_from_ops( 'flux', self.get_cz_operation_name(op_code=op_code, **kw)) fp.pulses[0]['pulse_off'] = ParametricValue('flux_pulse_off') # FIXME: currently, this assumes that only flux pulse parameters are # swept in the soft sweep. In fact, channels_to_upload should be # determined based on the sweep_points for k in ['channel', 'channel2']: if k in fp.pulses[0]: if fp.pulses[0][k] not in self.channels_to_upload: self.channels_to_upload.append(fp.pulses[0][k]) for k in soft_sweep_dict: if '=' not in k: # pulse modifier in the sweep dict fp.pulses[0][k] = ParametricValue(k) pulse_modifs = { 'all': {'element_name': 'pi_half_end', 'ref_pulse': 'start'}} fr = self.block_from_ops('final_rots', [f'X90 {qb}' for qb in qubits_to_measure], pulse_modifs=pulse_modifs) for p in fr.pulses: for k in hard_sweep_dict.keys(): if '=' not in k and k != 'flux_pulse_off': p[k] = ParametricValue(k) self.data_to_fit.update({qb: 'pe' for qb in qubits_to_measure}) return self.sequential_blocks( f"dynphase {'_'.join(qubits_to_measure)}", [pb, ir, fp, fr]) def get_meas_objs_from_task(self, task): return task['qubits_to_measure'] def run_analysis(self, **kw): extract_only = kw.pop('extract_only', False) for task in self.task_list: op = self.get_cz_operation_name(**task) op_split = op.split(' ') self.dynamic_phase_analysis[task['prefix']] = \ tda.CZDynamicPhaseAnalysis( qb_names=task['qubits_to_measure'], options_dict={ 'flux_pulse_length': self.dev.get_pulse_par( *op_split, param='pulse_length')(), 'flux_pulse_amp': self.dev.get_pulse_par( *op_split, param='amplitude')(), # FIXME in analysis: in case of a soft sweep, analysis # has to overwrite length and amp with values from the # sweep_points 'save_figs': ~extract_only}, extract_only=extract_only) self.dyn_phases[op] = {} for qb_name in task['qubits_to_measure']: self.dyn_phases[op][qb_name] = \ self.dynamic_phase_analysis[task['prefix']].proc_data_dict[ 'analysis_params_dict'][qb_name][ 'dynamic_phase']['val'] * 180 / np.pi return self.dyn_phases, self.dynamic_phase_analysis class Chevron(CalibBuilder): """ TODO Args: FIXME: add further args TODO :param cz_pulse_name: see CircuitBuilder :param n_cal_points_per_state: see CalibBuilder.get_cal_points() ... """ def __init__(self, task_list, sweep_points=None, **kw): try: self.experiment_name = 'Chevron' for task in task_list: if task.get('qbr', None) is None: task['qbr'] = task['qbt'] for k in ['qbc', 'qbt', 'qbr']: if not isinstance(task[k], str): task[k] = task[k].name if task['qbr'] not in [task['qbc'], task['qbt']]: raise ValueError( 'Only target or control qubit can be read out!') if not 'prefix' in task: task['prefix'] = f"{task['qbc']}{task['qbt']}_" super().__init__(task_list, sweep_points=sweep_points, **kw) self.preprocessed_task_list = self.preprocess_task_list(**kw) self.sequences, self.mc_points = self.parallel_sweep( self.preprocessed_task_list, self.sweep_block, **kw) self.autorun(**kw) except Exception as x: self.exception = x traceback.print_exc() def add_default_sweep_points(self, sweep_points, **kw): sweep_points = self.add_default_ramsey_sweep_points(sweep_points, **kw) nr_phases = sweep_points.length(0) // 2 hard_sweep_dict = SweepPoints( 'pi_pulse_off', [0] * nr_phases + [1] * nr_phases) sweep_points.update(hard_sweep_dict + [{}]) return sweep_points def sweep_block(self, sweep_points, qbc, qbt, qbr, num_cz_gates=1, max_flux_length=None, prepend_pulse_dicts=None, **kw): """ chevron block (sweep of flux pulse parameters) Timings of sequence <-- length --> qb_control: |X180| --- | fluxpulse | qb_target: |X180| -------------------------------------- |RO| TODO :param cz_pulse_name: task-specific prefix of CZ gates (overwrites global choice passed to the class init) ... """ hard_sweep_dict, soft_sweep_dict = sweep_points pb = self.prepend_pulses_block(prepend_pulse_dicts) pulse_modifs = {'all': {'element_name': 'initial_rots_el'}} ir = self.block_from_ops('initial_rots', [f'X180 {qbc}', f'X180 {qbt}'], pulse_modifs=pulse_modifs) ir.pulses[1]['ref_point_new'] = 'end' fp = self.block_from_ops('flux', [f"{kw.get('cz_pulse_name', 'CZ')} " f"{qbc} {qbt}"] * num_cz_gates) # FIXME: currently, this assumes that only flux pulse parameters are # swept in the soft sweep. In fact, channels_to_upload should be # determined based on the sweep_points for k in ['channel', 'channel2']: if k in fp.pulses[0]: if fp.pulses[0][k] not in self.channels_to_upload: self.channels_to_upload.append(fp.pulses[0][k]) for k in list(hard_sweep_dict.keys()) + list(soft_sweep_dict.keys()): for p in fp.pulses: p[k] = ParametricValue(k) if max_flux_length is not None: log.debug(f'max_flux_length = {max_flux_length * 1e9:.2f} ns, ' f'set by user') max_flux_length = self.max_pulse_length(fp.pulses[0], sweep_points, max_flux_length) b = self.sequential_blocks(f'chevron {qbc} {qbt}', [pb, ir, fp]) b.block_end.update({'ref_pulse': 'initial_rots-|-end', 'pulse_delay': max_flux_length * num_cz_gates}) self.data_to_fit.update({qbr: 'pe'}) return b def guess_label(self, **kw): if self.label is None: self.label = self.experiment_name for t in self.task_list: self.label += f"_{t['qbc']}{t['qbt']}" def get_meas_objs_from_task(self, task): # FIXME is this correct? it will prevent us from doing # preselection/reset on the other qubit return [task['qbr']] def run_analysis(self, **kw): self.analysis = tda.MultiQubit_TimeDomain_Analysis( qb_names=[task['qbr'] for task in self.task_list], options_dict={'TwoD': True}) return self.analysis DynamicPhase: fixed bugs in analysis call and related to update import numpy as np from copy import copy from copy import deepcopy from itertools import zip_longest import traceback from pycqed.utilities.general import temporary_value from pycqed.measurement.quantum_experiment import QuantumExperiment from pycqed.measurement.waveform_control.circuit_builder import CircuitBuilder from pycqed.measurement.waveform_control.block import Block, ParametricValue from pycqed.measurement.waveform_control.segment import UnresolvedPulse from pycqed.measurement.sweep_points import SweepPoints from pycqed.measurement.calibration.calibration_points import CalibrationPoints import pycqed.measurement.awg_sweep_functions as awg_swf import pycqed.analysis_v2.timedomain_analysis as tda from pycqed.instrument_drivers.meta_instrument.qubit_objects.QuDev_transmon \ import QuDev_transmon from pycqed.measurement import multi_qubit_module as mqm import logging log = logging.getLogger(__name__) # TODO: docstrings (list all kw at the highest level with reference to where # they are explained, explain all kw where they are processed) # TODO: add some comments that explain the way the code works class MultiTaskingExperiment(QuantumExperiment): kw_for_sweep_points = {} kw_for_task_keys = () def __init__(self, task_list, dev=None, qubits=None, operation_dict=None, **kw): self.task_list = task_list self.generate_kw_sweep_points(kw) # Try to get qubits or at least qb_names _, qb_names = self.extract_qubits(dev, qubits, operation_dict) # Filter to the ones that are needed qb_names = self.find_qubits_in_tasks(qb_names, task_list) # Initialize the QuantumExperiment super().__init__(dev=dev, qubits=qubits, operation_dict=operation_dict, filter_qb_names=qb_names, **kw) if 'sweep_points' in kw: self.sweep_points = kw.pop('sweep_points') self.cal_points = None self.cal_states = None self.exception = None self.all_main_blocks = [] self.data_to_fit = {} self.experiment_name = kw.pop( 'experiment_name', getattr(self, 'experiment_name', 'Experiment')) # The following is done because the respective call in the init of # QuantumExperiment does not capture all kw since many are explicit # arguments of the init there. kw.pop('exp_metadata', None) self.exp_metadata.update(kw) self.create_cal_points(**kw) def add_to_meas_obj_sweep_points_map(self, meas_objs, sweep_point): if 'meas_obj_sweep_points_map' not in self.exp_metadata: self.exp_metadata['meas_obj_sweep_points_map'] = {} if not isinstance(meas_objs, list): meas_objs = [meas_objs] for mo in meas_objs: if mo not in self.exp_metadata['meas_obj_sweep_points_map']: self.exp_metadata['meas_obj_sweep_points_map'][mo] = [] if sweep_point not in self.exp_metadata[ 'meas_obj_sweep_points_map'][mo]: self.exp_metadata['meas_obj_sweep_points_map'][mo].append( sweep_point) def get_meas_objs_from_task(self, task): return self.find_qubits_in_tasks(self.qb_names, [task]) def guess_label(self, **kw): if self.label is None: self.label = self.experiment_name if self.dev is not None: self.label += self.dev.get_msmt_suffix(self.meas_obj_names) else: # guess_label is called from run_measurement -> we have qubits self.label += mqm.get_multi_qubit_msmt_suffix(self.meas_objs) def run_measurement(self, **kw): # allow the user to overwrite the automatically generated list of # channels to upload self.channels_to_upload = kw.get('channels_to_upload', self.channels_to_upload) self.df_kwargs.update( {'nr_averages': max(qb.acq_averages() for qb in self.meas_objs)}) self.exp_metadata.update({ 'preparation_params': self.get_prep_params(), 'rotate': len(self.cal_states) != 0 and not self.classified, 'sweep_points': self.sweep_points, 'ro_qubits': self.meas_obj_names, 'data_to_fit': self.data_to_fit, }) if self.task_list is not None: self.exp_metadata.update({'task_list': self.task_list}) super().run_measurement(**kw) def create_cal_points(self, n_cal_points_per_state=1, cal_states='auto', for_ef=False, **kw): """ Creates a CalibrationPoints object based on the given parameters. :param n_cal_points_per_state: number of segments for each calibration state :param cal_states: str or tuple of str; the calibration states to measure :param for_ef: bool indicating whether to measure the |f> calibration state for each qubit :param kw: keyword arguments (to allow pass through kw even if it contains entries that are not needed) :return: CalibrationPoints object """ self.cal_states = CalibrationPoints.guess_cal_states( cal_states, for_ef=for_ef) self.cal_points = CalibrationPoints.multi_qubit( self.meas_obj_names, self.cal_states, n_per_state=n_cal_points_per_state) self.exp_metadata.update({'cal_points': repr(self.cal_points)}) def preprocess_task_list(self, **kw): given_sweep_points = self.sweep_points self.sweep_points = SweepPoints(from_dict_list=given_sweep_points) while len(self.sweep_points) < 2: self.sweep_points.add_sweep_dimension() preprocessed_task_list = [] for task in self.task_list: preprocessed_task_list.append( self.preprocess_task(task, self.sweep_points, given_sweep_points, **kw)) return preprocessed_task_list def preprocess_task(self, task, global_sweep_points, sweep_points=None, **kw): task = copy(task) # no deepcopy: might contain qubit objects prefix = task.get('prefix', None) if prefix is None: # try to guess one based on contained qubits prefix = '_'.join(self.find_qubits_in_tasks(self.qb_names, [task])) prefix += ('_' if prefix[-1] != '_' else '') task['prefix'] = prefix mo = self.get_meas_objs_from_task(task) for param in self.kw_for_task_keys: if param not in task: task[param] = kw.get(param, None) current_sweep_points = SweepPoints(from_dict_list=sweep_points) self.generate_kw_sweep_points(task) current_sweep_points.update( SweepPoints(from_dict_list=task['sweep_points'])) params_to_prefix = [d.keys() for d in task['sweep_points']] task['params_to_prefix'] = params_to_prefix task['sweep_points'] = current_sweep_points while len(current_sweep_points) < 2: current_sweep_points.add_sweep_dimension() while len(params_to_prefix) < 2: params_to_prefix.append([]) for gsp, csp, params in zip(global_sweep_points, current_sweep_points, params_to_prefix): for k in csp.keys(): if k in params: gsp[prefix + k] = csp[k] self.add_to_meas_obj_sweep_points_map(mo, prefix + k) else: self.add_to_meas_obj_sweep_points_map(mo, k) return task def parallel_sweep(self, preprocessed_task_list=(), block_func=None, **kw): """ Calls a block creation function for each task in a task list, puts these blocks in parallel and sweeps over the given sweep points. :param task_list: a list of dictionaries, each containing keyword arguments for block_func, plus a key 'prefix' with a unique prefix string, plus optionally a key 'params_to_prefix' created by preprocess_task indicating which sweep parameters have to be prefixed with the task prefix. :param block_func: a handle to a function that creates a block :param kw: keyword arguments are passed to sweep_n_dim :return: see sweep_n_dim """ parallel_blocks = [] for task in preprocessed_task_list: task = copy(task) prefix = task.pop('prefix') params_to_prefix = task.pop('params_to_prefix', None) if not 'block_func' in task: task['block_func'] = block_func new_block = task['block_func'](**task) if params_to_prefix is not None: new_block.prefix_parametric_values( prefix, [k for l in params_to_prefix for k in l]) parallel_blocks.append(new_block) self.all_main_blocks = self.simultaneous_blocks('all', parallel_blocks) if len(self.sweep_points[1]) == 0: # with this dummy soft sweep, exactly one sequence will be created # and the data format will be the same as for a true soft sweep self.sweep_points.add_sweep_parameter('dummy_sweep_param', [0]) # only measure meas_objs if 'ro_qubits' not in kw: op_codes = [p['op_code'] for p in self.all_main_blocks.pulses if 'op_code' in p] kw = copy(kw) kw['ro_qubits'] = [m for m in self.meas_obj_names if f'RO {m}' not in op_codes] return self.sweep_n_dim(self.sweep_points, body_block=self.all_main_blocks, cal_points=self.cal_points, **kw) @staticmethod def find_qubits_in_tasks(qubits, task_list, search_in_operations=True): qbs_dict = {qb if isinstance(qb, str) else qb.name: qb for qb in qubits} found_qubits = [] def append_qbs(found_qubits, candidate): if isinstance(candidate, QuDev_transmon): if candidate not in found_qubits: found_qubits.append(candidate) elif isinstance(candidate, str): if candidate in qbs_dict.keys(): if qbs_dict[candidate] not in found_qubits: found_qubits.append(qbs_dict[candidate]) elif ' ' in candidate and search_in_operations: append_qbs(found_qubits, candidate.split(' ')) elif isinstance(candidate, list): for v in candidate: append_qbs(found_qubits, v) else: return None for task in task_list: for v in task.values(): append_qbs(found_qubits, v) return found_qubits def create_meas_objs_list(self, task_list=None, **kw): if task_list is None: task_list = self.task_list if task_list is None: task_list = [{}] ro_qubits = kw.pop('ro_qubits', None) if ro_qubits is None: ro_qubits = [qb for task in task_list for qb in task.pop( 'ro_qubits', self.get_meas_objs_from_task(task))] else: ro_qubits += [qb for task in task_list for qb in task.pop('ro_qubits', [])] # unique and sort ro_qubits = [qb if isinstance(qb, str) else qb.name for qb in ro_qubits] ro_qubits = list(np.unique(ro_qubits)) ro_qubits.sort() self.meas_objs, self.meas_obj_names = self.get_qubits( 'all' if len(ro_qubits) == 0 else ro_qubits) def generate_kw_sweep_points(self, task): # instead of a task, a kw dict can also be passed task['sweep_points'] = SweepPoints( from_dict_list=task.get('sweep_points', None)) for k, vals in self.kw_for_sweep_points.items(): if isinstance(vals, dict): vals = [vals] for v in vals: v = copy(v) values_func = v.pop('values_func', None) if k in task and task[k] is not None: if values_func is not None: values = values_func(task[k]) elif isinstance(task[k], int): values = np.arange(task[k]) else: values = task[k] task['sweep_points'].add_sweep_parameter( values=values, **v) class CalibBuilder(MultiTaskingExperiment): def __init__(self, task_list, **kw): super().__init__(task_list=task_list, **kw) self.update = kw.pop('update', False) def max_pulse_length(self, pulse, sweep_points=None, given_pulse_length=None): pulse = copy(pulse) pulse['name'] = 'tmp' pulse['element_name'] = 'tmp' if given_pulse_length is not None: pulse['pulse_length'] = given_pulse_length p = UnresolvedPulse(pulse) return p.pulse_obj.length b = Block('tmp', [pulse]) sweep_points = deepcopy(sweep_points) if sweep_points is None: sweep_points = SweepPoints(from_dict_list=[{}, {}]) if len(sweep_points) == 1: sweep_points.add_sweep_dimension() for i in range(len(sweep_points)): if len(sweep_points[i]) == 0: sweep_points[i].update({'dummy': ([0], '', 'dummy')}) nr_sp_list = [len(list(d.values())[0][0]) for d in sweep_points] max_length = 0 for i in range(nr_sp_list[1]): for j in range(nr_sp_list[0]): pulses = b.build( sweep_dicts_list=sweep_points, sweep_index_list=[j, i]) p = UnresolvedPulse(pulses[1]) max_length = max(p.pulse_obj.length, max_length) return max_length def prepend_pulses_block(self, prepend_pulse_dicts): prepend_pulses = [] if prepend_pulse_dicts is not None: for i, pp in enumerate(prepend_pulse_dicts): prepend_pulse = self.get_pulse(pp['op_code']) prepend_pulse.update(pp) prepend_pulses += [prepend_pulse] return Block('prepend', prepend_pulses) @staticmethod def add_default_ramsey_sweep_points(sweep_points, **kw): sweep_points = SweepPoints(from_dict_list=sweep_points, min_length=2) if len(sweep_points[0]) > 0: nr_phases = sweep_points.length(0) // 2 else: nr_phases = kw.get('nr_phases', 6) hard_sweep_dict = SweepPoints() if 'phase' not in sweep_points[0]: hard_sweep_dict.add_sweep_parameter( 'phase', np.tile(np.linspace(0, 2 * np.pi, nr_phases) * 180 / np.pi, 2), 'deg') sweep_points.update(hard_sweep_dict + [{}]) return sweep_points class CPhase(CalibBuilder): """ class to measure the leakage and the phase acquired during a flux pulse conditioned on the state of another qubit (qbl). In this measurement, the phase from two Ramsey type measurements on qbr is measured, once with the control qubit in the excited state and once in the ground state. The conditional phase is calculated as the difference. Args: FIXME: add further args TODO :param cz_pulse_name: see CircuitBuilder :param n_cal_points_per_state: see CalibBuilder.get_cal_points() ... """ def __init__(self, task_list, sweep_points=None, **kw): try: self.experiment_name = 'CPhase_measurement' for task in task_list: for k in ['qbl', 'qbr']: if not isinstance(task[k], str): task[k] = task[k].name if not 'prefix' in task: task['prefix'] = f"{task['qbl']}{task['qbr']}_" kw['for_ef'] = kw.get('for_ef', True) super().__init__(task_list, sweep_points=sweep_points, **kw) self.cphases = None self.population_losses = None self.leakage = None self.cz_durations = {} self.cal_states_rotations = {} self.add_default_sweep_points(**kw) self.preprocessed_task_list = self.preprocess_task_list(**kw) self.sequences, self.mc_points = self.parallel_sweep( self.preprocessed_task_list, self.cphase_block, **kw) self.exp_metadata.update({ 'cz_durations': self.cz_durations, 'cal_states_rotations': self.cal_states_rotations, }) self.autorun(**kw) except Exception as x: self.exception = x traceback.print_exc() def add_default_sweep_points(self, **kw): self.sweep_points = self.add_default_ramsey_sweep_points( self.sweep_points, **kw) nr_phases = self.sweep_points.length(0) // 2 hard_sweep_dict = SweepPoints( 'pi_pulse_off', [0] * nr_phases + [1] * nr_phases) self.sweep_points.update(hard_sweep_dict + [{}]) def cphase_block(self, sweep_points, qbl, qbr, num_cz_gates=1, max_flux_length=None, prepend_pulse_dicts=None, **kw): """ TODO :param cz_pulse_name: task-specific prefix of CZ gates (overwrites global choice passed to the class init) ... """ hard_sweep_dict, soft_sweep_dict = sweep_points assert num_cz_gates % 2 != 0 pb = self.prepend_pulses_block(prepend_pulse_dicts) pulse_modifs = {'all': {'element_name': 'cphase_initial_rots_el'}} ir = self.block_from_ops('initial_rots', [f'X180 {qbl}', f'X90s {qbr}'] + kw.get('spectator_op_codes', []), pulse_modifs=pulse_modifs) ir.pulses[0]['pulse_off'] = ParametricValue(param='pi_pulse_off') fp = self.block_from_ops('flux', [f"{kw.get('cz_pulse_name', 'CZ')} " f"{qbl} {qbr}"] * num_cz_gates) # TODO here, we could do DD pulses (CH by 2020-06-19) # FIXME: currently, this assumes that only flux pulse parameters are # swept in the soft sweep. In fact, channels_to_upload should be # determined based on the sweep_points for k in ['channel', 'channel2']: if k in fp.pulses[0]: if fp.pulses[0][k] not in self.channels_to_upload: self.channels_to_upload.append(fp.pulses[0][k]) for k in soft_sweep_dict: for p in fp.pulses: p[k] = ParametricValue(k) if max_flux_length is not None: log.debug(f'max_flux_length = {max_flux_length * 1e9:.2f} ns, ' f'set by user') max_flux_length = self.max_pulse_length(fp.pulses[0], sweep_points, max_flux_length) pulse_modifs = {'all': {'element_name': 'cphase_final_rots_el'}} fr = self.block_from_ops('final_rots', [f'X180 {qbl}', f'X90s {qbr}'], pulse_modifs=pulse_modifs) fr.pulses[0]['pulse_delay'] = max_flux_length * num_cz_gates fr.pulses[0]['pulse_off'] = ParametricValue(param='pi_pulse_off') for k in hard_sweep_dict.keys(): if k != 'pi_pulse_on' and '=' not in k: fr.pulses[1][k] = ParametricValue(k) self.cz_durations.update({ fp.pulses[0]['op_code']: fr.pulses[0]['pulse_delay']}) self.cal_states_rotations.update({qbl: {'g': 0, 'e': 1, 'f': 2}, qbr: {'g': 0, 'e': 1}}) self.data_to_fit.update({qbl: 'pf', qbr: 'pe'}) fp_fr = self.simultaneous_blocks('sim', [fp, fr]) return self.sequential_blocks(f'cphase {qbl} {qbr}', [pb, ir, fp_fr]) def guess_label(self, **kw): predictive_label = kw.pop('predictive_label', False) if self.label is None: if predictive_label: self.label = 'Predictive_' + self.experiment_name else: self.label = self.experiment_name if self.classified: self.label += '_classified' if 'active' in self.get_prep_params()['preparation_type']: self.label += '_reset' # if num_cz_gates > 1: # label += f'_{num_cz_gates}_gates' for t in self.task_list: self.label += f"_{t['qbl']}{t['qbr']}" def get_meas_objs_from_task(self, task): return [task['qbl'], task['qbr']] def run_analysis(self, **kw): plot_all_traces = kw.get('plot_all_traces', True) plot_all_probs = kw.get('plot_all_probs', True) if self.classified: channel_map = {qb.name: [vn + ' ' + qb.instr_uhf() for vn in qb.int_avg_classif_det.value_names] for qb in self.meas_objs} else: channel_map = {qb.name: [vn + ' ' + qb.instr_uhf() for vn in qb.int_avg_det.value_names] for qb in self.meas_objs} self.analysis = tda.CPhaseLeakageAnalysis( qb_names=self.qb_names, options_dict={'TwoD': True, 'plot_all_traces': plot_all_traces, 'plot_all_probs': plot_all_probs, 'channel_map': channel_map}) self.cphases = {} self.population_losses = {} self.leakage = {} for task in self.task_list: self.cphases.update({task['prefix'][:-1]: self.analysis.proc_data_dict[ 'analysis_params_dict'][f"cphase_{task['qbr']}"]['val']}) self.population_losses.update( {task['prefix'][:-1]: self.analysis.proc_data_dict[ 'analysis_params_dict'][ f"population_loss_{task['qbr']}"]['val']}) self.leakage.update( {task['prefix'][:-1]: self.analysis.proc_data_dict[ 'analysis_params_dict'][ f"leakage_{task['qbl']}"]['val']}) return self.cphases, self.population_losses, self.leakage, \ self.analysis class DynamicPhase(CalibBuilder): def __init__(self, task_list, sweep_points=None, **kw): try: self.simultaneous = kw.get('simultaneous', False) self.reset_phases_before_measurement = kw.get( 'reset_phases_before_measurement', True) self.dynamic_phase_analysis = {} self.dyn_phases = {} self.old_dyn_phases = {} for task in task_list: if task.get('qubits_to_measure', None) is None: task['qubits_to_measure'] = task['op_code'].split(' ')[1:] else: # copy to not modify the caller's list task['qubits_to_measure'] = copy(task['qubits_to_measure']) for k, v in enumerate(task['qubits_to_measure']): if not isinstance(v, str): task['qubits_to_measure'][k] = v.name if 'prefix' not in task: task['prefix'] = task['op_code'].replace(' ', '') qbm_all = [task['qubits_to_measure'] for task in task_list] if not self.simultaneous and max([len(qbs) for qbs in qbm_all]) > 1: # create a child for each measurement task_lists = [] # the number of required children is the length of the # longest qubits_to_measure for z in zip_longest(*qbm_all): new_task_list = [] for task, new_qb in zip(task_list, z): if new_qb is not None: new_task = copy(task) new_task['qubits_to_measure'] = [new_qb] new_task_list.append(new_task) task_lists.append(new_task_list) # device object will be needed for update self.dev = kw.get('dev', None) # children should not update self.update = kw.pop('update', False) self.measurements = [DynamicPhase(tl, sweep_points, **kw) for tl in task_lists] if self.measurements[0].analyze: for m in self.measurements: for k, v in m.dyn_phases.items(): if k not in self.dyn_phases: self.dyn_phases[k] = {} self.dyn_phases[k].update(v) else: # this happens if we are in child or if simultaneous=True or # if only one qubit per task is measured self.measurements = [self] super().__init__(task_list, sweep_points=sweep_points, **kw) self.add_default_sweep_points(**kw) if self.reset_phases_before_measurement: for task in task_list: self.operation_dict[self.get_cz_operation_name( **task)]['basis_rotation'] = {} self.preprocessed_task_list = self.preprocess_task_list(**kw) self.sequences, self.mc_points = self.parallel_sweep( self.preprocessed_task_list, self.dynamic_phase_block, **kw) self.autorun(**kw) if self.update: assert self.dev is not None, \ "Update only works with device object provided." assert self.measurements[0].analyze, \ "Update is only allowed with analyze=True." assert len(self.measurements[0].mc_points[1]) == 1, \ "Update is only allowed without a soft sweep." for op, dp in self.dyn_phases.items(): op_split = op.split(' ') basis_rot_par = self.dev.get_pulse_par( *op_split, param='basis_rotation') if self.reset_phases_before_measurement: basis_rot_par(dp) else: not_updated = {k: v for k, v in basis_rot_par().items() if k not in dp} basis_rot_par().update(dp) if len(not_updated) > 0: log.warning(f'Not all basis_rotations stored in the ' f'pulse settings for {op} have been ' f'measured. Keeping the following old ' f'value(s): {not_updated}') except Exception as x: self.exception = x traceback.print_exc() def add_default_sweep_points(self, **kw): self.sweep_points = self.add_default_ramsey_sweep_points( self.sweep_points, **kw) nr_phases = self.sweep_points.length(0) // 2 hard_sweep_dict = SweepPoints( 'flux_pulse_off', [0] * nr_phases + [1] * nr_phases) self.sweep_points.update(hard_sweep_dict + [{}]) def guess_label(self, **kw): if self.label is None: self.label = f'Dynamic_phase_measurement' for task in self.task_list: self.label += "_" + task['prefix'] + "_" for qb_name in task['qubits_to_measure']: self.label += f"{qb_name}" def dynamic_phase_block(self, sweep_points, op_code, qubits_to_measure, prepend_pulse_dicts=None, **kw): assert (sum([qb in op_code.split(' ')[1:] for qb in qubits_to_measure]) <= 1), \ f"Dynamic phases of control and target qubit cannot be " \ f"measured simultaneously ({op_code})." hard_sweep_dict, soft_sweep_dict = sweep_points pb = self.prepend_pulses_block(prepend_pulse_dicts) pulse_modifs = { 'all': {'element_name': 'pi_half_start', 'ref_pulse': 'start'}} ir = self.block_from_ops('initial_rots', [f'X90 {qb}' for qb in qubits_to_measure], pulse_modifs=pulse_modifs) # calling op_replace_cz() allows to have a custom cz_pulse_name in kw fp = self.block_from_ops( 'flux', self.get_cz_operation_name(op_code=op_code, **kw)) fp.pulses[0]['pulse_off'] = ParametricValue('flux_pulse_off') # FIXME: currently, this assumes that only flux pulse parameters are # swept in the soft sweep. In fact, channels_to_upload should be # determined based on the sweep_points for k in ['channel', 'channel2']: if k in fp.pulses[0]: if fp.pulses[0][k] not in self.channels_to_upload: self.channels_to_upload.append(fp.pulses[0][k]) for k in soft_sweep_dict: if '=' not in k: # pulse modifier in the sweep dict fp.pulses[0][k] = ParametricValue(k) pulse_modifs = { 'all': {'element_name': 'pi_half_end', 'ref_pulse': 'start'}} fr = self.block_from_ops('final_rots', [f'X90 {qb}' for qb in qubits_to_measure], pulse_modifs=pulse_modifs) for p in fr.pulses: for k in hard_sweep_dict.keys(): if '=' not in k and k != 'flux_pulse_off': p[k] = ParametricValue(k) self.data_to_fit.update({qb: 'pe' for qb in qubits_to_measure}) return self.sequential_blocks( f"dynphase {'_'.join(qubits_to_measure)}", [pb, ir, fp, fr]) def get_meas_objs_from_task(self, task): return task['qubits_to_measure'] def run_analysis(self, **kw): extract_only = kw.pop('extract_only', False) for task in self.task_list: op = self.get_cz_operation_name(**task) op_split = op.split(' ') self.dynamic_phase_analysis[task['prefix']] = \ tda.DynamicPhaseAnalysis( qb_names=task['qubits_to_measure'], options_dict={ 'flux_pulse_length': self.dev.get_pulse_par( *op_split, param='pulse_length')(), 'flux_pulse_amp': self.dev.get_pulse_par( *op_split, param='amplitude')(), # FIXME in analysis: in case of a soft sweep, analysis # has to overwrite length and amp with values from the # sweep_points 'save_figs': ~extract_only}, extract_only=extract_only) self.dyn_phases[op] = {} for qb_name in task['qubits_to_measure']: self.dyn_phases[op][qb_name] = \ self.dynamic_phase_analysis[task['prefix']].proc_data_dict[ 'analysis_params_dict'][f"dynamic_phase_{qb_name}"][ 'val'] * 180 / np.pi return self.dyn_phases, self.dynamic_phase_analysis class Chevron(CalibBuilder): """ TODO Args: FIXME: add further args TODO :param cz_pulse_name: see CircuitBuilder :param n_cal_points_per_state: see CalibBuilder.get_cal_points() ... """ def __init__(self, task_list, sweep_points=None, **kw): try: self.experiment_name = 'Chevron' for task in task_list: if task.get('qbr', None) is None: task['qbr'] = task['qbt'] for k in ['qbc', 'qbt', 'qbr']: if not isinstance(task[k], str): task[k] = task[k].name if task['qbr'] not in [task['qbc'], task['qbt']]: raise ValueError( 'Only target or control qubit can be read out!') if not 'prefix' in task: task['prefix'] = f"{task['qbc']}{task['qbt']}_" super().__init__(task_list, sweep_points=sweep_points, **kw) self.preprocessed_task_list = self.preprocess_task_list(**kw) self.sequences, self.mc_points = self.parallel_sweep( self.preprocessed_task_list, self.sweep_block, **kw) self.autorun(**kw) except Exception as x: self.exception = x traceback.print_exc() def add_default_sweep_points(self, sweep_points, **kw): sweep_points = self.add_default_ramsey_sweep_points(sweep_points, **kw) nr_phases = sweep_points.length(0) // 2 hard_sweep_dict = SweepPoints( 'pi_pulse_off', [0] * nr_phases + [1] * nr_phases) sweep_points.update(hard_sweep_dict + [{}]) return sweep_points def sweep_block(self, sweep_points, qbc, qbt, qbr, num_cz_gates=1, max_flux_length=None, prepend_pulse_dicts=None, **kw): """ chevron block (sweep of flux pulse parameters) Timings of sequence <-- length --> qb_control: |X180| --- | fluxpulse | qb_target: |X180| -------------------------------------- |RO| TODO :param cz_pulse_name: task-specific prefix of CZ gates (overwrites global choice passed to the class init) ... """ hard_sweep_dict, soft_sweep_dict = sweep_points pb = self.prepend_pulses_block(prepend_pulse_dicts) pulse_modifs = {'all': {'element_name': 'initial_rots_el'}} ir = self.block_from_ops('initial_rots', [f'X180 {qbc}', f'X180 {qbt}'], pulse_modifs=pulse_modifs) ir.pulses[1]['ref_point_new'] = 'end' fp = self.block_from_ops('flux', [f"{kw.get('cz_pulse_name', 'CZ')} " f"{qbc} {qbt}"] * num_cz_gates) # FIXME: currently, this assumes that only flux pulse parameters are # swept in the soft sweep. In fact, channels_to_upload should be # determined based on the sweep_points for k in ['channel', 'channel2']: if k in fp.pulses[0]: if fp.pulses[0][k] not in self.channels_to_upload: self.channels_to_upload.append(fp.pulses[0][k]) for k in list(hard_sweep_dict.keys()) + list(soft_sweep_dict.keys()): for p in fp.pulses: p[k] = ParametricValue(k) if max_flux_length is not None: log.debug(f'max_flux_length = {max_flux_length * 1e9:.2f} ns, ' f'set by user') max_flux_length = self.max_pulse_length(fp.pulses[0], sweep_points, max_flux_length) b = self.sequential_blocks(f'chevron {qbc} {qbt}', [pb, ir, fp]) b.block_end.update({'ref_pulse': 'initial_rots-|-end', 'pulse_delay': max_flux_length * num_cz_gates}) self.data_to_fit.update({qbr: 'pe'}) return b def guess_label(self, **kw): if self.label is None: self.label = self.experiment_name for t in self.task_list: self.label += f"_{t['qbc']}{t['qbt']}" def get_meas_objs_from_task(self, task): # FIXME is this correct? it will prevent us from doing # preselection/reset on the other qubit return [task['qbr']] def run_analysis(self, **kw): self.analysis = tda.MultiQubit_TimeDomain_Analysis( qb_names=[task['qbr'] for task in self.task_list], options_dict={'TwoD': True}) return self.analysis
# Copyright 2019 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OpenFOAM Benchmark. OpenFOAM is a C++ toolbox for the development of customized numerical solvers, and pre-/post-processing utilities for the solution of continuum mechanics problems, most prominently including computational fluid dynamics. https://openfoam.org/ This benchmark runs a motorbike simulation that is popularly used to measure scalability of OpenFOAM across multiple cores. Since this is a complex computation, make sure to use a compute-focused machine-type that has multiple cores before attempting to run. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import posixpath import re from perfkitbenchmarker import configs from perfkitbenchmarker import flags from perfkitbenchmarker import hpc_util from perfkitbenchmarker import sample from perfkitbenchmarker import vm_util from perfkitbenchmarker.linux_packages import openfoam _DEFAULT_CASE = 'motorbike' _CASE_PATHS = { 'motorbike': 'tutorials/incompressible/simpleFoam/motorBike', 'pipe_cyclic': 'tutorials/incompressible/simpleFoam/pipeCyclic', } assert _DEFAULT_CASE in _CASE_PATHS FLAGS = flags.FLAGS flags.DEFINE_enum( 'openfoam_case', _DEFAULT_CASE, sorted(list(_CASE_PATHS.keys())), 'Name of the OpenFOAM case to run.') # Convenience flag when running motorbike. Motorbike is the most common case, # so we provide different sizes here. _DEFAULT_MOTORBIKE_DIMENSIONS = 'small' _MOTORBIKE_DIMENSIONS = { 'small': '20 8 8', 'medium': '40 16 16', 'large': '80 32 32', 'x-large': '160 64 64', } assert _DEFAULT_MOTORBIKE_DIMENSIONS in _MOTORBIKE_DIMENSIONS flags.DEFINE_enum( 'openfoam_motorbike_dimensions', _DEFAULT_MOTORBIKE_DIMENSIONS, sorted(list(_MOTORBIKE_DIMENSIONS.keys())), 'If running motorbike, sets the dimensions of the motorbike case.') # Problem size and scaling flags.DEFINE_string( 'openfoam_dimensions', _MOTORBIKE_DIMENSIONS[_DEFAULT_MOTORBIKE_DIMENSIONS], 'Dimensions of the case.') flags.DEFINE_integer( 'openfoam_num_threads', None, 'The number of threads to run OpenFOAM with.') BENCHMARK_NAME = 'openfoam' _BENCHMARK_ROOT = '$HOME/OpenFOAM/run' BENCHMARK_CONFIG = """ openfoam: description: Runs an OpenFOAM benchmark. vm_groups: default: vm_spec: GCP: machine_type: c2-standard-8 zone: us-east1-c boot_disk_size: 100 Azure: machine_type: Standard_F8s_v2 zone: eastus2 boot_disk_size: 100 AWS: machine_type: c5.2xlarge zone: us-east-1f boot_disk_size: 100 os_type: ubuntu1604 vm_count: 2 disk_spec: GCP: disk_type: nfs nfs_managed: False mount_point: {path} Azure: disk_type: nfs nfs_managed: False mount_point: {path} AWS: disk_type: nfs nfs_managed: False mount_point: {path} """.format(path=_BENCHMARK_ROOT) _MACHINEFILE = 'MACHINEFILE' _RUNSCRIPT = 'Allrun' _DECOMPOSEDICT = 'system/decomposeParDict' _BLOCKMESHDICT = 'system/blockMeshDict' _TIME_RE = re.compile(r"""(\d+)m # The minutes part (\d+)\.\d+s # The seconds part """, re.VERBOSE) def GetConfig(user_config): """Returns the configuration of a benchmark.""" return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) def Prepare(benchmark_spec): """Prepares the VMs and other resources for running the benchmark. This is a good place to download binaries onto the VMs, create any data files needed for a benchmark run, etc. Args: benchmark_spec: The benchmark spec for this sample benchmark. """ vms = benchmark_spec.vms vm_util.RunThreaded(lambda vm: vm.Install('openfoam'), vms) master_vm = vms[0] master_vm.RemoteCommand('mkdir -p %s' % _BENCHMARK_ROOT) master_vm.RemoteCommand('cp -r {case_path} {run_path}'.format( case_path=posixpath.join(openfoam.OPENFOAM_ROOT, _CASE_PATHS[FLAGS.openfoam_case]), run_path=_BENCHMARK_ROOT)) if len(vms) > 1: # Allow ssh access to other vms master_vm.AuthenticateVm() # Avoid printing ssh warnings when running mpirun master_vm.RemoteCommand('echo "LogLevel ERROR" | ' 'tee -a $HOME/.ssh/config') # Tells mpirun about other nodes hpc_util.CreateMachineFile(vms, remote_path=_GetPath(_MACHINEFILE)) def _AsSeconds(input_time): """Convert time from formatted string to seconds. Input format: 200m1.419s Should return 1201 Args: input_time: The time to parse to a float. Returns: An integer representing the time in seconds. """ match = _TIME_RE.match(input_time) assert match, 'Time "{}" does not match format "{}"'.format(input_time, _TIME_RE.pattern) minutes, seconds = match.group(1, 2) return int(minutes) * 60 + int(seconds) def _GetSample(line): """Parse a single output line into a performance sample. Input format: real 4m1.419s Args: line: A single line from the OpenFOAM timing output. Returns: A single performance sample, with times in ms. """ runtime_category, runtime_output = line.split() runtime_seconds = _AsSeconds(runtime_output) logging.info('Runtime of %s seconds from [%s, %s]', runtime_seconds, runtime_category, runtime_output) runtime_category = 'time_' + runtime_category return sample.Sample(runtime_category, runtime_seconds, 'seconds') def _GetSamples(output): """Parse the output and return performance samples. Output is in the format: real 4m1.419s user 23m11.198s sys 0m25.274s Args: output: The output from running the OpenFOAM benchmark. Returns: A list of performance samples. """ return [_GetSample(line) for line in output.strip().splitlines()] def _GetOpenfoamVersion(vm): """Get the installed OpenFOAM version from the vm.""" return vm.RemoteCommand('echo $WM_PROJECT_VERSION')[0] def _GetOpenmpiVersion(vm): """Get the installed OpenMPI version from the vm.""" return vm.RemoteCommand('mpirun -version')[0].split()[3] def _GetWorkingDirPath(): """Get the base directory name of the case being run.""" case_dir_name = posixpath.basename(_CASE_PATHS[FLAGS.openfoam_case]) return posixpath.join(_BENCHMARK_ROOT, case_dir_name) def _GetPath(openfoam_file): """Get the absolute path to the file in the working directory.""" return posixpath.join(_GetWorkingDirPath(), openfoam_file) def _SetDecomposeMethod(vm, decompose_method): """Set the parallel decomposition method if using multiple cores.""" logging.info('Using %s decomposition', decompose_method) vm_util.ReplaceText(vm, 'method.*', 'method %s;' % decompose_method, _GetPath(_DECOMPOSEDICT)) def _SetNumProcesses(vm, num_processes): """Configure OpenFOAM to use the correct number of processes.""" logging.info('Decomposing into %s subdomains', num_processes) vm_util.ReplaceText(vm, 'numberOfSubdomains.*', 'numberOfSubdomains %s;' % str(num_processes), _GetPath(_DECOMPOSEDICT)) def _SetDimensions(vm, dimensions): """Sets the mesh dimensions in blockMeshDict. Replaces lines of the format: hex (0 1 2 3 4 5 6 7) (20 8 8) simpleGrading (1 1 1) with: hex (0 1 2 3 4 5 6 7) (dimensions) simpleGrading (1 1 1) Args: vm: The vm to make the replacement on. dimensions: String, new mesh dimensions to run with. """ logging.info('Using dimensions (%s) in blockMeshDict', dimensions) vm_util.ReplaceText(vm, r'(hex \(.*\) \().*(\) .* \(.*\))', r'\1{}\2'.format(dimensions), _GetPath(_BLOCKMESHDICT), regex_char='|') def _UseMpi(vm, num_processes): """Configure OpenFOAM to use MPI if running with more than 1 VM.""" runscript = _GetPath(_RUNSCRIPT) vm_util.ReplaceText( vm, 'runParallel', 'mpirun ' '-hostfile {machinefile} ' '-mca btl ^openib ' '--map-by node ' '-np {num_processes}'.format( machinefile=_GetPath(_MACHINEFILE), num_processes=num_processes), runscript, '|') vm_util.ReplaceText(vm, '^mpirun.*', '& -parallel', runscript) def Run(benchmark_spec): """Runs the benchmark and returns a dict of performance data. It must be possible to run the benchmark multiple times after the Prepare stage. Args: benchmark_spec: The benchmark spec for the OpenFOAM benchmark. Returns: A list of performance samples. """ vms = benchmark_spec.vms master_vm = vms[0] num_vms = len(vms) num_cpus_available = num_vms * master_vm.NumCpusForBenchmark() num_cpus_to_use = FLAGS.openfoam_num_threads or num_cpus_available // 2 logging.info('Running %s case on %s/%s cores on %s vms', FLAGS.openfoam_case, num_cpus_to_use, num_cpus_available, num_vms) # Configure the run case = FLAGS.openfoam_case master_vm.RemoteCommand('cp -r {case_path} {destination}'.format( case_path=posixpath.join(openfoam.OPENFOAM_ROOT, _CASE_PATHS[case]), destination=_BENCHMARK_ROOT)) if case == 'motorbike': dimensions = _MOTORBIKE_DIMENSIONS[FLAGS.openfoam_motorbike_dimensions] else: dimensions = FLAGS.openfoam_dimensions _SetDimensions(master_vm, dimensions) _SetDecomposeMethod(master_vm, 'scotch') _SetNumProcesses(master_vm, num_cpus_to_use) if num_vms > 1: _UseMpi(master_vm, num_cpus_to_use) # Run and collect samples run_command = ' && '.join([ 'cd %s' % _GetWorkingDirPath(), './Allclean', 'time ./Allrun' ]) _, run_output = master_vm.RemoteCommand(run_command) samples = _GetSamples(run_output) common_metadata = { 'case': FLAGS.openfoam_case, 'dimensions': dimensions, 'num_cpus_available': num_cpus_available, 'num_cpus_used': num_cpus_to_use, 'openfoam_version': _GetOpenfoamVersion(master_vm), 'openmpi_version': _GetOpenmpiVersion(master_vm) } for result in samples: result.metadata.update(common_metadata) return samples def Cleanup(benchmark_spec): """Cleans up after the benchmark completes. The state of the VMs should be equivalent to the state before Prepare was called. Args: benchmark_spec: The benchmark spec for the OpenFOAM benchmark. """ del benchmark_spec Fixes a "E701 multiple statements on one line (colon)" linter error. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=281605859 # Copyright 2019 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OpenFOAM Benchmark. OpenFOAM is a C++ toolbox for the development of customized numerical solvers, and pre-/post-processing utilities for the solution of continuum mechanics problems, most prominently including computational fluid dynamics. https://openfoam.org/ This benchmark runs a motorbike simulation that is popularly used to measure scalability of OpenFOAM across multiple cores. Since this is a complex computation, make sure to use a compute-focused machine-type that has multiple cores before attempting to run. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import posixpath import re from perfkitbenchmarker import configs from perfkitbenchmarker import flags from perfkitbenchmarker import hpc_util from perfkitbenchmarker import sample from perfkitbenchmarker import vm_util from perfkitbenchmarker.linux_packages import openfoam _DEFAULT_CASE = 'motorbike' _CASE_PATHS = { 'motorbike': 'tutorials/incompressible/simpleFoam/motorBike', 'pipe_cyclic': 'tutorials/incompressible/simpleFoam/pipeCyclic', } assert _DEFAULT_CASE in _CASE_PATHS FLAGS = flags.FLAGS flags.DEFINE_enum( 'openfoam_case', _DEFAULT_CASE, sorted(list(_CASE_PATHS.keys())), 'Name of the OpenFOAM case to run.') # Convenience flag when running motorbike. Motorbike is the most common case, # so we provide different sizes here. _DEFAULT_MOTORBIKE_DIMENSIONS = 'small' _MOTORBIKE_DIMENSIONS = { 'small': '20 8 8', 'medium': '40 16 16', 'large': '80 32 32', 'x-large': '160 64 64', } assert _DEFAULT_MOTORBIKE_DIMENSIONS in _MOTORBIKE_DIMENSIONS flags.DEFINE_enum( 'openfoam_motorbike_dimensions', _DEFAULT_MOTORBIKE_DIMENSIONS, sorted(list(_MOTORBIKE_DIMENSIONS.keys())), 'If running motorbike, sets the dimensions of the motorbike case.') # Problem size and scaling flags.DEFINE_string( 'openfoam_dimensions', _MOTORBIKE_DIMENSIONS[_DEFAULT_MOTORBIKE_DIMENSIONS], 'Dimensions of the case.') flags.DEFINE_integer( 'openfoam_num_threads', None, 'The number of threads to run OpenFOAM with.') BENCHMARK_NAME = 'openfoam' _BENCHMARK_ROOT = '$HOME/OpenFOAM/run' BENCHMARK_CONFIG = """ openfoam: description: Runs an OpenFOAM benchmark. vm_groups: default: vm_spec: GCP: machine_type: c2-standard-8 zone: us-east1-c boot_disk_size: 100 Azure: machine_type: Standard_F8s_v2 zone: eastus2 boot_disk_size: 100 AWS: machine_type: c5.2xlarge zone: us-east-1f boot_disk_size: 100 os_type: ubuntu1604 vm_count: 2 disk_spec: GCP: disk_type: nfs nfs_managed: False mount_point: {path} Azure: disk_type: nfs nfs_managed: False mount_point: {path} AWS: disk_type: nfs nfs_managed: False mount_point: {path} """.format(path=_BENCHMARK_ROOT) _MACHINEFILE = 'MACHINEFILE' _RUNSCRIPT = 'Allrun' _DECOMPOSEDICT = 'system/decomposeParDict' _BLOCKMESHDICT = 'system/blockMeshDict' _TIME_RE = re.compile(r"""(\d+)m # The minutes part (\d+)\.\d+s # The seconds part """, re.VERBOSE) def GetConfig(user_config): """Returns the configuration of a benchmark.""" return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) def Prepare(benchmark_spec): """Prepares the VMs and other resources for running the benchmark. This is a good place to download binaries onto the VMs, create any data files needed for a benchmark run, etc. Args: benchmark_spec: The benchmark spec for this sample benchmark. """ vms = benchmark_spec.vms vm_util.RunThreaded(lambda vm: vm.Install('openfoam'), vms) master_vm = vms[0] master_vm.RemoteCommand('mkdir -p %s' % _BENCHMARK_ROOT) master_vm.RemoteCommand('cp -r {case_path} {run_path}'.format( case_path=posixpath.join(openfoam.OPENFOAM_ROOT, _CASE_PATHS[FLAGS.openfoam_case]), run_path=_BENCHMARK_ROOT)) if len(vms) > 1: # Allow ssh access to other vms master_vm.AuthenticateVm() # Avoid printing ssh warnings when running mpirun master_vm.RemoteCommand('echo "LogLevel ERROR" | ' 'tee -a $HOME/.ssh/config') # Tells mpirun about other nodes hpc_util.CreateMachineFile(vms, remote_path=_GetPath(_MACHINEFILE)) def _AsSeconds(input_time): """Convert time from formatted string to seconds. Input format: 200m1.419s Should return 1201 Args: input_time: The time to parse to a float. Returns: An integer representing the time in seconds. """ match = _TIME_RE.match(input_time) assert match, 'Time "{}" does not match format "{}"'.format(input_time, _TIME_RE.pattern) minutes, seconds = match.group(1, 2) return int(minutes) * 60 + int(seconds) def _GetSample(line): """Parse a single output line into a performance sample. Input format: real 4m1.419s Args: line: A single line from the OpenFOAM timing output. Returns: A single performance sample, with times in ms. """ runtime_category, runtime_output = line.split() runtime_seconds = _AsSeconds(runtime_output) logging.info('Runtime of %s seconds from [%s, %s]', runtime_seconds, runtime_category, runtime_output) runtime_category = 'time_' + runtime_category return sample.Sample(runtime_category, runtime_seconds, 'seconds') def _GetSamples(output): """Parse the output and return performance samples. Output is in the format: real 4m1.419s user 23m11.198s sys 0m25.274s Args: output: The output from running the OpenFOAM benchmark. Returns: A list of performance samples. """ return [_GetSample(line) for line in output.strip().splitlines()] def _GetOpenfoamVersion(vm): """Get the installed OpenFOAM version from the vm.""" return vm.RemoteCommand('echo $WM_PROJECT_VERSION')[0] def _GetOpenmpiVersion(vm): """Get the installed OpenMPI version from the vm.""" return vm.RemoteCommand('mpirun -version')[0].split()[3] def _GetWorkingDirPath(): """Get the base directory name of the case being run.""" case_dir_name = posixpath.basename(_CASE_PATHS[FLAGS.openfoam_case]) return posixpath.join(_BENCHMARK_ROOT, case_dir_name) def _GetPath(openfoam_file): """Get the absolute path to the file in the working directory.""" return posixpath.join(_GetWorkingDirPath(), openfoam_file) def _SetDecomposeMethod(vm, decompose_method): """Set the parallel decomposition method if using multiple cores.""" logging.info('Using %s decomposition', decompose_method) vm_util.ReplaceText(vm, 'method.*', 'method %s;' % decompose_method, _GetPath(_DECOMPOSEDICT)) def _SetNumProcesses(vm, num_processes): """Configure OpenFOAM to use the correct number of processes.""" logging.info('Decomposing into %s subdomains', num_processes) vm_util.ReplaceText(vm, 'numberOfSubdomains.*', 'numberOfSubdomains %s;' % str(num_processes), _GetPath(_DECOMPOSEDICT)) def _SetDimensions(vm, dimensions): """Sets the mesh dimensions in blockMeshDict. Replaces lines of the format: hex (0 1 2 3 4 5 6 7) (20 8 8) simpleGrading (1 1 1) with: hex (0 1 2 3 4 5 6 7) (dimensions) simpleGrading (1 1 1) Args: vm: The vm to make the replacement on. dimensions: String, new mesh dimensions to run with. """ logging.info('Using dimensions (%s) in blockMeshDict', dimensions) vm_util.ReplaceText(vm, r'(hex \(.*\) \().*(\) .* \(.*\))', r'\1{}\2'.format(dimensions), _GetPath(_BLOCKMESHDICT), regex_char='|') def _UseMpi(vm, num_processes): """Configure OpenFOAM to use MPI if running with more than 1 VM.""" runscript = _GetPath(_RUNSCRIPT) vm_util.ReplaceText( vm, 'runParallel', 'mpirun ' '-hostfile {machinefile} ' '-mca btl ^openib ' '--map-by node ' '-np {num_processes}'.format( machinefile=_GetPath(_MACHINEFILE), num_processes=num_processes), runscript, '|') vm_util.ReplaceText(vm, '^mpirun.*', '& -parallel', runscript) def Run(benchmark_spec): """Runs the benchmark and returns a dict of performance data. It must be possible to run the benchmark multiple times after the Prepare stage. Args: benchmark_spec: The benchmark spec for the OpenFOAM benchmark. Returns: A list of performance samples. """ vms = benchmark_spec.vms master_vm = vms[0] num_vms = len(vms) num_cpus_available = num_vms * master_vm.NumCpusForBenchmark() num_cpus_to_use = FLAGS.openfoam_num_threads or num_cpus_available // 2 logging.info('Running %s case on %s/%s cores on %s vms', FLAGS.openfoam_case, num_cpus_to_use, num_cpus_available, num_vms) # Configure the run case = FLAGS.openfoam_case master_vm.RemoteCommand('cp -r {case_path} {destination}'.format( case_path=posixpath.join(openfoam.OPENFOAM_ROOT, _CASE_PATHS[case]), destination=_BENCHMARK_ROOT)) if case == 'motorbike': dimensions = _MOTORBIKE_DIMENSIONS[FLAGS.openfoam_motorbike_dimensions] else: dimensions = FLAGS.openfoam_dimensions _SetDimensions(master_vm, dimensions) _SetDecomposeMethod(master_vm, 'scotch') _SetNumProcesses(master_vm, num_cpus_to_use) if num_vms > 1: _UseMpi(master_vm, num_cpus_to_use) # Run and collect samples run_command = ' && '.join([ 'cd %s' % _GetWorkingDirPath(), './Allclean', 'time ./Allrun' ]) _, run_output = master_vm.RemoteCommand(run_command) samples = _GetSamples(run_output) common_metadata = { 'case': FLAGS.openfoam_case, 'dimensions': dimensions, 'num_cpus_available': num_cpus_available, 'num_cpus_used': num_cpus_to_use, 'openfoam_version': _GetOpenfoamVersion(master_vm), 'openmpi_version': _GetOpenmpiVersion(master_vm) } for result in samples: result.metadata.update(common_metadata) return samples def Cleanup(benchmark_spec): """Cleans up after the benchmark completes. The state of the VMs should be equivalent to the state before Prepare was called. Args: benchmark_spec: The benchmark spec for the OpenFOAM benchmark. """ del benchmark_spec
#!/usr/bin/env python # -*- coding: utf-8 -*- """ gallerize ~~~~~~~~~ Create a static HTML/CSS image gallery from a bunch of images. See README for details. :Copyright: 2007-2013 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from __future__ import print_function import argparse import codecs from collections import defaultdict, namedtuple try: from future_builtins import filter, map # Python 2.6+ except ImportError: pass # Python 3+ from itertools import islice import os import shutil import subprocess import sys from jinja2 import Environment, FileSystemLoader ARGS_DEFAULT_MAX_IMAGE_SIZE = '1024x1024' ARGS_DEFAULT_MAX_THUMBNAIL_SIZE = '120x120' IMAGE_CAPTION_EXTENSION = '.txt' TEMPLATE_EXTENSION = '.html' OUTPUT_HTML_EXTENSION = '.html' PATH = os.path.dirname(os.path.abspath(__file__)) PATH_STATIC = os.path.join(PATH, 'static') TEMPLATE_ENVIRONMENT = Environment( autoescape=True, loader=FileSystemLoader(os.path.join(PATH, 'templates')), trim_blocks=False) def debug(msg): print(msg) def resize_image(src_filename, dst_filename, max_dimension): """Create a resized (and antialiased) version of an image.""" dimension_str = '%dx%d' % (max_dimension.width, max_dimension.height) cmd = ['convert', '-resize', dimension_str, src_filename, dst_filename] subprocess.check_call(cmd) def render_html_to_file(template_name, context, path, page_name): """Render the template and write the result to the given file.""" context['url_for_page'] = lambda page: page + OUTPUT_HTML_EXTENSION html = render_template(template_name + TEMPLATE_EXTENSION, **context) filename = os.path.join(path, page_name + OUTPUT_HTML_EXTENSION) write_file(filename, html) def render_template(template_filename, **context): return TEMPLATE_ENVIRONMENT \ .get_template(template_filename) \ .render(context) def write_file(filename, content): with codecs.open(filename, 'wb', 'utf-8') as f: debug('Writing "%s" ...' % filename) f.write(content) class Gallery(object): @classmethod def from_args(cls, args): gallery = Gallery() gallery.images = [Image(gallery, image) for image in sorted(args.full_image_filenames)] gallery.link_images() gallery.title = args.title gallery.destination_path = args.destination_path gallery.resize = not args.no_resize gallery.max_image_size = args.max_image_size gallery.max_thumbnail_size = args.max_thumbnail_size return gallery def link_images(self): """Assign the predecessor and successor for every image.""" for previous_image, image, next_image \ in window([None] + self.images + [None], 3): image.previous_image = previous_image image.next_image = next_image def generate(self): # Create destination path if it doesn't exist. if not os.path.exists(self.destination_path): debug('Destination path "%s" does not exist, creating it.' % self.destination_path) os.mkdir(self.destination_path) self.generate_images() for image in self.images: image.load_caption() self.generate_stylesheet() self.render_html_pages() self.copy_additional_static_files() debug('Done.') def generate_images(self): for image in self.images: image.generate_image() image.generate_thumbnail() image.load_caption() def generate_stylesheet(self): filename = os.path.join(self.destination_path, 'style.css') css = render_template('style.css') write_file(filename, css) def render_html_pages(self): for image in self.images: image.render_html_page() self.render_html_index_page() def render_html_index_page(self): """Create an HTML document of thumbnails that link to single image documents. """ context = { 'gallery': self, } render_html_to_file('index', context, self.destination_path, 'index') def copy_additional_static_files(self): if not os.path.exists(PATH_STATIC): debug('Path "%s", does not exist; not copying any static files.' % PATH_STATIC) return filenames = list(sorted(os.listdir(PATH_STATIC))) if not filenames: debug('No static files to copy.') for filename in filenames: debug('Copying static file "%s" ...' % filename) shutil.copy( os.path.join(PATH_STATIC, filename), os.path.join(self.destination_path, filename)) def window(iterable, n): """Return a sliding window of width ``n`` over the iterable.""" it = iter(iterable) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result class Image(object): previous_image = None next_image = None def __init__(self, gallery, full_filename): self.gallery = gallery self.full_filename = full_filename self.path, self.filename = os.path.split(full_filename) self.basename, self.extension = os.path.splitext(self.filename) self.thumbnail_filename = '%s_t%s' % (self.basename, self.extension) self.page_name = self.basename def generate_image(self): """Create a (optionally resized) copy of an image.""" destination_filename = os.path.join(self.gallery.destination_path, self.filename) if self.gallery.resize: # Resize image. debug('Resizing image "%s" ...' % self.full_filename) resize_image(self.full_filename, destination_filename, self.gallery.max_image_size) else: # Copy image. debug('Copying image "%s" ...' % self.full_filename) shutil.copy(self.full_filename, destination_filename) def generate_thumbnail(self): """Create a preview of an image.""" debug('Creating thumbnail "%s" ...' % self.thumbnail_filename) destination_filename = os.path.join(self.gallery.destination_path, self.thumbnail_filename) resize_image(self.full_filename, destination_filename, self.gallery.max_thumbnail_size) def load_caption(self): """Load image caption from file.""" caption_filename = os.path.join(self.path, self.filename + IMAGE_CAPTION_EXTENSION) self.caption = self._read_first_line(caption_filename) def _read_first_line(self, filename): """Read the first line from the specified file.""" try: with codecs.open(filename, 'rb', 'utf-8') as f: return f.next().strip() except IOError: # File does not exist (OK) or cannot be read (not really OK). pass def render_html_page(self): """Create an HTML document for a single image.""" context = { 'image': self, } render_html_to_file('view', context, self.gallery.destination_path, self.page_name) # -------------------------------------------------------------------- # # command line argument parsing Dimension = namedtuple('Dimension', ['width', 'height']) def parse_dimension_arg(value): """Validate a dimension value.""" try: return Dimension(*map(int, value.split('x', 1))) except ValueError: raise argparse.ArgumentTypeError( 'invalid dimension value: %r' % value) def parse_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser( usage='%(prog)s [options] <target path> <image> [image] ...') parser.add_argument('-c', '--captions', dest='captions', action='store_true', default=False, help='read image captions from text files ("<IMAGE_NAME>.txt")') parser.add_argument('--no-resize', dest='no_resize', action='store_true', default=False, help='do not resize images, just copy them') parser.add_argument('-s', '--size', dest='max_image_size', type=Dimension, default=ARGS_DEFAULT_MAX_IMAGE_SIZE, help='set maximum image size [default: %s]' % ARGS_DEFAULT_MAX_IMAGE_SIZE) parser.add_argument('-t', '--thumbnail-size', dest='max_thumbnail_size', type=Dimension, default=ARGS_DEFAULT_MAX_THUMBNAIL_SIZE, help='set maximum thumbnail size [default: %s]' % ARGS_DEFAULT_MAX_THUMBNAIL_SIZE) parser.add_argument('--title', dest='title', help='set gallery title on the website') # First positional argument. parser.add_argument('destination_path') # Remaining positional arguments (at least one), as a list. parser.add_argument('full_image_filenames', nargs='+') return parser.parse_args() # -------------------------------------------------------------------- # def handle_duplicate_filenames(paths): duplicates = list(find_duplicate_filenames(paths)) if duplicates: print('Found duplicate filenames:') for filename, paths in duplicates: print(' + "%s" appears in the following paths:' % filename) for path in paths: print(' - ' + path) sys.exit('Clashing target filenames, aborting.') def find_duplicate_filenames(paths): d = defaultdict(list) for path in paths: key = os.path.basename(path).lower() d[key].append(path) return filter(lambda x: len(x[1]) > 1, d.items()) # -------------------------------------------------------------------- # if __name__ == '__main__': try: args = parse_args() handle_duplicate_filenames(args.full_image_filenames) Gallery.from_args(args).generate() except KeyboardInterrupt: sys.exit('Ctrl-C pressed, aborting.') Changed indentation according to PEP 8. #!/usr/bin/env python # -*- coding: utf-8 -*- """ gallerize ~~~~~~~~~ Create a static HTML/CSS image gallery from a bunch of images. See README for details. :Copyright: 2007-2013 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from __future__ import print_function import argparse import codecs from collections import defaultdict, namedtuple try: from future_builtins import filter, map # Python 2.6+ except ImportError: pass # Python 3+ from itertools import islice import os import shutil import subprocess import sys from jinja2 import Environment, FileSystemLoader ARGS_DEFAULT_MAX_IMAGE_SIZE = '1024x1024' ARGS_DEFAULT_MAX_THUMBNAIL_SIZE = '120x120' IMAGE_CAPTION_EXTENSION = '.txt' TEMPLATE_EXTENSION = '.html' OUTPUT_HTML_EXTENSION = '.html' PATH = os.path.dirname(os.path.abspath(__file__)) PATH_STATIC = os.path.join(PATH, 'static') TEMPLATE_ENVIRONMENT = Environment( autoescape=True, loader=FileSystemLoader(os.path.join(PATH, 'templates')), trim_blocks=False) def debug(msg): print(msg) def resize_image(src_filename, dst_filename, max_dimension): """Create a resized (and antialiased) version of an image.""" dimension_str = '%dx%d' % (max_dimension.width, max_dimension.height) cmd = ['convert', '-resize', dimension_str, src_filename, dst_filename] subprocess.check_call(cmd) def render_html_to_file(template_name, context, path, page_name): """Render the template and write the result to the given file.""" context['url_for_page'] = lambda page: page + OUTPUT_HTML_EXTENSION html = render_template(template_name + TEMPLATE_EXTENSION, **context) filename = os.path.join(path, page_name + OUTPUT_HTML_EXTENSION) write_file(filename, html) def render_template(template_filename, **context): return TEMPLATE_ENVIRONMENT \ .get_template(template_filename) \ .render(context) def write_file(filename, content): with codecs.open(filename, 'wb', 'utf-8') as f: debug('Writing "%s" ...' % filename) f.write(content) class Gallery(object): @classmethod def from_args(cls, args): gallery = Gallery() gallery.images = [Image(gallery, image) for image in sorted(args.full_image_filenames)] gallery.link_images() gallery.title = args.title gallery.destination_path = args.destination_path gallery.resize = not args.no_resize gallery.max_image_size = args.max_image_size gallery.max_thumbnail_size = args.max_thumbnail_size return gallery def link_images(self): """Assign the predecessor and successor for every image.""" for previous_image, image, next_image \ in window([None] + self.images + [None], 3): image.previous_image = previous_image image.next_image = next_image def generate(self): # Create destination path if it doesn't exist. if not os.path.exists(self.destination_path): debug('Destination path "%s" does not exist, creating it.' % self.destination_path) os.mkdir(self.destination_path) self.generate_images() for image in self.images: image.load_caption() self.generate_stylesheet() self.render_html_pages() self.copy_additional_static_files() debug('Done.') def generate_images(self): for image in self.images: image.generate_image() image.generate_thumbnail() image.load_caption() def generate_stylesheet(self): filename = os.path.join(self.destination_path, 'style.css') css = render_template('style.css') write_file(filename, css) def render_html_pages(self): for image in self.images: image.render_html_page() self.render_html_index_page() def render_html_index_page(self): """Create an HTML document of thumbnails that link to single image documents. """ context = { 'gallery': self, } render_html_to_file('index', context, self.destination_path, 'index') def copy_additional_static_files(self): if not os.path.exists(PATH_STATIC): debug('Path "%s", does not exist; not copying any static files.' % PATH_STATIC) return filenames = list(sorted(os.listdir(PATH_STATIC))) if not filenames: debug('No static files to copy.') for filename in filenames: debug('Copying static file "%s" ...' % filename) shutil.copy( os.path.join(PATH_STATIC, filename), os.path.join(self.destination_path, filename)) def window(iterable, n): """Return a sliding window of width ``n`` over the iterable.""" it = iter(iterable) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result class Image(object): previous_image = None next_image = None def __init__(self, gallery, full_filename): self.gallery = gallery self.full_filename = full_filename self.path, self.filename = os.path.split(full_filename) self.basename, self.extension = os.path.splitext(self.filename) self.thumbnail_filename = '%s_t%s' % (self.basename, self.extension) self.page_name = self.basename def generate_image(self): """Create a (optionally resized) copy of an image.""" destination_filename = os.path.join(self.gallery.destination_path, self.filename) if self.gallery.resize: # Resize image. debug('Resizing image "%s" ...' % self.full_filename) resize_image( self.full_filename, destination_filename, self.gallery.max_image_size) else: # Copy image. debug('Copying image "%s" ...' % self.full_filename) shutil.copy(self.full_filename, destination_filename) def generate_thumbnail(self): """Create a preview of an image.""" debug('Creating thumbnail "%s" ...' % self.thumbnail_filename) destination_filename = os.path.join(self.gallery.destination_path, self.thumbnail_filename) resize_image( self.full_filename, destination_filename, self.gallery.max_thumbnail_size) def load_caption(self): """Load image caption from file.""" caption_filename = os.path.join( self.path, self.filename + IMAGE_CAPTION_EXTENSION) self.caption = self._read_first_line(caption_filename) def _read_first_line(self, filename): """Read the first line from the specified file.""" try: with codecs.open(filename, 'rb', 'utf-8') as f: return f.next().strip() except IOError: # File does not exist (OK) or cannot be read (not really OK). pass def render_html_page(self): """Create an HTML document for a single image.""" context = { 'image': self, } render_html_to_file('view', context, self.gallery.destination_path, self.page_name) # -------------------------------------------------------------------- # # command line argument parsing Dimension = namedtuple('Dimension', ['width', 'height']) def parse_dimension_arg(value): """Validate a dimension value.""" try: return Dimension(*map(int, value.split('x', 1))) except ValueError: raise argparse.ArgumentTypeError( 'invalid dimension value: %r' % value) def parse_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser( usage='%(prog)s [options] <target path> <image> [image] ...') parser.add_argument( '-c', '--captions', dest='captions', action='store_true', default=False, help='read image captions from text files ("<IMAGE_NAME>.txt")') parser.add_argument( '--no-resize', dest='no_resize', action='store_true', default=False, help='do not resize images, just copy them') parser.add_argument( '-s', '--size', dest='max_image_size', type=Dimension, default=ARGS_DEFAULT_MAX_IMAGE_SIZE, help='set maximum image size [default: %s]' % ARGS_DEFAULT_MAX_IMAGE_SIZE) parser.add_argument( '-t', '--thumbnail-size', dest='max_thumbnail_size', type=Dimension, default=ARGS_DEFAULT_MAX_THUMBNAIL_SIZE, help='set maximum thumbnail size [default: %s]' % ARGS_DEFAULT_MAX_THUMBNAIL_SIZE) parser.add_argument( '--title', dest='title', help='set gallery title on the website') # First positional argument. parser.add_argument('destination_path') # Remaining positional arguments (at least one), as a list. parser.add_argument('full_image_filenames', nargs='+') return parser.parse_args() # -------------------------------------------------------------------- # def handle_duplicate_filenames(paths): duplicates = list(find_duplicate_filenames(paths)) if duplicates: print('Found duplicate filenames:') for filename, paths in duplicates: print(' + "%s" appears in the following paths:' % filename) for path in paths: print(' - ' + path) sys.exit('Clashing target filenames, aborting.') def find_duplicate_filenames(paths): d = defaultdict(list) for path in paths: key = os.path.basename(path).lower() d[key].append(path) return filter(lambda x: len(x[1]) > 1, d.items()) # -------------------------------------------------------------------- # if __name__ == '__main__': try: args = parse_args() handle_duplicate_filenames(args.full_image_filenames) Gallery.from_args(args).generate() except KeyboardInterrupt: sys.exit('Ctrl-C pressed, aborting.')
#!/usr/bin/env python # -*- coding: utf-8 -*- import itertools as it import numpy as np # This is the basis state for the spin nelec=4 j2=1.0 # This is the RATIO j2/j1 (low value high dimerization) n=float(nelec) bc='obc' ms=0 nstate=2 #Number of states to print preket=list(it.product([0.5,-0.5], repeat=nelec)) prebra=list(it.product([1,0], repeat=nelec)) #### Commented on 10/10/2014 print prebra # Convert list of tuples to list of lists welcome = """\ ------------------------------------------------------------------------------- ██╗ ██╗███████╗██╗███████╗███████╗███╗ ██╗██████╗ ███████╗██████╗ ██████╗ ██║ ██║██╔════╝██║██╔════╝██╔════╝████╗ ██║██╔══██╗██╔════╝██╔══██╗██╔════╝ ███████║█████╗ ██║███████╗█████╗ ██╔██╗ ██║██████╔╝█████╗ ██████╔╝██║ ███╗ ██╔══██║██╔══╝ ██║╚════██║██╔══╝ ██║╚██╗██║██╔══██╗██╔══╝ ██╔══██╗██║ ██║ ██║ ██║███████╗██║███████║███████╗██║ ╚████║██████╔╝███████╗██║ ██║╚██████╔╝ ╚═╝ ╚═╝╚══════╝╚═╝╚══════╝╚══════╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ A program to calculate the total position spread tensor using a Heisenberg hamiltonian. This program has been written by Muammar El Khatib and Edoardo Fertitta. ------------------------------------------------------------------------------- """ print (welcome) """ Ms partition """ bra=[] for idx,i in enumerate(preket): if np.sum(i) == ms: bra.append(prebra[idx]) #### Commented on 10/10/2014 print bra brams=[] for i in bra: brams.append(np.sum(i)) #### Commented on 10/10/2014 print brams print ('Heisenberg hamiltonian matrix:') print ('') ovm = np.zeros(shape=(len(bra),len(bra))) #### Commented on 10/10/2014 print bra for idx,i in enumerate(bra): for idy,j in enumerate(bra): if brams[idx] == brams[idy]: diff=np.matrix(i)-np.matrix(j) vectornorm=np.linalg.norm(diff)**2 if int(vectornorm) == 2: # print diff diffn= np.squeeze(np.asarray(diff)) order=np.flatnonzero(diffn) #### Commented on 10/10/2014 print order if bc == 'pbc': if order[1]-order[0] == 1 or order[1]-order[0] == nelec-1: #PBC ovm.itemset((idx,idy),1) else: if order[1]-order[0] == 1: if order[0] % 2== 0: ovm.itemset((idx,idy),1) else: ovm.itemset((idx,idy),j2) """ Define pairs """ def pairs(lst): for i in range(1, len(lst)): yield lst[i-1], lst[i] if bc == 'pbc': yield lst[-1], lst[0] prediagonal=[] expec=[] for idx,j in enumerate(bra): elemd=[] suma=0 for i1, i2 in pairs(j): # print suma, i1, i2 if suma % 2 == 0: r = 1.0 else: r = j2 if i1 == i2: elemd.append(0.5*r) else: elemd.append(-0.5*r) suma=suma+1 prediagonal.append(elemd) for xx in prediagonal: expec.append(np.sum(xx)) #print expec for idd,i in enumerate(prediagonal): j=np.sum(i) #print i, idd, j #print type(i) ovm.itemset((idd,idd),j) print ovm print ('') from scipy import linalg as LA e_vals, e_vecs = LA.eigh(ovm) """ This is let just for debugging reasons. """ #for idx, i in enumerate(e_vals): # print e_vals[idx] # print e_vecs[:,idx] # print '' enumerate(e_vals) np.set_printoptions(precision=8,suppress=True) for state in range(nstate): print ('Results for STATE '+str(state+1)+': ') print ('Eigenvalue= '+ str(e_vals[state])) print ('Corresponding state vector:') print e_vecs[:,state] idxtomatch=np.flatnonzero(e_vecs[:,state]) presumtps=[] for i in idxtomatch: # print bra[i] brarray=np.array(bra[i]) positions=(np.flatnonzero(brarray)).astype(float)-(n-1.)/2. # print positions sq=np.sum(positions)**2 coefsq=e_vecs[:,state][i]**2*sq # print coefsq presumtps.append(coefsq) #print presumtps print ('Λ(αα) contribution = ' + str(np.sum(presumtps))) print ('') #print ('Λ(αα+ββ) contrib = ' + str(np.sum(presumtps))) Header with license added #!/usr/bin/env python # -*- coding: utf-8 -*- """ __author__ = "Muammar El Khatib; Edoardo Fertitta." __copyright__ = "Copyright 2014, Muammar El Khatib; Edoardo Fertitta." __credits__ = [""] __license__ = "GPL" __version__ = "3" __maintainer__ = "Muammar El Khatib" __email__ = "muammarelkhatib@gmail.com" __status__ = "Development" """ import itertools as it import numpy as np # This is the basis state for the spin nelec=4 j2=1.0 # This is the RATIO j2/j1 (low value high dimerization) n=float(nelec) bc='obc' ms=0 nstate=2 #Number of states to print preket=list(it.product([0.5,-0.5], repeat=nelec)) prebra=list(it.product([1,0], repeat=nelec)) #### Commented on 10/10/2014 print prebra # Convert list of tuples to list of lists welcome = """\ ------------------------------------------------------------------------------- ██╗ ██╗███████╗██╗███████╗███████╗███╗ ██╗██████╗ ███████╗██████╗ ██████╗ ██║ ██║██╔════╝██║██╔════╝██╔════╝████╗ ██║██╔══██╗██╔════╝██╔══██╗██╔════╝ ███████║█████╗ ██║███████╗█████╗ ██╔██╗ ██║██████╔╝█████╗ ██████╔╝██║ ███╗ ██╔══██║██╔══╝ ██║╚════██║██╔══╝ ██║╚██╗██║██╔══██╗██╔══╝ ██╔══██╗██║ ██║ ██║ ██║███████╗██║███████║███████╗██║ ╚████║██████╔╝███████╗██║ ██║╚██████╔╝ ╚═╝ ╚═╝╚══════╝╚═╝╚══════╝╚══════╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ A program to calculate the total position spread tensor using a Heisenberg hamiltonian. This program has been written by Muammar El Khatib and Edoardo Fertitta. ------------------------------------------------------------------------------- """ print (welcome) """ Ms partition """ bra=[] for idx,i in enumerate(preket): if np.sum(i) == ms: bra.append(prebra[idx]) #### Commented on 10/10/2014 print bra brams=[] for i in bra: brams.append(np.sum(i)) #### Commented on 10/10/2014 print brams print ('Heisenberg hamiltonian matrix:') print ('') ovm = np.zeros(shape=(len(bra),len(bra))) #### Commented on 10/10/2014 print bra for idx,i in enumerate(bra): for idy,j in enumerate(bra): if brams[idx] == brams[idy]: diff=np.matrix(i)-np.matrix(j) vectornorm=np.linalg.norm(diff)**2 if int(vectornorm) == 2: # print diff diffn= np.squeeze(np.asarray(diff)) order=np.flatnonzero(diffn) #### Commented on 10/10/2014 print order if bc == 'pbc': if order[1]-order[0] == 1 or order[1]-order[0] == nelec-1: #PBC ovm.itemset((idx,idy),1) else: if order[1]-order[0] == 1: if order[0] % 2== 0: ovm.itemset((idx,idy),1) else: ovm.itemset((idx,idy),j2) """ Define pairs """ def pairs(lst): for i in range(1, len(lst)): yield lst[i-1], lst[i] if bc == 'pbc': yield lst[-1], lst[0] prediagonal=[] expec=[] for idx,j in enumerate(bra): elemd=[] suma=0 for i1, i2 in pairs(j): # print suma, i1, i2 if suma % 2 == 0: r = 1.0 else: r = j2 if i1 == i2: elemd.append(0.5*r) else: elemd.append(-0.5*r) suma=suma+1 prediagonal.append(elemd) for xx in prediagonal: expec.append(np.sum(xx)) #print expec for idd,i in enumerate(prediagonal): j=np.sum(i) #print i, idd, j #print type(i) ovm.itemset((idd,idd),j) print ovm print ('') from scipy import linalg as LA e_vals, e_vecs = LA.eigh(ovm) """ This is let just for debugging reasons. """ #for idx, i in enumerate(e_vals): # print e_vals[idx] # print e_vecs[:,idx] # print '' enumerate(e_vals) np.set_printoptions(precision=8,suppress=True) for state in range(nstate): print ('Results for STATE '+str(state+1)+': ') print ('Eigenvalue= '+ str(e_vals[state])) print ('Corresponding state vector:') print e_vecs[:,state] idxtomatch=np.flatnonzero(e_vecs[:,state]) presumtps=[] for i in idxtomatch: # print bra[i] brarray=np.array(bra[i]) positions=(np.flatnonzero(brarray)).astype(float)-(n-1.)/2. # print positions sq=np.sum(positions)**2 coefsq=e_vecs[:,state][i]**2*sq # print coefsq presumtps.append(coefsq) #print presumtps print ('Λ(αα) contribution = ' + str(np.sum(presumtps))) print ('') #print ('Λ(αα+ββ) contrib = ' + str(np.sum(presumtps)))
# -*- coding: utf-8 -*- from django.conf import settings as django_settings import pytz from dateutil import rrule from django.contrib.contenttypes import generic from django.db import models from django.db.models import Q from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.template.defaultfilters import date from django.utils.translation import ugettext, ugettext_lazy as _ from django.utils import timezone from schedule.conf import settings from schedule.models.rules import Rule from schedule.models.calendars import Calendar from schedule.utils import OccurrenceReplacer import cPickle as pickle from schedule.utils import get_boolean class EventManager(models.Manager): def get_for_object(self, content_object, distinction=None, inherit=True): return EventRelation.objects.get_events_for_object(content_object, distinction, inherit) class Event(models.Model): ''' This model stores meta data for a date. You can relate this data to many other models. ''' start = models.DateTimeField(_("start")) end = models.DateTimeField(_("end"), help_text=_("The end time must be later than the start time.")) title = models.CharField(_("title"), max_length=255) description = models.TextField(_("description"), null=True, blank=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, verbose_name=_("creator"), related_name='creator') created_on = models.DateTimeField(_("created on"), auto_now_add=True) updated_on = models.DateTimeField(_("updated on"), auto_now=True) rule = models.ForeignKey(Rule, null=True, blank=True, verbose_name=_("rule"), help_text=_("Select '----' for a one time only event.")) end_recurring_period = models.DateTimeField(_("end recurring period"), null=True, blank=True, help_text=_("This date is ignored for one time only events.")) calendar = models.ForeignKey(Calendar, null=True, blank=True, verbose_name=_("calendar")) objects = EventManager() recent_start = models.TextField(null=True) class Meta: verbose_name = _('event') verbose_name_plural = _('events') app_label = 'schedule' def __unicode__(self): date_format = u'%s' % ugettext("DATE_FORMAT") return ugettext('%(title)s: %(start)s - %(end)s') % { 'title': self.title, 'start': date(self.start, date_format), 'end': date(self.end, date_format), } def get_absolute_url(self): return reverse('event', args=[self.id]) def get_recent_start_validated(self): """ Unserializes and validates self.recent_start. Returns the dictionary represented by self.recent_start if all goes well, or None if there is a validation error. @return recent_start converted to object if it's valid given current state of event; None if it doesn't exist or is invalid. """ if self.recent_start == None: return None recent_start_data = pickle.loads(str(self.recent_start)) if (recent_start_data['event']['start'] == self.start and recent_start_data['event']['rule_id'] == self.rule.pk): return recent_start_data else: return None @property def recent_occurrence_start(self): """ A lazy loaded property that ensures we unpickle to get the recent occurrence start only once. Use similar pattern for other properties :return: """ if not hasattr(self, '_recent_start'): setattr(self, '_recent_start', self.get_recent_start_validated()) recent_start = getattr(self, '_recent_start', None) if (recent_start is not None and 'occurrence' in recent_start and 'start' in recent_start['occurrence']): return recent_start['occurrence']['start'] else: return None def build_recent_start_payload(self, occurrence): """ Builds a payload to store in self.recent_start and returns the result @return string representation of payload representing recent start. """ event_occurrence_data = { 'event': { 'start': self.start, 'rule_id': self.rule.pk }, 'occurrence': { 'start': occurrence.start, 'end': occurrence.end } } event_occurrence_payload = pickle.dumps(event_occurrence_data) return event_occurrence_payload def get_optimized_rrule_object(self, period_start): """ An optimized version of self.get_rrule_object that examines if we have a recent start that was calculated for this event and uses that as the start of the rrule dtstart if it falls earlier than the desired period_start """ if self.rule is not None: params = self.rule.get_params() frequency = self.rule.rrule_frequency() if self.recent_occurrence_start is not None and self.recent_occurrence_start < period_start: # Optimization: use recent_occurrence_start for the rrule object # to calculate occurrences. return rrule.rrule(frequency, dtstart=self.recent_occurrence_start, **params) else: return rrule.rrule(frequency, dtstart=self.start, **params) def get_occurrences(self, start, end, skip_booster=False, persisted_occurrences=None): """ :param persisted_occurrences - In some contexts (such as models post_constraints), we need to ensure that we get the latest set of persisted_occurrences and avoid using the prefetch cache which may be stale. Client code can pass its own persisted_occurrences using the `all().all()` pattern in these cases. >>> rule = Rule(frequency = "MONTHLY", name = "Monthly") >>> rule.save() >>> event = Event(rule=rule, start=datetime.datetime(2008,1,1,tzinfo=pytz.utc), end=datetime.datetime(2008,1,2)) >>> event.rule <Rule: Monthly> >>> occurrences = event.get_occurrences(datetime.datetime(2008,1,24), datetime.datetime(2008,3,2)) >>> ["%s to %s" %(o.start, o.end) for o in occurrences] ['2008-02-01 00:00:00+00:00 to 2008-02-02 00:00:00+00:00', '2008-03-01 00:00:00+00:00 to 2008-03-02 00:00:00+00:00'] Ensure that if an event has no rule, that it appears only once. >>> event = Event(start=datetime.datetime(2008,1,1,8,0), end=datetime.datetime(2008,1,1,9,0)) >>> occurrences = event.get_occurrences(datetime.datetime(2008,1,24), datetime.datetime(2008,3,2)) >>> ["%s to %s" %(o.start, o.end) for o in occurrences] [] """ if self.pk and not skip_booster: # performance booster for occurrences relationship Event.objects.select_related('occurrence').get(pk=self.pk) if persisted_occurrences is None: persisted_occurrences = self.occurrence_set.all() occ_replacer = OccurrenceReplacer(persisted_occurrences) occurrences = self._get_occurrence_list(start, end) final_occurrences = [] for occ in occurrences: # replace occurrences with their persisted counterparts if occ_replacer.has_occurrence(occ): p_occ = occ_replacer.get_occurrence(occ) # ...but only if they are within this period if p_occ.start < end and p_occ.end >= start: final_occurrences.append(p_occ) else: final_occurrences.append(occ) # then add persisted occurrences which originated outside of this period but now # fall within it final_occurrences += occ_replacer.get_additional_occurrences(start, end) return final_occurrences def get_rrule_object(self): if self.rule is not None: params = self.rule.get_params() frequency = self.rule.rrule_frequency() return rrule.rrule(frequency, dtstart=self.start, **params) def _create_occurrence(self, start, end=None): if end is None: end = start + (self.end - self.start) return Occurrence(event=self, start=start, end=end, original_start=start, original_end=end, title=self.title, description=self.description) def get_occurrence(self, date): if timezone.is_naive(date) and django_settings.USE_TZ: date = timezone.make_aware(date, timezone.utc) rule = self.get_rrule_object() if rule: next_occurrence = rule.after(date, inc=True) else: next_occurrence = self.start if next_occurrence == date: try: return Occurrence.objects.get(event=self, original_start=date) except Occurrence.DoesNotExist: return self._create_occurrence(next_occurrence) def _get_occurrence_list(self, start, end): """ returns a list of occurrences for this event from start to end. """ difference = (self.end - self.start) if self.rule is not None: occurrences = [] if self.end_recurring_period and self.end_recurring_period < end: end = self.end_recurring_period rule = None if get_boolean('ENABLE_OPTIMIZED_RRULE_GENERATION', False): rule = self.get_optimized_rrule_object(start-difference) else: rule = self.get_rrule_object() o_starts = rule.between(start-difference, end, inc=True) for o_start in o_starts: o_end = o_start + difference occurrences.append(self._create_occurrence(o_start, o_end)) return occurrences else: # check if event is in the period if self.start < end and self.end > start: return [self._create_occurrence(self.start)] else: return [] def _occurrences_after_generator(self, after=None, tzinfo=pytz.utc): """ returns a generator that produces unpresisted occurrences after the datetime ``after``. """ if after is None: after = timezone.now() rule = self.get_rrule_object() if rule is None: if self.end > after: yield self._create_occurrence(self.start, self.end) raise StopIteration date_iter = iter(rule) difference = self.end - self.start while True: o_start = date_iter.next() if o_start > self.end_recurring_period: raise StopIteration o_end = o_start + difference if o_end > after: yield self._create_occurrence(o_start, o_end) def occurrences_after(self, after=None): """ returns a generator that produces occurrences after the datetime ``after``. Includes all of the persisted Occurrences. """ occ_replacer = OccurrenceReplacer(self.occurrence_set.all()) generator = self._occurrences_after_generator(after) while True: next = generator.next() yield occ_replacer.get_occurrence(next) class EventRelationManager(models.Manager): ''' >>> EventRelation.objects.all().delete() >>> CalendarRelation.objects.all().delete() >>> data = { ... 'title': 'Test1', ... 'start': datetime.datetime(2008, 1, 1), ... 'end': datetime.datetime(2008, 1, 11) ... } >>> Event.objects.all().delete() >>> event1 = Event(**data) >>> event1.save() >>> data['title'] = 'Test2' >>> event2 = Event(**data) >>> event2.save() >>> user1 = User(username='alice') >>> user1.save() >>> user2 = User(username='bob') >>> user2.save() >>> event1.create_relation(user1, 'owner') >>> event1.create_relation(user2, 'viewer') >>> event2.create_relation(user1, 'viewer') ''' # Currently not supported # Multiple level reverse lookups of generic relations appears to be # unsupported in Django, which makes sense. # # def get_objects_for_event(self, event, model, distinction=None): # ''' # returns a queryset full of instances of model, if it has an EventRelation # with event, and distinction # >>> event = Event.objects.get(title='Test1') # >>> EventRelation.objects.get_objects_for_event(event, User, 'owner') # [<User: alice>] # >>> EventRelation.objects.get_objects_for_event(event, User) # [<User: alice>, <User: bob>] # ''' # if distinction: # dist_q = Q(eventrelation__distinction = distinction) # else: # dist_q = Q() # ct = ContentType.objects.get_for_model(model) # return model.objects.filter( # dist_q, # eventrelation__content_type = ct, # eventrelation__event = event # ) def get_events_for_object(self, content_object, distinction=None, inherit=True): ''' returns a queryset full of events, that relate to the object through, the distinction If inherit is false it will not consider the calendars that the events belong to. If inherit is true it will inherit all of the relations and distinctions that any calendar that it belongs to has, as long as the relation has inheritable set to True. (See Calendar) >>> event = Event.objects.get(title='Test1') >>> user = User.objects.get(username = 'alice') >>> EventRelation.objects.get_events_for_object(user, 'owner', inherit=False) [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>] If a distinction is not declared it will not vet the relations based on distinction. >>> EventRelation.objects.get_events_for_object(user, inherit=False) [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>, <Event: Test2: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>] Now if there is a Calendar >>> calendar = Calendar(name = 'MyProject') >>> calendar.save() And an event that belongs to that calendar >>> event = Event.objects.get(title='Test2') >>> calendar.events.add(event) If we relate this calendar to some object with inheritable set to true, that relation will be inherited >>> user = User.objects.get(username='bob') >>> cr = calendar.create_relation(user, 'viewer', True) >>> EventRelation.objects.get_events_for_object(user, 'viewer') [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>, <Event: Test2: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>] ''' ct = ContentType.objects.get_for_model(type(content_object)) if distinction: dist_q = Q(eventrelation__distinction=distinction) cal_dist_q = Q(calendar__calendarrelation__distinction=distinction) else: dist_q = Q() cal_dist_q = Q() if inherit: inherit_q = Q( cal_dist_q, calendar__calendarrelation__object_id=content_object.id, calendar__calendarrelation__content_type=ct, calendar__calendarrelation__inheritable=True, ) else: inherit_q = Q() event_q = Q(dist_q, Q(eventrelation__object_id=content_object.id), Q(eventrelation__content_type=ct)) return Event.objects.filter(inherit_q | event_q) def create_relation(self, event, content_object, distinction=None): """ Creates a relation between event and content_object. See EventRelation for help on distinction. """ ct = ContentType.objects.get_for_model(type(content_object)) object_id = content_object.id er = EventRelation( content_type=ct, object_id=object_id, event=event, distinction=distinction, content_object=content_object ) er.save() return er class EventRelation(models.Model): ''' This is for relating data to an Event, there is also a distinction, so that data can be related in different ways. A good example would be, if you have events that are only visible by certain users, you could create a relation between events and users, with the distinction of 'visibility', or 'ownership'. event: a foreign key relation to an Event model. content_type: a foreign key relation to ContentType of the generic object object_id: the id of the generic object content_object: the generic foreign key to the generic object distinction: a string representing a distinction of the relation, User could have a 'veiwer' relation and an 'owner' relation for example. DISCLAIMER: while this model is a nice out of the box feature to have, it may not scale well. If you use this keep that in mindself. ''' event = models.ForeignKey(Event, verbose_name=_("event")) content_type = models.ForeignKey(ContentType) object_id = models.IntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') distinction = models.CharField(_("distinction"), max_length=20, null=True) objects = EventRelationManager() class Meta: verbose_name = _("event relation") verbose_name_plural = _("event relations") app_label = 'schedule' def __unicode__(self): return u'%s(%s)-%s' % (self.event.title, self.distinction, self.content_object) class Occurrence(models.Model): event = models.ForeignKey(Event, verbose_name=_("event")) title = models.CharField(_("title"), max_length=255, blank=True, null=True) description = models.TextField(_("description"), blank=True, null=True) start = models.DateTimeField(_("start")) end = models.DateTimeField(_("end")) cancelled = models.BooleanField(_("cancelled"), default=False) original_start = models.DateTimeField(_("original start")) original_end = models.DateTimeField(_("original end")) created_on = models.DateTimeField(_("created on"), auto_now_add=True) updated_on = models.DateTimeField(_("updated on"), auto_now=True) class Meta: verbose_name = _("occurrence") verbose_name_plural = _("occurrences") app_label = 'schedule' def moved(self): return self.original_start != self.start or self.original_end != self.end moved = property(moved) def move(self, new_start, new_end): self.start = new_start self.end = new_end self.save() def cancel(self): self.cancelled = True self.save() def uncancel(self): self.cancelled = False self.save() def get_absolute_url(self): if self.pk is not None: return reverse('occurrence', kwargs={'occurrence_id': self.pk, 'event_id': self.event.id}) return reverse('occurrence_by_date', kwargs={ 'event_id': self.event.id, 'year': self.start.year, 'month': self.start.month, 'day': self.start.day, 'hour': self.start.hour, 'minute': self.start.minute, 'second': self.start.second, }) def get_cancel_url(self): if self.pk is not None: return reverse('cancel_occurrence', kwargs={'occurrence_id': self.pk, 'event_id': self.event.id}) return reverse('cancel_occurrence_by_date', kwargs={ 'event_id': self.event.id, 'year': self.start.year, 'month': self.start.month, 'day': self.start.day, 'hour': self.start.hour, 'minute': self.start.minute, 'second': self.start.second, }) def get_edit_url(self): if self.pk is not None: return reverse('edit_occurrence', kwargs={'occurrence_id': self.pk, 'event_id': self.event.id}) return reverse('edit_occurrence_by_date', kwargs={ 'event_id': self.event.id, 'year': self.start.year, 'month': self.start.month, 'day': self.start.day, 'hour': self.start.hour, 'minute': self.start.minute, 'second': self.start.second, }) def __unicode__(self): return ugettext("%(start)s to %(end)s") % { 'start': self.start, 'end': self.end, } def __cmp__(self, other): rank = cmp(self.start, other.start) if rank == 0: return cmp(self.end, other.end) return rank def __eq__(self, other): return (isinstance(other, Occurrence) and self.original_start == other.original_start and self.original_end == other.original_end) inclusive events # -*- coding: utf-8 -*- from django.conf import settings as django_settings import pytz from dateutil import rrule from django.contrib.contenttypes import generic from django.db import models from django.db.models import Q from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.template.defaultfilters import date from django.utils.translation import ugettext, ugettext_lazy as _ from django.utils import timezone from schedule.conf import settings from schedule.models.rules import Rule from schedule.models.calendars import Calendar from schedule.utils import OccurrenceReplacer import cPickle as pickle from schedule.utils import get_boolean class EventManager(models.Manager): def get_for_object(self, content_object, distinction=None, inherit=True): return EventRelation.objects.get_events_for_object(content_object, distinction, inherit) class Event(models.Model): ''' This model stores meta data for a date. You can relate this data to many other models. ''' start = models.DateTimeField(_("start")) end = models.DateTimeField(_("end"), help_text=_("The end time must be later than the start time.")) title = models.CharField(_("title"), max_length=255) description = models.TextField(_("description"), null=True, blank=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, verbose_name=_("creator"), related_name='creator') created_on = models.DateTimeField(_("created on"), auto_now_add=True) updated_on = models.DateTimeField(_("updated on"), auto_now=True) rule = models.ForeignKey(Rule, null=True, blank=True, verbose_name=_("rule"), help_text=_("Select '----' for a one time only event.")) end_recurring_period = models.DateTimeField(_("end recurring period"), null=True, blank=True, help_text=_("This date is ignored for one time only events.")) calendar = models.ForeignKey(Calendar, null=True, blank=True, verbose_name=_("calendar")) objects = EventManager() recent_start = models.TextField(null=True) class Meta: verbose_name = _('event') verbose_name_plural = _('events') app_label = 'schedule' def __unicode__(self): date_format = u'%s' % ugettext("DATE_FORMAT") return ugettext('%(title)s: %(start)s - %(end)s') % { 'title': self.title, 'start': date(self.start, date_format), 'end': date(self.end, date_format), } def get_absolute_url(self): return reverse('event', args=[self.id]) def get_recent_start_validated(self): """ Unserializes and validates self.recent_start. Returns the dictionary represented by self.recent_start if all goes well, or None if there is a validation error. @return recent_start converted to object if it's valid given current state of event; None if it doesn't exist or is invalid. """ if self.recent_start == None: return None recent_start_data = pickle.loads(str(self.recent_start)) if (recent_start_data['event']['start'] == self.start and recent_start_data['event']['rule_id'] == self.rule.pk): return recent_start_data else: return None @property def recent_occurrence_start(self): """ A lazy loaded property that ensures we unpickle to get the recent occurrence start only once. Use similar pattern for other properties :return: """ if not hasattr(self, '_recent_start'): setattr(self, '_recent_start', self.get_recent_start_validated()) recent_start = getattr(self, '_recent_start', None) if (recent_start is not None and 'occurrence' in recent_start and 'start' in recent_start['occurrence']): return recent_start['occurrence']['start'] else: return None def build_recent_start_payload(self, occurrence): """ Builds a payload to store in self.recent_start and returns the result @return string representation of payload representing recent start. """ event_occurrence_data = { 'event': { 'start': self.start, 'rule_id': self.rule.pk }, 'occurrence': { 'start': occurrence.start, 'end': occurrence.end } } event_occurrence_payload = pickle.dumps(event_occurrence_data) return event_occurrence_payload def get_optimized_rrule_object(self, period_start): """ An optimized version of self.get_rrule_object that examines if we have a recent start that was calculated for this event and uses that as the start of the rrule dtstart if it falls earlier than the desired period_start """ if self.rule is not None: params = self.rule.get_params() frequency = self.rule.rrule_frequency() if self.recent_occurrence_start is not None and self.recent_occurrence_start < period_start: # Optimization: use recent_occurrence_start for the rrule object # to calculate occurrences. return rrule.rrule(frequency, dtstart=self.recent_occurrence_start, **params) else: return rrule.rrule(frequency, dtstart=self.start, **params) def get_occurrences(self, start, end, skip_booster=False, persisted_occurrences=None): """ :param persisted_occurrences - In some contexts (such as models post_constraints), we need to ensure that we get the latest set of persisted_occurrences and avoid using the prefetch cache which may be stale. Client code can pass its own persisted_occurrences using the `all().all()` pattern in these cases. >>> rule = Rule(frequency = "MONTHLY", name = "Monthly") >>> rule.save() >>> event = Event(rule=rule, start=datetime.datetime(2008,1,1,tzinfo=pytz.utc), end=datetime.datetime(2008,1,2)) >>> event.rule <Rule: Monthly> >>> occurrences = event.get_occurrences(datetime.datetime(2008,1,24), datetime.datetime(2008,3,2)) >>> ["%s to %s" %(o.start, o.end) for o in occurrences] ['2008-02-01 00:00:00+00:00 to 2008-02-02 00:00:00+00:00', '2008-03-01 00:00:00+00:00 to 2008-03-02 00:00:00+00:00'] Ensure that if an event has no rule, that it appears only once. >>> event = Event(start=datetime.datetime(2008,1,1,8,0), end=datetime.datetime(2008,1,1,9,0)) >>> occurrences = event.get_occurrences(datetime.datetime(2008,1,24), datetime.datetime(2008,3,2)) >>> ["%s to %s" %(o.start, o.end) for o in occurrences] [] """ if self.pk and not skip_booster: # performance booster for occurrences relationship Event.objects.select_related('occurrence').get(pk=self.pk) if persisted_occurrences is None: persisted_occurrences = self.occurrence_set.all() occ_replacer = OccurrenceReplacer(persisted_occurrences) occurrences = self._get_occurrence_list(start, end) final_occurrences = [] for occ in occurrences: # replace occurrences with their persisted counterparts if occ_replacer.has_occurrence(occ): p_occ = occ_replacer.get_occurrence(occ) # ...but only if they are within this period if p_occ.start <= end and p_occ.end >= start: final_occurrences.append(p_occ) else: final_occurrences.append(occ) # then add persisted occurrences which originated outside of this period but now # fall within it final_occurrences += occ_replacer.get_additional_occurrences(start, end) return final_occurrences def get_rrule_object(self): if self.rule is not None: params = self.rule.get_params() frequency = self.rule.rrule_frequency() return rrule.rrule(frequency, dtstart=self.start, **params) def _create_occurrence(self, start, end=None): if end is None: end = start + (self.end - self.start) return Occurrence(event=self, start=start, end=end, original_start=start, original_end=end, title=self.title, description=self.description) def get_occurrence(self, date): if timezone.is_naive(date) and django_settings.USE_TZ: date = timezone.make_aware(date, timezone.utc) rule = self.get_rrule_object() if rule: next_occurrence = rule.after(date, inc=True) else: next_occurrence = self.start if next_occurrence == date: try: return Occurrence.objects.get(event=self, original_start=date) except Occurrence.DoesNotExist: return self._create_occurrence(next_occurrence) def _get_occurrence_list(self, start, end): """ returns a list of occurrences for this event from start to end. """ difference = (self.end - self.start) if self.rule is not None: occurrences = [] if self.end_recurring_period and self.end_recurring_period < end: end = self.end_recurring_period rule = None if get_boolean('ENABLE_OPTIMIZED_RRULE_GENERATION', False): rule = self.get_optimized_rrule_object(start-difference) else: rule = self.get_rrule_object() o_starts = rule.between(start-difference, end, inc=True) for o_start in o_starts: o_end = o_start + difference occurrences.append(self._create_occurrence(o_start, o_end)) return occurrences else: # check if event is in the period if self.start <= end and self.end >= start: return [self._create_occurrence(self.start)] else: return [] def _occurrences_after_generator(self, after=None, tzinfo=pytz.utc): """ returns a generator that produces unpresisted occurrences after the datetime ``after``. """ if after is None: after = timezone.now() rule = self.get_rrule_object() if rule is None: if self.end > after: yield self._create_occurrence(self.start, self.end) raise StopIteration date_iter = iter(rule) difference = self.end - self.start while True: o_start = date_iter.next() if o_start > self.end_recurring_period: raise StopIteration o_end = o_start + difference if o_end > after: yield self._create_occurrence(o_start, o_end) def occurrences_after(self, after=None): """ returns a generator that produces occurrences after the datetime ``after``. Includes all of the persisted Occurrences. """ occ_replacer = OccurrenceReplacer(self.occurrence_set.all()) generator = self._occurrences_after_generator(after) while True: next = generator.next() yield occ_replacer.get_occurrence(next) class EventRelationManager(models.Manager): ''' >>> EventRelation.objects.all().delete() >>> CalendarRelation.objects.all().delete() >>> data = { ... 'title': 'Test1', ... 'start': datetime.datetime(2008, 1, 1), ... 'end': datetime.datetime(2008, 1, 11) ... } >>> Event.objects.all().delete() >>> event1 = Event(**data) >>> event1.save() >>> data['title'] = 'Test2' >>> event2 = Event(**data) >>> event2.save() >>> user1 = User(username='alice') >>> user1.save() >>> user2 = User(username='bob') >>> user2.save() >>> event1.create_relation(user1, 'owner') >>> event1.create_relation(user2, 'viewer') >>> event2.create_relation(user1, 'viewer') ''' # Currently not supported # Multiple level reverse lookups of generic relations appears to be # unsupported in Django, which makes sense. # # def get_objects_for_event(self, event, model, distinction=None): # ''' # returns a queryset full of instances of model, if it has an EventRelation # with event, and distinction # >>> event = Event.objects.get(title='Test1') # >>> EventRelation.objects.get_objects_for_event(event, User, 'owner') # [<User: alice>] # >>> EventRelation.objects.get_objects_for_event(event, User) # [<User: alice>, <User: bob>] # ''' # if distinction: # dist_q = Q(eventrelation__distinction = distinction) # else: # dist_q = Q() # ct = ContentType.objects.get_for_model(model) # return model.objects.filter( # dist_q, # eventrelation__content_type = ct, # eventrelation__event = event # ) def get_events_for_object(self, content_object, distinction=None, inherit=True): ''' returns a queryset full of events, that relate to the object through, the distinction If inherit is false it will not consider the calendars that the events belong to. If inherit is true it will inherit all of the relations and distinctions that any calendar that it belongs to has, as long as the relation has inheritable set to True. (See Calendar) >>> event = Event.objects.get(title='Test1') >>> user = User.objects.get(username = 'alice') >>> EventRelation.objects.get_events_for_object(user, 'owner', inherit=False) [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>] If a distinction is not declared it will not vet the relations based on distinction. >>> EventRelation.objects.get_events_for_object(user, inherit=False) [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>, <Event: Test2: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>] Now if there is a Calendar >>> calendar = Calendar(name = 'MyProject') >>> calendar.save() And an event that belongs to that calendar >>> event = Event.objects.get(title='Test2') >>> calendar.events.add(event) If we relate this calendar to some object with inheritable set to true, that relation will be inherited >>> user = User.objects.get(username='bob') >>> cr = calendar.create_relation(user, 'viewer', True) >>> EventRelation.objects.get_events_for_object(user, 'viewer') [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>, <Event: Test2: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>] ''' ct = ContentType.objects.get_for_model(type(content_object)) if distinction: dist_q = Q(eventrelation__distinction=distinction) cal_dist_q = Q(calendar__calendarrelation__distinction=distinction) else: dist_q = Q() cal_dist_q = Q() if inherit: inherit_q = Q( cal_dist_q, calendar__calendarrelation__object_id=content_object.id, calendar__calendarrelation__content_type=ct, calendar__calendarrelation__inheritable=True, ) else: inherit_q = Q() event_q = Q(dist_q, Q(eventrelation__object_id=content_object.id), Q(eventrelation__content_type=ct)) return Event.objects.filter(inherit_q | event_q) def create_relation(self, event, content_object, distinction=None): """ Creates a relation between event and content_object. See EventRelation for help on distinction. """ ct = ContentType.objects.get_for_model(type(content_object)) object_id = content_object.id er = EventRelation( content_type=ct, object_id=object_id, event=event, distinction=distinction, content_object=content_object ) er.save() return er class EventRelation(models.Model): ''' This is for relating data to an Event, there is also a distinction, so that data can be related in different ways. A good example would be, if you have events that are only visible by certain users, you could create a relation between events and users, with the distinction of 'visibility', or 'ownership'. event: a foreign key relation to an Event model. content_type: a foreign key relation to ContentType of the generic object object_id: the id of the generic object content_object: the generic foreign key to the generic object distinction: a string representing a distinction of the relation, User could have a 'veiwer' relation and an 'owner' relation for example. DISCLAIMER: while this model is a nice out of the box feature to have, it may not scale well. If you use this keep that in mindself. ''' event = models.ForeignKey(Event, verbose_name=_("event")) content_type = models.ForeignKey(ContentType) object_id = models.IntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') distinction = models.CharField(_("distinction"), max_length=20, null=True) objects = EventRelationManager() class Meta: verbose_name = _("event relation") verbose_name_plural = _("event relations") app_label = 'schedule' def __unicode__(self): return u'%s(%s)-%s' % (self.event.title, self.distinction, self.content_object) class Occurrence(models.Model): event = models.ForeignKey(Event, verbose_name=_("event")) title = models.CharField(_("title"), max_length=255, blank=True, null=True) description = models.TextField(_("description"), blank=True, null=True) start = models.DateTimeField(_("start")) end = models.DateTimeField(_("end")) cancelled = models.BooleanField(_("cancelled"), default=False) original_start = models.DateTimeField(_("original start")) original_end = models.DateTimeField(_("original end")) created_on = models.DateTimeField(_("created on"), auto_now_add=True) updated_on = models.DateTimeField(_("updated on"), auto_now=True) class Meta: verbose_name = _("occurrence") verbose_name_plural = _("occurrences") app_label = 'schedule' def moved(self): return self.original_start != self.start or self.original_end != self.end moved = property(moved) def move(self, new_start, new_end): self.start = new_start self.end = new_end self.save() def cancel(self): self.cancelled = True self.save() def uncancel(self): self.cancelled = False self.save() def get_absolute_url(self): if self.pk is not None: return reverse('occurrence', kwargs={'occurrence_id': self.pk, 'event_id': self.event.id}) return reverse('occurrence_by_date', kwargs={ 'event_id': self.event.id, 'year': self.start.year, 'month': self.start.month, 'day': self.start.day, 'hour': self.start.hour, 'minute': self.start.minute, 'second': self.start.second, }) def get_cancel_url(self): if self.pk is not None: return reverse('cancel_occurrence', kwargs={'occurrence_id': self.pk, 'event_id': self.event.id}) return reverse('cancel_occurrence_by_date', kwargs={ 'event_id': self.event.id, 'year': self.start.year, 'month': self.start.month, 'day': self.start.day, 'hour': self.start.hour, 'minute': self.start.minute, 'second': self.start.second, }) def get_edit_url(self): if self.pk is not None: return reverse('edit_occurrence', kwargs={'occurrence_id': self.pk, 'event_id': self.event.id}) return reverse('edit_occurrence_by_date', kwargs={ 'event_id': self.event.id, 'year': self.start.year, 'month': self.start.month, 'day': self.start.day, 'hour': self.start.hour, 'minute': self.start.minute, 'second': self.start.second, }) def __unicode__(self): return ugettext("%(start)s to %(end)s") % { 'start': self.start, 'end': self.end, } def __cmp__(self, other): rank = cmp(self.start, other.start) if rank == 0: return cmp(self.end, other.end) return rank def __eq__(self, other): return (isinstance(other, Occurrence) and self.original_start == other.original_start and self.original_end == other.original_end)
import http.client import json from cis.libs import exceptions try: from urllib import quote # Python 2.X except ImportError: from urllib.parse import quote # Python 3+ class Person(object): """Retrieve data from person api as needed.""" def __init__(self, person_api_config): """ :param person_api_config, a dictionary of configuration information about how to connect to person_api """ # Audience is either https://person-api.sso.mozilla.com or https://person-api.sso.allizom.org self.audience = person_api_config.get('audience') self.client_id = person_api_config.get('client_id') self.client_secret = person_api_config.get('client_secret') self.oauth2_domain = person_api_config.get('oauth2_domain') self.person_api_url = person_api_config.get('person_api_url') self.person_api_version = person_api_config.get('person_api_version') def get_bearer(self): conn = http.client.HTTPSConnection(self.oauth2_domain) payload = json.dumps( { 'client_id': self.client_id, 'client_secret': self.client_secret, 'audience': self.audience, 'grant_type': 'client_credentials' } ) headers = {'content-type': "application/json"} conn.request("POST", "/oauth/token", payload, headers) res = conn.getresponse() if res.status == '200': data = res.read() return json.loads(data.decode('utf-8')) else: logger.error('Status of API request was: {}'.format(res.status)) raise exceptions.AuthZeroUnavailable() def get_userinfo(self, auth_zero_id): user_id = quote(auth_zero_id) conn = http.client.HTTPSConnection("{}".format(self.person_api_url)) token = "Bearer {}".format(self.get_bearer().get('access_token')) headers = {'authorization': token} api_route = "/{version}/profile/{user_id}".format( version=self.person_api_version, user_id=user_id ) conn.request("GET", api_route, headers=headers) res = conn.getresponse() if res.status == '200': data = res.read() return json.loads(json.loads(data.decode('utf-8')).get('body')) else: logger.error('Status of API request was: {}'.format(res.status)) return None fix logger error import http.client import json import logging from cis.libs import exceptions try: from urllib import quote # Python 2.X except ImportError: from urllib.parse import quote # Python 3+ logger = logging.getLogger(__name__) class Person(object): """Retrieve data from person api as needed.""" def __init__(self, person_api_config): """ :param person_api_config, a dictionary of configuration information about how to connect to person_api """ # Audience is either https://person-api.sso.mozilla.com or https://person-api.sso.allizom.org self.audience = person_api_config.get('audience') self.client_id = person_api_config.get('client_id') self.client_secret = person_api_config.get('client_secret') self.oauth2_domain = person_api_config.get('oauth2_domain') self.person_api_url = person_api_config.get('person_api_url') self.person_api_version = person_api_config.get('person_api_version') def get_bearer(self): conn = http.client.HTTPSConnection(self.oauth2_domain) payload = json.dumps( { 'client_id': self.client_id, 'client_secret': self.client_secret, 'audience': self.audience, 'grant_type': 'client_credentials' } ) headers = {'content-type': "application/json"} conn.request("POST", "/oauth/token", payload, headers) res = conn.getresponse() if res.status == '200': data = res.read() return json.loads(data.decode('utf-8')) else: logger.error('Status of API request was: {}'.format(res.status)) raise exceptions.AuthZeroUnavailable() def get_userinfo(self, auth_zero_id): user_id = quote(auth_zero_id) conn = http.client.HTTPSConnection("{}".format(self.person_api_url)) token = "Bearer {}".format(self.get_bearer().get('access_token')) headers = {'authorization': token} api_route = "/{version}/profile/{user_id}".format( version=self.person_api_version, user_id=user_id ) conn.request("GET", api_route, headers=headers) res = conn.getresponse() if res.status == '200': data = res.read() return json.loads(json.loads(data.decode('utf-8')).get('body')) else: logger.error('Status of API request was: {}'.format(res.status)) return None
""" flow_direction_over_flat.py Implementation of Barnes et al.(2014) Created by JL, Oct 2015 """ import numpy as np import Queue from collections import deque import landlab from landlab import Component, FieldError from landlab.grid.base import BAD_INDEX_VALUE from landlab.components.flow_routing.flow_direction_DN import grid_flow_directions class FlowRouterOverFlat(Component): def __init__(self, input_grid): self._grid = input_grid self._n = self._grid.number_of_nodes (self._boundary, ) = np.where(self._grid.status_at_node!=0) (self._open_boundary, ) = np.where(np.logical_or(self._grid.status_at_node==1, self._grid.status_at_node==2)) (self._close_boundary, ) = np.where(self._grid.status_at_node==4) #self._neighbors = np.concatenate((self._grid.neighbors_at_node, self._grid.diagonals_at_node), axis=1) #self._neighbors[self._neighbors == BAD_INDEX_VALUE] = -1 self._build_neighbors_list() def _build_neighbors_list(self): (nrows, ncols) = self._grid.shape neighbor_dR = np.array([0, 0, 1, -1, 1, 1, -1, -1]) neighbor_dC = np.array([1, -1, 0, 0, 1, -1, 1, -1]) self._neighbors = np.zeros(shape=(self._n, 8), dtype=int) self._neighbors[self._neighbors==0] = -1 for node in range(self._n): r = self._grid.node_y[node]/self._grid.dx c = self._grid.node_x[node]/self._grid.dx for i in range(8): neighbor_r = r+neighbor_dR[i] neighbor_c = c+neighbor_dC[i] if neighbor_r<0 or neighbor_c<0 or neighbor_r>=nrows or neighbor_c>=ncols: continue self._neighbors[node][i] = neighbor_r*ncols+neighbor_c def route_flow(self, receiver, dem='topographic__elevation'): #main self._dem = self._grid['node'][dem] """ if receiver==None: self._flow_receiver = self._flow_dirs_d8(self._dem) else: self._flow_receiver = receiver """ self._flow_receiver = receiver #(self._flow_receiver, ss) = grid_flow_directions(self._grid, self._dem) flat_mask, labels = self._resolve_flats() #pdb.set_trace() self._flow_receiver = self._flow_dirs_over_flat_d8(flat_mask, labels) #a, q, s = flow_accum_bw.flow_accumulation(self._flow_receiver, self._open_boundary, node_cell_area=self._grid.forced_cell_areas) #self._grid['node']['flow_receiver'] = self._flow_receiver return self._flow_receiver def _resolve_flats(self): is_flat = np.zeros(self._n, dtype=bool) node_id = np.arange(self._n, dtype=int) (sink, ) = np.where(node_id==self._flow_receiver) for node in sink: if node in self._close_boundary: continue if not(is_flat[node]): is_flat = self._identify_flats(is_flat, node) high_edges, low_edges = self._flat_edges(is_flat) labels = np.zeros(self._n, dtype='int') labelid = 1 for node in low_edges.queue: if labels[node]==0: labels = self._label_flats(labels, node, labelid) labelid += 1 flat_mask = np.zeros(self._n, dtype='float') flat_height = np.zeros(labelid, dtype='float') #this part is bottleneck flat_mask, flat_height = self._away_from_higher(flat_mask, labels, flat_height, high_edges) flat_mask, flat_height = self._towards_lower(flat_mask, labels, flat_height, low_edges) return flat_mask, labels def _identify_flats(self, is_flat, node): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary dem = self._dem ''' to_fill = Queue.Queue(maxsize=self._n*2) to_fill_put = to_fill.put to_fill_get = to_fill.get to_fill_empty = to_fill.empty ''' to_fill = deque(maxlen=self._n*2) to_fill_put = to_fill.append to_fill_get = to_fill.popleft closed = np.zeros(self._n, dtype=bool) closed[node] = True to_fill_put(node) elev = dem[node] while not(len(to_fill)==0): node = to_fill_get() if is_flat[node]: continue is_flat[node] = True for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if dem[neighbor_node]!=elev: continue if neighbor_node in boundary: continue if is_flat[neighbor_node] or closed[neighbor_node]: continue closed[neighbor_node] = True to_fill_put(neighbor_node) return is_flat def _flat_edges(self, is_flat): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary open_boundary = self._open_boundary close_boundary = self._close_boundary dem = self._dem ''' low_edges = Queue.Queue(maxsize=self._n*2) high_edges = Queue.Queue(maxsize=self._n*2) high_put = high_edges.put low_put = low_edges.put ''' low_edges = deque(maxlen=self._n*2) high_edges = deque(maxlen=self._n*2) high_put = high_edges.append low_put = low_edges.append for node in range(self._n): if node in boundary: continue if not(is_flat[node]): continue for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if neighbor_node in boundary: if flow_receiver[node]==node and (neighbor_node in close_boundary): high_put(node) break continue if flow_receiver[node]!=node and flow_receiver[neighbor_node]==neighbor_node and dem[node]==dem[neighbor_node]: low_put(node) break elif flow_receiver[node]==node and dem[node]<dem[neighbor_node]: high_put(node) break return high_edges, low_edges def _label_flats(self, labels, node, labelid): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary dem = self._dem ''' to_fill = Queue.Queue(maxsize=self._n*2) to_fill_put = to_fill.put to_fill_get = to_fill.get to_fill_empty = to_fill.empty ''' to_fill = deque(maxlen=self._n*2) to_fill_put = to_fill.append to_fill_get = to_fill.popleft closed = np.zeros(self._n, dtype=bool) closed[node] = True to_fill_put(node) elev = dem[node] while not(len(to_fill)==0): node = to_fill_get() if labels[node]!=0: continue labels[node] = labelid for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if neighbor_node in boundary: continue if dem[neighbor_node]!=elev: continue if labels[neighbor_node]!=0 or closed[neighbor_node]: continue closed[neighbor_node] = True to_fill_put(neighbor_node) return labels def _away_from_higher(self, flat_mask, labels, flat_height, high_edges): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary k = 1 MARKER = -100 ''' high_put = high_edges.put high_get = high_edges.get high_qsize = high_edges.qsize ''' high_put = high_edges.append high_get = high_edges.popleft closed = np.zeros(self._n, dtype=bool) #closed[high_edges.queue] = True for i in high_edges: closed[i] = True high_put(MARKER) while len(high_edges)>1: node = high_get() if node==MARKER: k += 1 high_put(MARKER) continue if flat_mask[node]>0: continue flat_mask[node] = k flat_height[labels[node]] = k for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if neighbor_node in boundary: continue if flat_mask[neighbor_node]>0: continue if closed[neighbor_node]: continue if labels[neighbor_node]==labels[node] and flow_receiver[neighbor_node]==neighbor_node: closed[neighbor_node] = True high_put(neighbor_node) return flat_mask, flat_height def _towards_lower(self, flat_mask, labels, flat_height, low_edges): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary flat_mask = 0-flat_mask k = 1 MARKER = -100 ''' low_put = low_edges.put low_get = low_edges.get low_qsize = low_edges.qsize low_queue = low_edges.queue ''' low_put = low_edges.append low_get = low_edges.popleft closed = np.zeros(self._n, dtype=bool) #closed[low_edges.queue] = True for i in low_edges: closed[i] = True low_put(MARKER) while len(low_edges)>1: node = low_get() if node==MARKER: k += 1 low_put(MARKER) continue if flat_mask[node]>0: continue if flat_mask[node]<0: flat_mask[node] = flat_height[labels[node]]+flat_mask[node]+2*k else: flat_mask[node] = 2*k for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if neighbor_node in boundary: continue if flat_mask[neighbor_node]>0: continue if closed[neighbor_node]: continue if labels[neighbor_node]==labels[node] and flow_receiver[neighbor_node]==neighbor_node: closed[neighbor_node] = True low_put(neighbor_node) return flat_mask, flat_height def _flow_dirs_d8(self, dem): flow_receiver = np.arange(self._n) for node in range(self._n): if node in self._boundary: continue min_elev = dem[node] receiver = node for neighbor_node in self._neighbors[node]: if neighbor_node==-1: continue if neighbor_node in self._open_boundary: receiver = neighbor_node break if neighbor_node in self._close_boundary: continue if dem[neighbor_node]<min_elev: min_elev = dem[neighbor_node] receiver = neighbor_node flow_receiver[node] = receiver return flow_receiver def _flow_dirs_over_flat_d8(self, flat_mask, labels): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary for node in range(self._n): if flow_receiver[node]!=node: continue if node in boundary: continue """ min_elev = flat_mask[node] receiver = node for neighbor_node in self._neighbors[node]: if neighbor_node==-1: continue if labels[neighbor_node]!=labels[node]: continue if flat_mask[neighbor_node]<min_elev: min_elev = flat_mask[neighbor_node] receiver = neighbor_node """ potential_receiver = neighbors[node] potential_receiver = potential_receiver[np.where(potential_receiver!=-1)] potential_receiver = potential_receiver[np.where(labels[potential_receiver]==labels[node])] receiver = potential_receiver[np.argmin(flat_mask[potential_receiver])] flow_receiver[node] = receiver return flow_receiver debug """ flow_direction_over_flat.py Implementation of Barnes et al.(2014) Created by JL, Oct 2015 """ import numpy as np import Queue from collections import deque import landlab from landlab import Component, FieldError from landlab.grid.base import BAD_INDEX_VALUE from landlab.components.flow_routing.flow_direction_DN import grid_flow_directions class FlowRouterOverFlat(Component): def __init__(self, input_grid): self._grid = input_grid self._n = self._grid.number_of_nodes (self._boundary, ) = np.where(self._grid.status_at_node!=0) (self._open_boundary, ) = np.where(np.logical_or(self._grid.status_at_node==1, self._grid.status_at_node==2)) (self._close_boundary, ) = np.where(self._grid.status_at_node==4) #self._neighbors = np.concatenate((self._grid.neighbors_at_node, self._grid.diagonals_at_node), axis=1) #self._neighbors[self._neighbors == BAD_INDEX_VALUE] = -1 self._build_neighbors_list() def _build_neighbors_list(self): (nrows, ncols) = self._grid.shape neighbor_dR = np.array([0, 0, 1, -1, 1, 1, -1, -1]) neighbor_dC = np.array([1, -1, 0, 0, 1, -1, 1, -1]) self._neighbors = np.zeros(shape=(self._n, 8), dtype=int) self._neighbors[self._neighbors==0] = -1 for node in range(self._n): r = self._grid.node_y[node]/self._grid.dx c = self._grid.node_x[node]/self._grid.dx for i in range(8): neighbor_r = r+neighbor_dR[i] neighbor_c = c+neighbor_dC[i] if neighbor_r<0 or neighbor_c<0 or neighbor_r>=nrows or neighbor_c>=ncols: continue self._neighbors[node][i] = neighbor_r*ncols+neighbor_c def route_flow(self, receiver, dem='topographic__elevation'): #main self._dem = self._grid['node'][dem] """ if receiver==None: self._flow_receiver = self._flow_dirs_d8(self._dem) else: self._flow_receiver = receiver """ self._flow_receiver = receiver #(self._flow_receiver, ss) = grid_flow_directions(self._grid, self._dem) flat_mask, labels = self._resolve_flats() #pdb.set_trace() self._flow_receiver = self._flow_dirs_over_flat_d8(flat_mask, labels) #a, q, s = flow_accum_bw.flow_accumulation(self._flow_receiver, self._open_boundary, node_cell_area=self._grid.forced_cell_areas) #self._grid['node']['flow_receiver'] = self._flow_receiver return self._flow_receiver def _resolve_flats(self): is_flat = np.zeros(self._n, dtype=bool) node_id = np.arange(self._n, dtype=int) (sink, ) = np.where(node_id==self._flow_receiver) for node in sink: if node in self._close_boundary: continue if not(is_flat[node]): is_flat = self._identify_flats(is_flat, node) high_edges, low_edges = self._flat_edges(is_flat) labels = np.zeros(self._n, dtype='int') labelid = 1 for node in low_edges: if labels[node]==0: labels = self._label_flats(labels, node, labelid) labelid += 1 flat_mask = np.zeros(self._n, dtype='float') flat_height = np.zeros(labelid, dtype='float') #this part is bottleneck flat_mask, flat_height = self._away_from_higher(flat_mask, labels, flat_height, high_edges) flat_mask, flat_height = self._towards_lower(flat_mask, labels, flat_height, low_edges) return flat_mask, labels def _identify_flats(self, is_flat, node): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary dem = self._dem ''' to_fill = Queue.Queue(maxsize=self._n*2) to_fill_put = to_fill.put to_fill_get = to_fill.get to_fill_empty = to_fill.empty ''' to_fill = deque(maxlen=self._n*2) to_fill_put = to_fill.append to_fill_get = to_fill.popleft closed = np.zeros(self._n, dtype=bool) closed[node] = True to_fill_put(node) elev = dem[node] while not(len(to_fill)==0): node = to_fill_get() if is_flat[node]: continue is_flat[node] = True for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if dem[neighbor_node]!=elev: continue if neighbor_node in boundary: continue if is_flat[neighbor_node] or closed[neighbor_node]: continue closed[neighbor_node] = True to_fill_put(neighbor_node) return is_flat def _flat_edges(self, is_flat): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary open_boundary = self._open_boundary close_boundary = self._close_boundary dem = self._dem ''' low_edges = Queue.Queue(maxsize=self._n*2) high_edges = Queue.Queue(maxsize=self._n*2) high_put = high_edges.put low_put = low_edges.put ''' low_edges = deque(maxlen=self._n*2) high_edges = deque(maxlen=self._n*2) high_put = high_edges.append low_put = low_edges.append for node in range(self._n): if node in boundary: continue if not(is_flat[node]): continue for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if neighbor_node in boundary: if flow_receiver[node]==node and (neighbor_node in close_boundary): high_put(node) break continue if flow_receiver[node]!=node and flow_receiver[neighbor_node]==neighbor_node and dem[node]==dem[neighbor_node]: low_put(node) break elif flow_receiver[node]==node and dem[node]<dem[neighbor_node]: high_put(node) break return high_edges, low_edges def _label_flats(self, labels, node, labelid): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary dem = self._dem ''' to_fill = Queue.Queue(maxsize=self._n*2) to_fill_put = to_fill.put to_fill_get = to_fill.get to_fill_empty = to_fill.empty ''' to_fill = deque(maxlen=self._n*2) to_fill_put = to_fill.append to_fill_get = to_fill.popleft closed = np.zeros(self._n, dtype=bool) closed[node] = True to_fill_put(node) elev = dem[node] while not(len(to_fill)==0): node = to_fill_get() if labels[node]!=0: continue labels[node] = labelid for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if neighbor_node in boundary: continue if dem[neighbor_node]!=elev: continue if labels[neighbor_node]!=0 or closed[neighbor_node]: continue closed[neighbor_node] = True to_fill_put(neighbor_node) return labels def _away_from_higher(self, flat_mask, labels, flat_height, high_edges): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary k = 1 MARKER = -100 ''' high_put = high_edges.put high_get = high_edges.get high_qsize = high_edges.qsize ''' high_put = high_edges.append high_get = high_edges.popleft closed = np.zeros(self._n, dtype=bool) #closed[high_edges.queue] = True for i in high_edges: closed[i] = True high_put(MARKER) while len(high_edges)>1: node = high_get() if node==MARKER: k += 1 high_put(MARKER) continue if flat_mask[node]>0: continue flat_mask[node] = k flat_height[labels[node]] = k for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if neighbor_node in boundary: continue if flat_mask[neighbor_node]>0: continue if closed[neighbor_node]: continue if labels[neighbor_node]==labels[node] and flow_receiver[neighbor_node]==neighbor_node: closed[neighbor_node] = True high_put(neighbor_node) return flat_mask, flat_height def _towards_lower(self, flat_mask, labels, flat_height, low_edges): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary flat_mask = 0-flat_mask k = 1 MARKER = -100 ''' low_put = low_edges.put low_get = low_edges.get low_qsize = low_edges.qsize low_queue = low_edges.queue ''' low_put = low_edges.append low_get = low_edges.popleft closed = np.zeros(self._n, dtype=bool) #closed[low_edges.queue] = True for i in low_edges: closed[i] = True low_put(MARKER) while len(low_edges)>1: node = low_get() if node==MARKER: k += 1 low_put(MARKER) continue if flat_mask[node]>0: continue if flat_mask[node]<0: flat_mask[node] = flat_height[labels[node]]+flat_mask[node]+2*k else: flat_mask[node] = 2*k for neighbor_node in neighbors[node]: if neighbor_node==-1: continue if neighbor_node in boundary: continue if flat_mask[neighbor_node]>0: continue if closed[neighbor_node]: continue if labels[neighbor_node]==labels[node] and flow_receiver[neighbor_node]==neighbor_node: closed[neighbor_node] = True low_put(neighbor_node) return flat_mask, flat_height def _flow_dirs_d8(self, dem): flow_receiver = np.arange(self._n) for node in range(self._n): if node in self._boundary: continue min_elev = dem[node] receiver = node for neighbor_node in self._neighbors[node]: if neighbor_node==-1: continue if neighbor_node in self._open_boundary: receiver = neighbor_node break if neighbor_node in self._close_boundary: continue if dem[neighbor_node]<min_elev: min_elev = dem[neighbor_node] receiver = neighbor_node flow_receiver[node] = receiver return flow_receiver def _flow_dirs_over_flat_d8(self, flat_mask, labels): flow_receiver = self._flow_receiver neighbors = self._neighbors boundary = self._boundary for node in range(self._n): if flow_receiver[node]!=node: continue if node in boundary: continue """ min_elev = flat_mask[node] receiver = node for neighbor_node in self._neighbors[node]: if neighbor_node==-1: continue if labels[neighbor_node]!=labels[node]: continue if flat_mask[neighbor_node]<min_elev: min_elev = flat_mask[neighbor_node] receiver = neighbor_node """ potential_receiver = neighbors[node] potential_receiver = potential_receiver[np.where(potential_receiver!=-1)] potential_receiver = potential_receiver[np.where(labels[potential_receiver]==labels[node])] receiver = potential_receiver[np.argmin(flat_mask[potential_receiver])] flow_receiver[node] = receiver return flow_receiver
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import functools import numpy as np from ... import units as u from ...tests.helper import pytest from ...coordinates import (ICRS, FK4, FK5, Galactic, SkyCoord, SphericalRepresentation) from ...time import Time RA = 1.0 * u.deg DEC = 2.0 * u.deg C_ICRS = ICRS(RA, DEC) C_FK5 = C_ICRS.transform_to(FK5) J2001 = Time('J2001', scale='utc') allclose_1e8 = functools.partial(np.allclose, rtol=0.0, atol=1e-8) def tst_transform_to(): for frame in (FK5, FK5(equinox=Time('J1975.0')), FK4, FK4(equinox=Time('J1975.0')), Galactic): c_frame = C_ICRS.transform_to(frame) s_icrs = SkyCoord(RA, DEC, frame='icrs') s_frame = s_icrs.transform_to(frame) assert c_frame.ra == s_frame.ra assert c_frame.dec == s_frame.dec def test_frame_init(): """ Different ways of providing the frame. """ sc = SkyCoord(RA, DEC, frame='icrs') assert sc.frame == 'icrs' sc = SkyCoord(RA, DEC, frame=ICRS) assert sc.frame == 'icrs' sc = SkyCoord(RA, DEC, 'icrs') assert sc.frame == 'icrs' sc = SkyCoord(RA, DEC, ICRS) assert sc.frame == 'icrs' sc = SkyCoord('icrs', RA, DEC) assert sc.frame == 'icrs' sc = SkyCoord(ICRS, RA, DEC) assert sc.frame == 'icrs' sc = SkyCoord(sc) assert sc.frame == 'icrs' sc = SkyCoord(C_ICRS) assert sc.frame == 'icrs' SkyCoord(C_ICRS, frame='icrs') assert sc.frame == 'icrs' with pytest.raises(ValueError) as err: SkyCoord(C_ICRS, frame='galactic') assert 'Cannot override frame=' in str(err) def test_attr_inheritance(): """ When initializing from an existing coord the preferred attrs like equinox should be inherited to the SkyCoord. If there is a conflict then raise an exception. """ sc = SkyCoord('icrs', 1, 2, unit='deg', equinox='J1999', obstime='J2001') sc2 = SkyCoord(sc) assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose_1e8(sc2.ra, sc.ra) assert allclose_1e8(sc2.dec, sc.dec) assert allclose_1e8(sc2.distance, sc.distance) sc2 = SkyCoord(sc._coord) # Doesn't have equinox there so we get FK4 defaults assert sc2.equinox != sc.equinox assert sc2.obstime != sc.obstime assert allclose_1e8(sc2.ra, sc.ra) assert allclose_1e8(sc2.dec, sc.dec) assert allclose_1e8(sc2.distance, sc.distance) sc = SkyCoord('fk4', 1, 2, unit='deg', equinox='J1999', obstime='J2001') sc2 = SkyCoord(sc) assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose_1e8(sc2.ra, sc.ra) assert allclose_1e8(sc2.dec, sc.dec) assert allclose_1e8(sc2.distance, sc.distance) sc2 = SkyCoord(sc._coord) # sc._coord has equinox, obstime assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose_1e8(sc2.ra, sc.ra) assert allclose_1e8(sc2.dec, sc.dec) assert allclose_1e8(sc2.distance, sc.distance) def test_attr_conflicts(): """ Check conflicts resolution between coordinate attributes and init kwargs. """ sc = SkyCoord('icrs', 1, 2, unit='deg', equinox='J1999', obstime='J2001') # OK if attrs both specified but with identical values SkyCoord(sc, equinox='J1999', obstime='J2001') # OK because sc._coord doesn't have obstime SkyCoord(sc._coord, equinox='J1999', obstime='J2100') # Not OK if attrs don't match with pytest.raises(ValueError) as err: SkyCoord(sc, equinox='J1999', obstime='J2002') assert "Coordinate attribute 'obstime'=" in str(err) # Same game but with fk4 which has equinox and obstime frame attrs sc = SkyCoord('fk4', 1, 2, unit='deg', equinox='J1999', obstime='J2001') # OK if attrs both specified but with identical values SkyCoord(sc, equinox='J1999', obstime='J2001') # Not OK if SkyCoord attrs don't match with pytest.raises(ValueError) as err: SkyCoord(sc, equinox='J1999', obstime='J2002') assert "Coordinate attribute 'obstime'=" in str(err) # Not OK because sc._coord has different attrs with pytest.raises(ValueError) as err: SkyCoord(sc._coord, equinox='J1999', obstime='J2002') assert "Coordinate attribute 'obstime'=" in str(err) def test_frame_attr_getattr(): """ When accessing frame attributes like equinox, the value should come from self._coord when that object has the relevant attribute, otherwise from self. """ sc = SkyCoord('icrs', 1, 2, unit='deg', equinox='J1999', obstime='J2001') assert sc.equinox == 'J1999' # Just the raw value (not validated) assert sc.obstime == 'J2001' sc = SkyCoord('fk4', 1, 2, unit='deg', equinox='J1999', obstime='J2001') assert sc.equinox == Time('J1999') # Coming from the self._coord object assert sc.obstime == Time('J2001') sc = SkyCoord('fk4', 1, 2, unit='deg', equinox='J1999') assert sc.equinox == Time('J1999') assert sc.obstime == Time('J1999') def test_api(): """ Verify that the API take-2 examples run """ # NOT YET if False: sc = SkyCoord(SphericalRepresentation(lon=8 * u.hour, lat=5 * u.deg, distance=1 * u.kpc), frame='icrs') sc = SkyCoord(ra=8 * u.hour, dec=5 * u.deg, frame='icrs') sc = SkyCoord(l=120 * u.deg, b=5 * u.deg, frame='galactic') # High-level classes can also be initialized directly from low-level objects sc = SkyCoord(ICRS(ra=8 * u.hour, dec=5 * u.deg)) # The next example raises an error because the high-level class must always # have position data. if False: with pytest.raises(ValueError): sc = SkyCoord(FK5(equinox=J2001)) # raises ValueError # similarly, the low-level object can always be accessed # NOT YET. NEVER? # assert str(sframe) == '<ICRS RA=120.000 deg, Dec=5.00000 deg>' # Should (eventually) support a variety of possible complex string formats sc = SkyCoord('8h00m00s +5d00m00.0s', frame='icrs') # In the next example, the unit is only needed b/c units are ambiguous. In # general, we *never* accept ambiguity sc = SkyCoord('8:00:00 +5:00:00.0', unit=(u.hour, u.deg), frame='icrs') # The next one would yield length-2 array coordinates, because of the comma # NOT YET # sc = SkyCoord(['8h 5d', '2°5\'12.3" 0.3rad'], frame='icrs') # It should also interpret common designation styles as a coordinate # NOT YET # sc = SkyCoord('SDSS J123456.89-012345.6', frame='icrs') # the string representation can be inherited from the low-level class. # NOT YET # assert str(sc) == '<SkyCoord (ICRS) RA=120.000 deg, Dec=5.00000 deg>' # but it should also be possible to provide formats for outputting to strings, # similar to `Time`. This can be added right away or at a later date. # transformation is done the same as for low-level classes, which it delegates to # NOT YET # scfk5_j2001 = stransform_to(FK5(equinox=J2001)) # The key difference is that the high-level class remembers frame information # necessary for round-tripping, unlike the low-level classes: sc1 = SkyCoord(ra=8 * u.hour, dec=5 * u.deg, equinox=J2001, frame='fk5') sc2 = sc1.transform_to('icrs') # The next assertion succeeds, but it doesn't mean anything for ICRS, as ICRS # isn't defined in terms of an equinox assert sc2.equinox == J2001 # But it *is* necessary once we transform to FK5 sc3 = sc2.transform_to('fk5') assert sc3.equinox == J2001 assert sc1.ra == sc3.ra # Note that this did *not* work in the low-level class example shown above, # because the ICRS low-level class does not store `equinox`. # `SkyCoord` will also include the attribute-style access that is in the # v0.2/0.3 coordinate objects. This will *not* be in the low-level classes sc = SkyCoord(ra=8 * u.hour, dec=5 * u.deg, frame='icrs') scgal = sc.galactic assert str(scgal).startswith('<Galactic SkyCoord: l=216.317') # the existing `from_name` and `match_to_catalog_*` methods will be moved to the # high-level class as convenience functionality. if False: m31icrs = SkyCoord.from_name('M31', frame='icrs') assert str(m31icrs) == '<SkyCoord (ICRS) RA=10.68471 deg, Dec=41.26875 deg>' cat1 = SkyCoord(ra=1 * u.hr, dec=2 * u.deg, distance=3 * u.kpc) cat2 = SkyCoord(ra=1 * u.hr, dec=2 * u.deg, distance=3 * u.kpc) idx2, sep2d, dist3d = cat1.match_to_catalog_sky(cat2) idx2, sep2d, dist3d = cat1.match_to_catalog_3d(cat2) # additional convenience functionality for the future should be added as methods # on `SkyCoord`, *not* the low-level classes. Add bunch of tests # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import functools import numpy as np from ... import units as u from ...tests.helper import pytest from ...coordinates import (ICRS, FK4, FK5, Galactic, SkyCoord, Angle, SphericalRepresentation, CartesianRepresentation) from ...time import Time RA = 1.0 * u.deg DEC = 2.0 * u.deg C_ICRS = ICRS(RA, DEC) C_FK5 = C_ICRS.transform_to(FK5) J2001 = Time('J2001', scale='utc') allclose = functools.partial(np.allclose, rtol=0.0, atol=1e-8) def tst_transform_to(): for frame in (FK5, FK5(equinox=Time('J1975.0')), FK4, FK4(equinox=Time('J1975.0')), Galactic): c_frame = C_ICRS.transform_to(frame) s_icrs = SkyCoord(RA, DEC, frame='icrs') s_frame = s_icrs.transform_to(frame) assert c_frame.ra == s_frame.ra assert c_frame.dec == s_frame.dec def test_coord_init_string(): """ Spherical or Cartesian represenation input coordinates. """ sc = SkyCoord('1d 2d') assert allclose(sc.ra, 1 * u.deg) assert allclose(sc.dec, 2 * u.deg) sc = SkyCoord('1d', '2d') assert allclose(sc.ra, 1 * u.deg) assert allclose(sc.dec, 2 * u.deg) sc = SkyCoord(u'1°2′3″', u'2°3′4″') assert allclose(sc.ra, Angle(u'1°2′3″')) assert allclose(sc.dec, Angle(u'2°3′4″')) sc = SkyCoord(u'1°2′3″ 2°3′4″') assert allclose(sc.ra, Angle(u'1°2′3″')) assert allclose(sc.dec, Angle(u'2°3′4″')) with pytest.raises(ValueError) as err: SkyCoord('1d 2d 3d') assert "Cannot parse longitude and latitude" in str(err) def test_coord_init_list(): """ Spherical or Cartesian representation input coordinates. """ sc = SkyCoord([('1d', '2d'), (1 * u.deg, 2 * u.deg), '1d 2d', (u'1°', u'2°'), u'1° 2°'], unit='deg') assert allclose(sc.ra, Angle('1d')) assert allclose(sc.dec, Angle('2d')) with pytest.raises(ValueError) as err: SkyCoord(['1d 2d 3d']) assert "Cannot parse longitude and latitude" in str(err) with pytest.raises(ValueError) as err: SkyCoord([('1d', '2d', '3d')]) assert "Cannot parse longitude and latitude" in str(err) sc = SkyCoord([1 * u.deg, 1 * u.deg], [2 * u.deg, 2 * u.deg]) assert allclose(sc.ra, Angle('1d')) assert allclose(sc.dec, Angle('2d')) with pytest.raises(ValueError) as err: SkyCoord([1 * u.deg, 2 * u.deg]) # this list is taken as RA w/ missing dec assert "Cannot parse longitude and latitude" in str(err) def test_coord_init_representation(): """ Spherical or Cartesian represenation input coordinates. """ coord = SphericalRepresentation(lon=8 * u.deg, lat=5 * u.deg, distance=1 * u.kpc) sc = SkyCoord(coord, 'icrs') assert allclose(sc.ra, coord.lon) assert allclose(sc.dec, coord.lat) assert allclose(sc.distance, coord.distance) with pytest.raises(ValueError) as err: SkyCoord(coord, 'icrs', ra='1d') assert "conflicts with keyword argument 'ra'" in str(err) coord = CartesianRepresentation(1, 2, 3) sc = SkyCoord(coord, 'icrs') sc_cart = sc.represent_as(CartesianRepresentation) assert allclose(sc_cart.x, 1.0) assert allclose(sc_cart.y, 2.0) assert allclose(sc_cart.z, 3.0) def test_frame_init(): """ Different ways of providing the frame. """ sc = SkyCoord(RA, DEC, frame='icrs') assert sc.frame == 'icrs' sc = SkyCoord(RA, DEC, frame=ICRS) assert sc.frame == 'icrs' sc = SkyCoord(RA, DEC, 'icrs') assert sc.frame == 'icrs' sc = SkyCoord(RA, DEC, ICRS) assert sc.frame == 'icrs' sc = SkyCoord('icrs', RA, DEC) assert sc.frame == 'icrs' sc = SkyCoord(ICRS, RA, DEC) assert sc.frame == 'icrs' sc = SkyCoord(sc) assert sc.frame == 'icrs' sc = SkyCoord(C_ICRS) assert sc.frame == 'icrs' SkyCoord(C_ICRS, frame='icrs') assert sc.frame == 'icrs' with pytest.raises(ValueError) as err: SkyCoord(C_ICRS, frame='galactic') assert 'Cannot override frame=' in str(err) def test_attr_inheritance(): """ When initializing from an existing coord the preferred attrs like equinox should be inherited to the SkyCoord. If there is a conflict then raise an exception. """ sc = SkyCoord('icrs', 1, 2, unit='deg', equinox='J1999', obstime='J2001') sc2 = SkyCoord(sc) assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose(sc2.ra, sc.ra) assert allclose(sc2.dec, sc.dec) assert allclose(sc2.distance, sc.distance) sc2 = SkyCoord(sc._coord) # Doesn't have equinox there so we get FK4 defaults assert sc2.equinox != sc.equinox assert sc2.obstime != sc.obstime assert allclose(sc2.ra, sc.ra) assert allclose(sc2.dec, sc.dec) assert allclose(sc2.distance, sc.distance) sc = SkyCoord('fk4', 1, 2, unit='deg', equinox='J1999', obstime='J2001') sc2 = SkyCoord(sc) assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose(sc2.ra, sc.ra) assert allclose(sc2.dec, sc.dec) assert allclose(sc2.distance, sc.distance) sc2 = SkyCoord(sc._coord) # sc._coord has equinox, obstime assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose(sc2.ra, sc.ra) assert allclose(sc2.dec, sc.dec) assert allclose(sc2.distance, sc.distance) def test_attr_conflicts(): """ Check conflicts resolution between coordinate attributes and init kwargs. """ sc = SkyCoord('icrs', 1, 2, unit='deg', equinox='J1999', obstime='J2001') # OK if attrs both specified but with identical values SkyCoord(sc, equinox='J1999', obstime='J2001') # OK because sc._coord doesn't have obstime SkyCoord(sc._coord, equinox='J1999', obstime='J2100') # Not OK if attrs don't match with pytest.raises(ValueError) as err: SkyCoord(sc, equinox='J1999', obstime='J2002') assert "Coordinate attribute 'obstime'=" in str(err) # Same game but with fk4 which has equinox and obstime frame attrs sc = SkyCoord('fk4', 1, 2, unit='deg', equinox='J1999', obstime='J2001') # OK if attrs both specified but with identical values SkyCoord(sc, equinox='J1999', obstime='J2001') # Not OK if SkyCoord attrs don't match with pytest.raises(ValueError) as err: SkyCoord(sc, equinox='J1999', obstime='J2002') assert "Coordinate attribute 'obstime'=" in str(err) # Not OK because sc._coord has different attrs with pytest.raises(ValueError) as err: SkyCoord(sc._coord, equinox='J1999', obstime='J2002') assert "Coordinate attribute 'obstime'=" in str(err) def test_frame_attr_getattr(): """ When accessing frame attributes like equinox, the value should come from self._coord when that object has the relevant attribute, otherwise from self. """ sc = SkyCoord('icrs', 1, 2, unit='deg', equinox='J1999', obstime='J2001') assert sc.equinox == 'J1999' # Just the raw value (not validated) assert sc.obstime == 'J2001' sc = SkyCoord('fk4', 1, 2, unit='deg', equinox='J1999', obstime='J2001') assert sc.equinox == Time('J1999') # Coming from the self._coord object assert sc.obstime == Time('J2001') sc = SkyCoord('fk4', 1, 2, unit='deg', equinox='J1999') assert sc.equinox == Time('J1999') assert sc.obstime == Time('J1999') def test_api(): """ Verify that the API take-2 examples run """ # NOT YET sc = SkyCoord(SphericalRepresentation(lon=8 * u.hour, lat=5 * u.deg, distance=1 * u.kpc), frame='icrs') sc = SkyCoord(ra=8 * u.hour, dec=5 * u.deg, frame='icrs') sc = SkyCoord(l=120 * u.deg, b=5 * u.deg, frame='galactic') # High-level classes can also be initialized directly from low-level objects sc = SkyCoord(ICRS(ra=8 * u.hour, dec=5 * u.deg)) # The next example raises an error because the high-level class must always # have position data. if False: with pytest.raises(ValueError): sc = SkyCoord(FK5(equinox=J2001)) # raises ValueError # similarly, the low-level object can always be accessed # NOT YET. NEVER? # assert str(sframe) == '<ICRS RA=120.000 deg, Dec=5.00000 deg>' # Should (eventually) support a variety of possible complex string formats sc = SkyCoord('8h00m00s +5d00m00.0s', frame='icrs') # In the next example, the unit is only needed b/c units are ambiguous. In # general, we *never* accept ambiguity sc = SkyCoord('8:00:00 +5:00:00.0', unit=(u.hour, u.deg), frame='icrs') # The next one would yield length-2 array coordinates, because of the comma # NOT YET # sc = SkyCoord(['8h 5d', '2°5\'12.3" 0.3rad'], frame='icrs') # It should also interpret common designation styles as a coordinate # NOT YET # sc = SkyCoord('SDSS J123456.89-012345.6', frame='icrs') # the string representation can be inherited from the low-level class. # NOT YET # assert str(sc) == '<SkyCoord (ICRS) RA=120.000 deg, Dec=5.00000 deg>' # but it should also be possible to provide formats for outputting to strings, # similar to `Time`. This can be added right away or at a later date. # transformation is done the same as for low-level classes, which it delegates to # NOT YET # scfk5_j2001 = stransform_to(FK5(equinox=J2001)) # The key difference is that the high-level class remembers frame information # necessary for round-tripping, unlike the low-level classes: sc1 = SkyCoord(ra=8 * u.hour, dec=5 * u.deg, equinox=J2001, frame='fk5') sc2 = sc1.transform_to('icrs') # The next assertion succeeds, but it doesn't mean anything for ICRS, as ICRS # isn't defined in terms of an equinox assert sc2.equinox == J2001 # But it *is* necessary once we transform to FK5 sc3 = sc2.transform_to('fk5') assert sc3.equinox == J2001 assert sc1.ra == sc3.ra # Note that this did *not* work in the low-level class example shown above, # because the ICRS low-level class does not store `equinox`. # `SkyCoord` will also include the attribute-style access that is in the # v0.2/0.3 coordinate objects. This will *not* be in the low-level classes sc = SkyCoord(ra=8 * u.hour, dec=5 * u.deg, frame='icrs') scgal = sc.galactic assert str(scgal).startswith('<Galactic SkyCoord: l=216.317') # the existing `from_name` and `match_to_catalog_*` methods will be moved to the # high-level class as convenience functionality. if False: m31icrs = SkyCoord.from_name('M31', frame='icrs') assert str(m31icrs) == '<SkyCoord (ICRS) RA=10.68471 deg, Dec=41.26875 deg>' cat1 = SkyCoord(ra=1 * u.hr, dec=2 * u.deg, distance=3 * u.kpc) cat2 = SkyCoord(ra=1 * u.hr, dec=2 * u.deg, distance=3 * u.kpc) idx2, sep2d, dist3d = cat1.match_to_catalog_sky(cat2) idx2, sep2d, dist3d = cat1.match_to_catalog_3d(cat2) # additional convenience functionality for the future should be added as methods # on `SkyCoord`, *not* the low-level classes.
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from clr import AddReference AddReference("QuantConnect.Algorithm") AddReference("QuantConnect.Algorithm.Framework") AddReference("QuantConnect.Common") from QuantConnect import * from QuantConnect.Algorithm import * from QuantConnect.Algorithm.Framework import * from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel from QuantConnect.Indicators import RollingWindow, IndicatorDataPoint import pandas as pd class UncorrelatedUniverseSelectionModel(FundamentalUniverseSelectionModel): '''This universe selection model picks stocks that currently have their correlation to a benchmark deviated from the mean.''' def __init__(self, benchmark = Symbol.Create("SPY", SecurityType.Equity, Market.USA), numberOfSymbolsCoarse = 400, numberOfSymbols = 10, windowLength = 5, historyLength = 25, threshold = 0.5): '''Initializes a new default instance of the OnTheMoveUniverseSelectionModel Args: benchmark: Symbol of the benchmark numberOfSymbolsCoarse: Number of coarse symbols numberOfSymbols: Number of symbols selected by the universe model windowLength: Rolling window length period for correlation calculation historyLength: History length period threshold: Threadhold for the minimum mean correlation between security and benchmark''' super().__init__(False) self.benchmark = benchmark self.numberOfSymbolsCoarse = numberOfSymbolsCoarse self.numberOfSymbols = numberOfSymbols self.windowLength = windowLength self.historyLength = historyLength self.threshold = threshold self.cache = dict() self.symbol = list() def SelectCoarse(self, algorithm, coarse): '''Select stocks with highest Z-Score with fundamental data and positive previous-day price and volume''' # Verify whether the benchmark is present in the Coarse Fundamental benchmark = next((x for x in coarse if x.Symbol == self.benchmark), None) if benchmark is None: return self.symbol # Get the symbols with the highest dollar volume coarse = sorted([x for x in coarse if x.HasFundamentalData and x.Volume * x.Price > 0 and x.Symbol != self.benchmark], key = lambda x: x.DollarVolume, reverse=True)[:self.numberOfSymbolsCoarse] newSymbols = list() for cf in coarse + [benchmark]: symbol = cf.Symbol data = self.cache.setdefault(symbol, self.SymbolData(self, symbol)) data.Update(cf.EndTime, cf.AdjustedPrice) if not data.IsReady: newSymbols.append(symbol) # Warm up the dictionary objects of selected symbols and benchmark that do not have enought data if len(newSymbols) > 1: history = algorithm.History(newSymbols, self.historyLength, Resolution.Daily) if not (history.empty or len(history.index) < self.historyLength): history = history.close.unstack(level=0).dropna() for symbol in newSymbols: self.cache[symbol].Warmup(history) # Create a new dictionary with the zScore zScore = dict() benchmark = self.cache[self.benchmark].GetReturns() for cf in coarse: symbol = cf.Symbol value = self.cache[symbol].CalculateZScore(benchmark) if value > 0: zScore[symbol] = value # Sort the zScore dictionary by value if len(zScore) > self.numberOfSymbols: sorted_zScore = sorted(zScore.items(), key=lambda kvp: kvp[1], reverse=True) zScore = dict(sorted_zScore[:self.numberOfSymbols]) # Return the symbols self.symbols = list(zScore.keys()) return self.symbols class SymbolData: '''Contains data specific to a symbol required by this model''' def __init__(self, model, symbol): self.symbol = symbol self.windowLength = model.windowLength self.historyLength = model.historyLength self.threshold = model.threshold self.history = RollingWindow[IndicatorDataPoint](self.historyLength) self.correlation = None def Warmup(self, history): '''Save the historical data that will be used to compute the correlation''' symbol = str(self.symbol) if symbol not in history: return # Save the last point before reset last = self.history[0] self.history.Reset() # Uptade window with historical data for time, value in history[symbol].iteritems(): self.Update(time, value) # Re-add the last point if necessary if last.EndTime > time: self.Update(last.EndTime, last.Value) def Update(self, time, value): '''Update the historical data''' self.history.Add(IndicatorDataPoint(self.symbol, time, value)) def CalculateZScore(self, benchmark): '''Computes the ZScore''' # Not enough data to compute zScore if not self.IsReady: return 0 returns = pd.DataFrame.from_dict({"A": self.GetReturns(), "B": benchmark}) if self.correlation is None: # Calculate stdev(correlation) using rolling window for all history correlation = returns.rolling(self.windowLength, min_periods = self.windowLength).corr() self.correlation = correlation["B"].dropna().unstack() else: last_correlation = returns.tail(self.windowLength).corr()["B"] self.correlation = self.correlation.append(last_correlation).tail(self.historyLength) # Calculate the mean of correlation and discard low mean correlation mean = self.correlation.mean() if mean.empty or mean[0] < self.threshold: return 0 # Calculate the standard deviation of correlation std = self.correlation.std() # Current correlation current = self.correlation.tail(1).unstack() # Calculate absolute value of Z-Score for stocks in the Coarse Universe. return abs(current[0] - mean[0]) / std[0] def GetReturns(self): '''Get the returns from the rolling window dictionary''' historyDict = {x.EndTime: x.Value for x in self.history} return pd.Series(historyDict).sort_index().pct_change().dropna() @property def IsReady(self): return self.history.IsReady Update UncorrelatedUniverseSelectionModel.py # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from clr import AddReference AddReference("QuantConnect.Algorithm") AddReference("QuantConnect.Algorithm.Framework") AddReference("QuantConnect.Common") from QuantConnect import * from QuantConnect.Algorithm import * from QuantConnect.Algorithm.Framework import * from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel from QuantConnect.Indicators import RollingWindow, IndicatorDataPoint import pandas as pd class UncorrelatedUniverseSelectionModel(FundamentalUniverseSelectionModel): '''This universe selection model picks stocks that currently have their correlation to a benchmark deviated from the mean.''' def __init__(self, benchmark = Symbol.Create("SPY", SecurityType.Equity, Market.USA), numberOfSymbolsCoarse = 400, numberOfSymbols = 10, windowLength = 5, historyLength = 25, threshold = 0.5): '''Initializes a new default instance of the OnTheMoveUniverseSelectionModel Args: benchmark: Symbol of the benchmark numberOfSymbolsCoarse: Number of coarse symbols numberOfSymbols: Number of symbols selected by the universe model windowLength: Rolling window length period for correlation calculation historyLength: History length period threshold: Threadhold for the minimum mean correlation between security and benchmark''' super().__init__(False) self.benchmark = benchmark self.numberOfSymbolsCoarse = numberOfSymbolsCoarse self.numberOfSymbols = numberOfSymbols self.windowLength = windowLength self.historyLength = historyLength self.threshold = threshold self.cache = dict() self.symbol = list() def SelectCoarse(self, algorithm, coarse): '''Select stocks with highest Z-Score with fundamental data and positive previous-day price and volume''' # Verify whether the benchmark is present in the Coarse Fundamental benchmark = next((x for x in coarse if x.Symbol == self.benchmark), None) if benchmark is None: return self.symbol # Get the symbols with the highest dollar volume coarse = sorted([x for x in coarse if x.HasFundamentalData and x.Volume * x.Price > 0 and x.Symbol != self.benchmark], key = lambda x: x.DollarVolume, reverse=True)[:self.numberOfSymbolsCoarse] newSymbols = list() for cf in coarse + [benchmark]: symbol = cf.Symbol data = self.cache.setdefault(symbol, self.SymbolData(self, symbol)) data.Update(cf.EndTime, cf.AdjustedPrice) if not data.IsReady: newSymbols.append(symbol) # Warm up the dictionary objects of selected symbols and benchmark that do not have enough data if len(newSymbols) > 1: history = algorithm.History(newSymbols, self.historyLength, Resolution.Daily) if not history.empty: history = history.close.unstack(level=0).fillna(method='bfill') for symbol in newSymbols: self.cache[symbol].Warmup(history) # Create a new dictionary with the zScore zScore = dict() benchmark = self.cache[self.benchmark].GetReturns() for cf in coarse: symbol = cf.Symbol value = self.cache[symbol].CalculateZScore(benchmark) if value > 0: zScore[symbol] = value # Sort the zScore dictionary by value if len(zScore) > self.numberOfSymbols: sorted_zScore = sorted(zScore.items(), key=lambda kvp: kvp[1], reverse=True) zScore = dict(sorted_zScore[:self.numberOfSymbols]) # Return the symbols self.symbols = list(zScore.keys()) return self.symbols class SymbolData: '''Contains data specific to a symbol required by this model''' def __init__(self, model, symbol): self.symbol = symbol self.windowLength = model.windowLength self.historyLength = model.historyLength self.threshold = model.threshold self.history = RollingWindow[IndicatorDataPoint](self.historyLength) self.correlation = None def Warmup(self, history): '''Save the historical data that will be used to compute the correlation''' symbol = str(self.symbol) if symbol not in history: return # Save the last point before reset last = self.history[0] self.history.Reset() # Uptade window with historical data for time, value in history[symbol].iteritems(): self.Update(time, value) # Re-add the last point if necessary if last.EndTime > time: self.Update(last.EndTime, last.Value) def Update(self, time, value): '''Update the historical data''' self.history.Add(IndicatorDataPoint(self.symbol, time, value)) def CalculateZScore(self, benchmark): '''Computes the ZScore''' # Not enough data to compute zScore if not self.IsReady: return 0 returns = pd.DataFrame.from_dict({"A": self.GetReturns(), "B": benchmark}) if self.correlation is None: # Calculate stdev(correlation) using rolling window for all history correlation = returns.rolling(self.windowLength, min_periods = self.windowLength).corr() self.correlation = correlation["B"].dropna().unstack() else: last_correlation = returns.tail(self.windowLength).corr()["B"] self.correlation = self.correlation.append(last_correlation).tail(self.historyLength) # Calculate the mean of correlation and discard low mean correlation mean = self.correlation.mean() if mean.empty or mean[0] < self.threshold: return 0 # Calculate the standard deviation of correlation std = self.correlation.std() # Current correlation current = self.correlation.tail(1).unstack() # Calculate absolute value of Z-Score for stocks in the Coarse Universe. return abs(current[0] - mean[0]) / std[0] def GetReturns(self): '''Get the returns from the rolling window dictionary''' historyDict = {x.EndTime: x.Value for x in self.history} return pd.Series(historyDict).sort_index().pct_change().dropna() @property def IsReady(self): return self.history.IsReady
"""A module containing validation functionality. Warning: It is planned to change from Schema-based to Data-based Codelist validation. As such, this module will change significantly. """ from lxml import etree import iati.core.default def _correct_codes(dataset, codelist, error_log=False): """Determine whether a given Dataset has values from the specified Codelist where expected. Args: dataset (iati.core.data.Dataset): The Dataset to check Codelist values within. codelist (iati.core.codelists.Codelist): The Codelist to check values from. error_log (bool): Whether to return a detailed error log, or merely a boolean value. Default False. Returns: bool: If `error_log` is False. A boolean indicating whether the given Dataset has values from the specified Codelist where they should be. list of dict: If `error_log` is True. A list of the errors that occurred. """ errors = [] mappings = iati.core.default.codelist_mapping() for mapping in mappings[codelist.name]: base_xpath = mapping['xpath'] condition = mapping['condition'] split_xpath = base_xpath.split('/') parent_el_xpath = '/'.join(split_xpath[:-1]) attr_name = split_xpath[-1:][0][1:] if condition is None: parent_el_xpath = parent_el_xpath + '[@' + attr_name + ']' else: parent_el_xpath = parent_el_xpath + '[' + condition + ' and @' + attr_name + ']' parents_to_check = dataset.xml_tree.xpath(parent_el_xpath) for parent in parents_to_check: code = parent.attrib[attr_name] if code not in codelist.codes: if error_log: errors.append(_create_error()) else: return False if error_log: return errors else: return True def _correct_codelist_values(dataset, schema, error_log=False): """Determine whether a given Dataset has values from Codelists that have been added to a Schema where expected. Args: dataset (iati.core.data.Dataset): The Dataset to check Codelist values within. schema (iati.core.schemas.Schema): The Schema to locate Codelists within. error_log (bool): Whether to return a detailed error log, or merely a boolean value. Default False. Returns: bool: If `error_log` is False. A boolean indicating whether the given Dataset has values from the specified Codelists where they should be. list of dict: If `error_log` is True. A list of the errors that occurred. """ errors = [] for codelist in schema.codelists: if error_log: errors = errors + _correct_codes(dataset, codelist, error_log) else: correct_for_codelist = _correct_codes(dataset, codelist) if not correct_for_codelist: return False if error_log: return errors else: return True def _create_error(): """Creates an error. Returns: dict: Information about the error. """ return {} def full_validation(dataset, schema): """Perform full validation on a Dataset. Args: dataset (iati.core.Dataset): The Dataset to check validity of. schema (iati.core.Schema): The Schema to validate the Dataset against. Warning: Parameters are likely to change in some manner. Returns: list of dict: A list of dictionaries containing error output. An empty list indicates that there are no errors. Todo: Create test against a bad Schema. """ return _correct_codelist_values(dataset, schema, True) def is_iati_xml(dataset, schema): """Determine whether a given Dataset's XML is valid against the specified Schema. Args: dataset (iati.core.data.Dataset): The Dataset to check validity of. schema (iati.core.schemas.Schema): The Schema to validate the Dataset against. Warning: Parameters are likely to change in some manner. Returns: bool: A boolean indicating whether the given Dataset is valid XML against the given Schema. Raises: iati.core.exceptions.SchemaError: An error occurred in the parsing of the Schema. Todo: Create test against a bad Schema. """ try: validator = schema.validator() except iati.core.exceptions.SchemaError as err: raise err try: validator.assertValid(dataset.xml_tree) except etree.DocumentInvalid: return False return True def is_valid(dataset, schema): """Determine whether a given Dataset is valid against the specified Schema. Args: dataset (iati.core.Dataset): The Dataset to check validity of. schema (iati.core.Schema): The Schema to validate the Dataset against. Warning: Parameters are likely to change in some manner. Returns: bool: A boolean indicating whether the given Dataset is valid against the given Schema. Todo: Create test against a bad Schema. """ try: iati_xml = is_iati_xml(dataset, schema) if not iati_xml: return False except iati.core.exceptions.SchemaError: return False return _correct_codelist_values(dataset, schema) def is_xml(maybe_xml): """Determine whether a given parameter is XML. Args: maybe_xml (str): An string that may or may not contain valid XML. Returns: bool: A boolean indicating whether the given Dataset is valid XML. """ if isinstance(maybe_xml, iati.core.data.Dataset): maybe_xml = maybe_xml.xml_str try: _ = etree.fromstring(maybe_xml.strip()) return True except (etree.XMLSyntaxError, AttributeError, TypeError, ValueError): return False Remove a curently redundant function """A module containing validation functionality. Warning: It is planned to change from Schema-based to Data-based Codelist validation. As such, this module will change significantly. """ from lxml import etree import iati.core.default def _correct_codes(dataset, codelist, error_log=False): """Determine whether a given Dataset has values from the specified Codelist where expected. Args: dataset (iati.core.data.Dataset): The Dataset to check Codelist values within. codelist (iati.core.codelists.Codelist): The Codelist to check values from. error_log (bool): Whether to return a detailed error log, or merely a boolean value. Default False. Returns: bool: If `error_log` is False. A boolean indicating whether the given Dataset has values from the specified Codelist where they should be. list of dict: If `error_log` is True. A list of the errors that occurred. """ errors = [] mappings = iati.core.default.codelist_mapping() for mapping in mappings[codelist.name]: base_xpath = mapping['xpath'] condition = mapping['condition'] split_xpath = base_xpath.split('/') parent_el_xpath = '/'.join(split_xpath[:-1]) attr_name = split_xpath[-1:][0][1:] if condition is None: parent_el_xpath = parent_el_xpath + '[@' + attr_name + ']' else: parent_el_xpath = parent_el_xpath + '[' + condition + ' and @' + attr_name + ']' parents_to_check = dataset.xml_tree.xpath(parent_el_xpath) for parent in parents_to_check: code = parent.attrib[attr_name] if code not in codelist.codes: if error_log: errors.append({}) else: return False if error_log: return errors else: return True def _correct_codelist_values(dataset, schema, error_log=False): """Determine whether a given Dataset has values from Codelists that have been added to a Schema where expected. Args: dataset (iati.core.data.Dataset): The Dataset to check Codelist values within. schema (iati.core.schemas.Schema): The Schema to locate Codelists within. error_log (bool): Whether to return a detailed error log, or merely a boolean value. Default False. Returns: bool: If `error_log` is False. A boolean indicating whether the given Dataset has values from the specified Codelists where they should be. list of dict: If `error_log` is True. A list of the errors that occurred. """ errors = [] for codelist in schema.codelists: if error_log: errors = errors + _correct_codes(dataset, codelist, error_log) else: correct_for_codelist = _correct_codes(dataset, codelist) if not correct_for_codelist: return False if error_log: return errors else: return True def full_validation(dataset, schema): """Perform full validation on a Dataset. Args: dataset (iati.core.Dataset): The Dataset to check validity of. schema (iati.core.Schema): The Schema to validate the Dataset against. Warning: Parameters are likely to change in some manner. Returns: list of dict: A list of dictionaries containing error output. An empty list indicates that there are no errors. Todo: Create test against a bad Schema. """ return _correct_codelist_values(dataset, schema, True) def is_iati_xml(dataset, schema): """Determine whether a given Dataset's XML is valid against the specified Schema. Args: dataset (iati.core.data.Dataset): The Dataset to check validity of. schema (iati.core.schemas.Schema): The Schema to validate the Dataset against. Warning: Parameters are likely to change in some manner. Returns: bool: A boolean indicating whether the given Dataset is valid XML against the given Schema. Raises: iati.core.exceptions.SchemaError: An error occurred in the parsing of the Schema. Todo: Create test against a bad Schema. """ try: validator = schema.validator() except iati.core.exceptions.SchemaError as err: raise err try: validator.assertValid(dataset.xml_tree) except etree.DocumentInvalid: return False return True def is_valid(dataset, schema): """Determine whether a given Dataset is valid against the specified Schema. Args: dataset (iati.core.Dataset): The Dataset to check validity of. schema (iati.core.Schema): The Schema to validate the Dataset against. Warning: Parameters are likely to change in some manner. Returns: bool: A boolean indicating whether the given Dataset is valid against the given Schema. Todo: Create test against a bad Schema. """ try: iati_xml = is_iati_xml(dataset, schema) if not iati_xml: return False except iati.core.exceptions.SchemaError: return False return _correct_codelist_values(dataset, schema) def is_xml(maybe_xml): """Determine whether a given parameter is XML. Args: maybe_xml (str): An string that may or may not contain valid XML. Returns: bool: A boolean indicating whether the given Dataset is valid XML. """ if isinstance(maybe_xml, iati.core.data.Dataset): maybe_xml = maybe_xml.xml_str try: _ = etree.fromstring(maybe_xml.strip()) return True except (etree.XMLSyntaxError, AttributeError, TypeError, ValueError): return False
# Orca # # Copyright 2010 Joanmarie Diggs. # Copyright 2014-2015 Igalia, S.L. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA. __id__ = "$Id$" __version__ = "$Revision$" __date__ = "$Date$" __copyright__ = "Copyright (c) 2010 Joanmarie Diggs." \ "Copyright (c) 2014-2015 Igalia, S.L." __license__ = "LGPL" import functools import pyatspi import re import time import urllib from orca import debug from orca import input_event from orca import messages from orca import mouse_review from orca import orca from orca import orca_state from orca import script_utilities from orca import script_manager from orca import settings from orca import settings_manager _scriptManager = script_manager.getManager() _settingsManager = settings_manager.getManager() class Utilities(script_utilities.Utilities): def __init__(self, script): super().__init__(script) self._objectAttributes = {} self._currentTextAttrs = {} self._caretContexts = {} self._priorContexts = {} self._contextPathsRolesAndNames = {} self._paths = {} self._inDocumentContent = {} self._inTopLevelWebApp = {} self._isTextBlockElement = {} self._isContentEditableWithEmbeddedObjects = {} self._isCodeDescendant = {} self._isEntryDescendant = {} self._isGridDescendant = {} self._isLabelDescendant = {} self._isMenuDescendant = {} self._isNavigableToolTipDescendant = {} self._isToolBarDescendant = {} self._isWebAppDescendant = {} self._isLayoutOnly = {} self._isFocusableWithMathChild = {} self._mathNestingLevel = {} self._isOffScreenLabel = {} self._elementLinesAreSingleChars= {} self._elementLinesAreSingleWords= {} self._hasNoSize = {} self._hasLongDesc = {} self._hasDetails = {} self._isDetails = {} self._hasUselessCanvasDescendant = {} self._isClickableElement = {} self._isAnchor = {} self._isEditableComboBox = {} self._isErrorMessage = {} self._isInlineIframeDescendant = {} self._isInlineListItem = {} self._isInlineListDescendant = {} self._isLandmark = {} self._isLink = {} self._isListDescendant = {} self._isNonNavigablePopup = {} self._isNonEntryTextWidget = {} self._isUselessImage = {} self._isRedundantSVG = {} self._isUselessEmptyElement = {} self._hasNameAndActionAndNoUsefulChildren = {} self._isNonNavigableEmbeddedDocument = {} self._isParentOfNullChild = {} self._inferredLabels = {} self._actualLabels = {} self._labelTargets = {} self._displayedLabelText = {} self._mimeType = {} self._preferDescriptionOverName = {} self._shouldFilter = {} self._shouldInferLabelFor = {} self._text = {} self._treatAsDiv = {} self._currentObjectContents = None self._currentSentenceContents = None self._currentLineContents = None self._currentWordContents = None self._currentCharacterContents = None self._lastQueuedLiveRegionEvent = None self._findContainer = None self._validChildRoles = {pyatspi.ROLE_LIST: [pyatspi.ROLE_LIST_ITEM]} def _cleanupContexts(self): toRemove = [] for key, [obj, offset] in self._caretContexts.items(): if self.isZombie(obj): toRemove.append(key) for key in toRemove: self._caretContexts.pop(key, None) def clearCachedObjects(self): debug.println(debug.LEVEL_INFO, "WEB: cleaning up cached objects", True) self._objectAttributes = {} self._inDocumentContent = {} self._inTopLevelWebApp = {} self._isTextBlockElement = {} self._isContentEditableWithEmbeddedObjects = {} self._isCodeDescendant = {} self._isEntryDescendant = {} self._isGridDescendant = {} self._isLabelDescendant = {} self._isMenuDescendant = {} self._isNavigableToolTipDescendant = {} self._isToolBarDescendant = {} self._isWebAppDescendant = {} self._isLayoutOnly = {} self._isFocusableWithMathChild = {} self._mathNestingLevel = {} self._isOffScreenLabel = {} self._elementLinesAreSingleChars= {} self._elementLinesAreSingleWords= {} self._hasNoSize = {} self._hasLongDesc = {} self._hasDetails = {} self._isDetails = {} self._hasUselessCanvasDescendant = {} self._isClickableElement = {} self._isAnchor = {} self._isEditableComboBox = {} self._isErrorMessage = {} self._isInlineIframeDescendant = {} self._isInlineListItem = {} self._isInlineListDescendant = {} self._isLandmark = {} self._isLink = {} self._isListDescendant = {} self._isNonNavigablePopup = {} self._isNonEntryTextWidget = {} self._isUselessImage = {} self._isRedundantSVG = {} self._isUselessEmptyElement = {} self._hasNameAndActionAndNoUsefulChildren = {} self._isNonNavigableEmbeddedDocument = {} self._isParentOfNullChild = {} self._inferredLabels = {} self._actualLabels = {} self._labelTargets = {} self._displayedLabelText = {} self._mimeType = {} self._preferDescriptionOverName = {} self._shouldFilter = {} self._shouldInferLabelFor = {} self._treatAsDiv = {} self._paths = {} self._contextPathsRolesAndNames = {} self._cleanupContexts() self._priorContexts = {} self._lastQueuedLiveRegionEvent = None self._findContainer = None def clearContentCache(self): self._currentObjectContents = None self._currentSentenceContents = None self._currentLineContents = None self._currentWordContents = None self._currentCharacterContents = None self._currentTextAttrs = {} self._text = {} def isDocument(self, obj): if not obj: return False roles = [pyatspi.ROLE_DOCUMENT_FRAME, pyatspi.ROLE_DOCUMENT_WEB, pyatspi.ROLE_EMBEDDED] try: rv = obj.getRole() in roles except: msg = "WEB: Exception getting role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = False return rv def inDocumentContent(self, obj=None): if not obj: obj = orca_state.locusOfFocus if self.isDocument(obj): return True rv = self._inDocumentContent.get(hash(obj)) if rv is not None: return rv document = self.getDocumentForObject(obj) rv = document is not None self._inDocumentContent[hash(obj)] = rv return rv def _getDocumentsEmbeddedBy(self, frame): if not frame: return [] isEmbeds = lambda r: r.getRelationType() == pyatspi.RELATION_EMBEDS try: relations = list(filter(isEmbeds, frame.getRelationSet())) except: msg = "ERROR: Exception getting embeds relation for %s" % frame debug.println(debug.LEVEL_INFO, msg, True) return [] if not relations: return [] relation = relations[0] targets = [relation.getTarget(i) for i in range(relation.getNTargets())] if not targets: return [] return list(filter(self.isDocument, targets)) def sanityCheckActiveWindow(self): app = self._script.app try: windowInApp = orca_state.activeWindow in app except: msg = "ERROR: Exception checking if %s is in %s" % (orca_state.activeWindow, app) debug.println(debug.LEVEL_INFO, msg, True) windowInApp = False if windowInApp: return True msg = "WARNING: %s is not in %s" % (orca_state.activeWindow, app) debug.println(debug.LEVEL_INFO, msg, True) try: script = _scriptManager.getScript(app, orca_state.activeWindow) msg = "WEB: Script for active Window is %s" % script debug.println(debug.LEVEL_INFO, msg, True) except: msg = "ERROR: Exception getting script for active window" debug.println(debug.LEVEL_INFO, msg, True) else: if type(script) == type(self._script): attrs = script.getTransferableAttributes() for attr, value in attrs.items(): msg = "WEB: Setting %s to %s" % (attr, value) debug.println(debug.LEVEL_INFO, msg, True) setattr(self._script, attr, value) window = self.activeWindow(app) try: self._script.app = window.getApplication() msg = "WEB: updating script's app to %s" % self._script.app debug.println(debug.LEVEL_INFO, msg, True) except: msg = "ERROR: Exception getting app for %s" % window debug.println(debug.LEVEL_INFO, msg, True) return False orca_state.activeWindow = window return True def activeDocument(self, window=None): isShowing = lambda x: x and x.getState().contains(pyatspi.STATE_SHOWING) documents = self._getDocumentsEmbeddedBy(window or orca_state.activeWindow) documents = list(filter(isShowing, documents)) if len(documents) == 1: return documents[0] return None def documentFrame(self, obj=None): if not obj and self.sanityCheckActiveWindow(): document = self.activeDocument() if document: return document return self.getDocumentForObject(obj or orca_state.locusOfFocus) def documentFrameURI(self, documentFrame=None): documentFrame = documentFrame or self.documentFrame() if documentFrame and not self.isZombie(documentFrame): try: document = documentFrame.queryDocument() except NotImplementedError: msg = "WEB: %s does not implement document interface" % documentFrame debug.println(debug.LEVEL_INFO, msg, True) except: msg = "ERROR: Exception querying document interface of %s" % documentFrame debug.println(debug.LEVEL_INFO, msg, True) else: return document.getAttributeValue('DocURL') or document.getAttributeValue('URI') return "" def isPlainText(self, documentFrame=None): return self.mimeType(documentFrame) == "text/plain" def mimeType(self, documentFrame=None): documentFrame = documentFrame or self.documentFrame() rv = self._mimeType.get(hash(documentFrame)) if rv is not None: return rv try: document = documentFrame.queryDocument() attrs = dict([attr.split(":", 1) for attr in document.getAttributes()]) except NotImplementedError: msg = "WEB: %s does not implement document interface" % documentFrame debug.println(debug.LEVEL_INFO, msg, True) except: msg = "ERROR: Exception getting document attributes of %s" % documentFrame debug.println(debug.LEVEL_INFO, msg, True) else: rv = attrs.get("MimeType") msg = "WEB: MimeType of %s is '%s'" % (documentFrame, rv) self._mimeType[hash(documentFrame)] = rv return rv def grabFocusWhenSettingCaret(self, obj): try: role = obj.getRole() state = obj.getState() childCount = obj.childCount except: msg = "WEB: Exception getting role, state, and childCount for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False # To avoid triggering popup lists. if role == pyatspi.ROLE_ENTRY: return False if role == pyatspi.ROLE_IMAGE: isLink = lambda x: x and x.getRole() == pyatspi.ROLE_LINK return pyatspi.utils.findAncestor(obj, isLink) is not None if role == pyatspi.ROLE_HEADING and childCount == 1: return self.isLink(obj[0]) return state.contains(pyatspi.STATE_FOCUSABLE) def grabFocus(self, obj): try: obj.queryComponent().grabFocus() except NotImplementedError: msg = "WEB: %s does not implement the component interface" % obj debug.println(debug.LEVEL_INFO, msg, True) except: msg = "WEB: Exception grabbing focus on %s" % obj debug.println(debug.LEVEL_INFO, msg, True) def setCaretPosition(self, obj, offset, documentFrame=None): if self._script.flatReviewContext: self._script.toggleFlatReviewMode() grabFocus = self.grabFocusWhenSettingCaret(obj) obj, offset = self.findFirstCaretContext(obj, offset) self.setCaretContext(obj, offset, documentFrame) if self._script.focusModeIsSticky(): return oldFocus = orca_state.locusOfFocus self.clearTextSelection(oldFocus) orca.setLocusOfFocus(None, obj, notifyScript=False) if grabFocus: self.grabFocus(obj) # Don't use queryNonEmptyText() because we need to try to force-update focus. if "Text" in pyatspi.listInterfaces(obj): try: obj.queryText().setCaretOffset(offset) except: msg = "WEB: Exception setting caret to %i in %s" % (offset, obj) debug.println(debug.LEVEL_INFO, msg, True) else: msg = "WEB: Caret set to %i in %s" % (offset, obj) debug.println(debug.LEVEL_INFO, msg, True) if self._script.useFocusMode(obj, oldFocus) != self._script.inFocusMode(): self._script.togglePresentationMode(None) if obj: obj.clearCache() # TODO - JD: This is private. self._script._saveFocusedObjectInfo(obj) def getNextObjectInDocument(self, obj, documentFrame): if not obj: return None for relation in obj.getRelationSet(): if relation.getRelationType() == pyatspi.RELATION_FLOWS_TO: return relation.getTarget(0) if obj == documentFrame: obj, offset = self.getCaretContext(documentFrame) for child in documentFrame: if self.characterOffsetInParent(child) > offset: return child if obj and obj.childCount: return obj[0] nextObj = None while obj and not nextObj: index = obj.getIndexInParent() + 1 if 0 < index < obj.parent.childCount: nextObj = obj.parent[index] elif obj.parent != documentFrame: obj = obj.parent else: break return nextObj def getPreviousObjectInDocument(self, obj, documentFrame): if not obj: return None for relation in obj.getRelationSet(): if relation.getRelationType() == pyatspi.RELATION_FLOWS_FROM: return relation.getTarget(0) if obj == documentFrame: obj, offset = self.getCaretContext(documentFrame) for child in documentFrame: if self.characterOffsetInParent(child) < offset: return child index = obj.getIndexInParent() - 1 if not 0 <= index < obj.parent.childCount: obj = obj.parent index = obj.getIndexInParent() - 1 previousObj = obj.parent[index] while previousObj and previousObj.childCount: previousObj = previousObj[previousObj.childCount - 1] return previousObj def getTopOfFile(self): return self.findFirstCaretContext(self.documentFrame(), 0) def getBottomOfFile(self): obj = self.getLastObjectInDocument(self.documentFrame()) offset = 0 text = self.queryNonEmptyText(obj) if text: offset = text.characterCount - 1 while obj: lastobj, lastoffset = self.nextContext(obj, offset) if not lastobj: break obj, offset = lastobj, lastoffset return [obj, offset] def getLastObjectInDocument(self, documentFrame): try: lastChild = documentFrame[documentFrame.childCount - 1] except: lastChild = documentFrame while lastChild: lastObj = self.getNextObjectInDocument(lastChild, documentFrame) if lastObj and lastObj != lastChild: lastChild = lastObj else: break return lastChild def objectAttributes(self, obj, useCache=True): if not (obj and self.inDocumentContent(obj)): return super().objectAttributes(obj) if useCache: rv = self._objectAttributes.get(hash(obj)) if rv is not None: return rv try: rv = dict([attr.split(':', 1) for attr in obj.getAttributes()]) except: rv = {} self._objectAttributes[hash(obj)] = rv return rv def getRoleDescription(self, obj): attrs = self.objectAttributes(obj) return attrs.get('roledescription', '') def nodeLevel(self, obj): if not (obj and self.inDocumentContent(obj)): return super().nodeLevel(obj) rv = -1 if not (self.inMenu(obj) or obj.getRole() == pyatspi.ROLE_HEADING): attrs = self.objectAttributes(obj) # ARIA levels are 1-based; non-web content is 0-based. Be consistent. rv = int(attrs.get('level', 0)) -1 return rv def getPositionInSet(self, obj): attrs = self.objectAttributes(obj, False) position = attrs.get('posinset') if position is not None: return int(position) if obj.getRole() == pyatspi.ROLE_TABLE_ROW: rowindex = attrs.get('rowindex') if rowindex is None and obj.childCount: roles = self._cellRoles() cell = pyatspi.findDescendant(obj, lambda x: x and x.getRole() in roles) rowindex = self.objectAttributes(cell, False).get('rowindex') if rowindex is not None: return int(rowindex) return None def getSetSize(self, obj): attrs = self.objectAttributes(obj, False) setsize = attrs.get('setsize') if setsize is not None: return int(setsize) if obj.getRole() == pyatspi.ROLE_TABLE_ROW: rows, cols = self.rowAndColumnCount(self.getTable(obj)) if rows != -1: return rows return None def _getID(self, obj): attrs = self.objectAttributes(obj) return attrs.get('id') def _getDisplayStyle(self, obj): attrs = self.objectAttributes(obj) return attrs.get('display') def _getTag(self, obj): attrs = self.objectAttributes(obj) return attrs.get('tag') def _getXMLRoles(self, obj): attrs = self.objectAttributes(obj) return attrs.get('xml-roles', '').split() def inFindContainer(self, obj=None): if not obj: obj = orca_state.locusOfFocus if self.inDocumentContent(obj): return False return super().inFindContainer(obj) def isEmpty(self, obj): if not self.isTextBlockElement(obj): return False if obj.name: return False return self.queryNonEmptyText(obj, False) is None def isHidden(self, obj): attrs = self.objectAttributes(obj) return attrs.get('hidden', False) def _isOrIsIn(self, child, parent): if not (child and parent): return False if child == parent: return True return pyatspi.findAncestor(child, lambda x: x == parent) def isShowingAndVisible(self, obj): rv = super().isShowingAndVisible(obj) if rv or not self.inDocumentContent(obj): return rv if not mouse_review.reviewer.inMouseEvent: if not self._isOrIsIn(orca_state.locusOfFocus, obj): return rv msg = "WEB: %s contains locusOfFocus but not showing and visible" % obj debug.println(debug.LEVEL_INFO, msg, True) obj.clearCache() rv = super().isShowingAndVisible(obj) if rv: msg = "WEB: Clearing cache fixed state of %s. Missing event?" % obj debug.println(debug.LEVEL_INFO, msg, True) return rv def isTextArea(self, obj): if not self.inDocumentContent(obj): return super().isTextArea(obj) if self.isLink(obj): return False try: role = obj.getRole() state = obj.getState() except: msg = "WEB: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if role == pyatspi.ROLE_COMBO_BOX \ and state.contains(pyatspi.STATE_EDITABLE) \ and not obj.childCount: return True if role in self._textBlockElementRoles(): document = self.getDocumentForObject(obj) if document and document.getState().contains(pyatspi.STATE_EDITABLE): return True return super().isTextArea(obj) def isReadOnlyTextArea(self, obj): # NOTE: This method is deliberately more conservative than isTextArea. if obj.getRole() != pyatspi.ROLE_ENTRY: return False state = obj.getState() readOnly = state.contains(pyatspi.STATE_FOCUSABLE) \ and not state.contains(pyatspi.STATE_EDITABLE) return readOnly def setCaretOffset(self, obj, characterOffset): self.setCaretPosition(obj, characterOffset) self._script.updateBraille(obj) def nextContext(self, obj=None, offset=-1, skipSpace=False): if not obj: obj, offset = self.getCaretContext() nextobj, nextoffset = self.findNextCaretInOrder(obj, offset) if (obj, offset) == (nextobj, nextoffset): nextobj, nextoffset = self.findNextCaretInOrder(nextobj, nextoffset) if skipSpace: text = self.queryNonEmptyText(nextobj) while text and text.getText(nextoffset, nextoffset + 1).isspace(): nextobj, nextoffset = self.findNextCaretInOrder(nextobj, nextoffset) text = self.queryNonEmptyText(nextobj) return nextobj, nextoffset def previousContext(self, obj=None, offset=-1, skipSpace=False): if not obj: obj, offset = self.getCaretContext() prevobj, prevoffset = self.findPreviousCaretInOrder(obj, offset) if (obj, offset) == (prevobj, prevoffset): prevobj, prevoffset = self.findPreviousCaretInOrder(prevobj, prevoffset) if skipSpace: text = self.queryNonEmptyText(prevobj) while text and text.getText(prevoffset, prevoffset + 1).isspace(): prevobj, prevoffset = self.findPreviousCaretInOrder(prevobj, prevoffset) text = self.queryNonEmptyText(prevobj) return prevobj, prevoffset def lastContext(self, root): offset = 0 text = self.queryNonEmptyText(root) if text: offset = text.characterCount - 1 def _isInRoot(o): return o == root or pyatspi.utils.findAncestor(o, lambda x: x == root) obj = root while obj: lastobj, lastoffset = self.nextContext(obj, offset) if not (lastobj and _isInRoot(lastobj)): break obj, offset = lastobj, lastoffset return obj, offset def contextsAreOnSameLine(self, a, b): if a == b: return True aObj, aOffset = a bObj, bOffset = b aExtents = self.getExtents(aObj, aOffset, aOffset + 1) bExtents = self.getExtents(bObj, bOffset, bOffset + 1) return self.extentsAreOnSameLine(aExtents, bExtents) @staticmethod def extentsAreOnSameLine(a, b, pixelDelta=5): if a == b: return True aX, aY, aWidth, aHeight = a bX, bY, bWidth, bHeight = b if aWidth == 0 and aHeight == 0: return bY <= aY <= bY + bHeight if bWidth == 0 and bHeight == 0: return aY <= bY <= aY + aHeight highestBottom = min(aY + aHeight, bY + bHeight) lowestTop = max(aY, bY) if lowestTop >= highestBottom: return False aMiddle = aY + aHeight / 2 bMiddle = bY + bHeight / 2 if abs(aMiddle - bMiddle) > pixelDelta: return False return True @staticmethod def getExtents(obj, startOffset, endOffset): if not obj: return [0, 0, 0, 0] result = [0, 0, 0, 0] try: text = obj.queryText() if text.characterCount and 0 <= startOffset < endOffset: result = list(text.getRangeExtents(startOffset, endOffset, 0)) except NotImplementedError: pass except: msg = "WEB: Exception getting range extents for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] else: if result[0] and result[1] and result[2] == 0 and result[3] == 0 \ and text.getText(startOffset, endOffset).strip(): msg = "WEB: Suspected bogus range extents for %s (chars: %i, %i): %s" % \ (obj, startOffset, endOffset, result) debug.println(debug.LEVEL_INFO, msg, True) elif text.characterCount: return result role = obj.getRole() try: parentRole = obj.parent.getRole() except: msg = "WEB: Exception getting role of parent (%s) of %s" % (obj.parent, obj) debug.println(debug.LEVEL_INFO, msg, True) parentRole = None if role in [pyatspi.ROLE_MENU, pyatspi.ROLE_LIST_ITEM] \ and parentRole in [pyatspi.ROLE_COMBO_BOX, pyatspi.ROLE_LIST_BOX]: try: ext = obj.parent.queryComponent().getExtents(0) except NotImplementedError: msg = "WEB: %s does not implement the component interface" % obj.parent debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] except: msg = "WEB: Exception getting extents for %s" % obj.parent debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] else: try: ext = obj.queryComponent().getExtents(0) except NotImplementedError: msg = "WEB: %s does not implement the component interface" % obj debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] except: msg = "WEB: Exception getting extents for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] return [ext.x, ext.y, ext.width, ext.height] def _preserveTree(self, obj): if not (obj and obj.childCount): return False if self.isMathTopLevel(obj): return True return False def expandEOCs(self, obj, startOffset=0, endOffset=-1): if not self.inDocumentContent(obj): return super().expandEOCs(obj, startOffset, endOffset) text = self.queryNonEmptyText(obj) if not text: return "" if self._preserveTree(obj): utterances = self._script.speechGenerator.generateSpeech(obj) return self._script.speechGenerator.utterancesToString(utterances) return super().expandEOCs(obj, startOffset, endOffset).strip() def substring(self, obj, startOffset, endOffset): if not self.inDocumentContent(obj): return super().substring(obj, startOffset, endOffset) text = self.queryNonEmptyText(obj) if text: return text.getText(startOffset, endOffset) return "" def textAttributes(self, acc, offset, get_defaults=False): attrsForObj = self._currentTextAttrs.get(hash(acc)) or {} if offset in attrsForObj: return attrsForObj.get(offset) attrs = super().textAttributes(acc, offset, get_defaults) self._currentTextAttrs[hash(acc)] = {offset:attrs} return attrs def findObjectInContents(self, obj, offset, contents, usingCache=False): if not obj or not contents: return -1 offset = max(0, offset) matches = [x for x in contents if x[0] == obj] match = [x for x in matches if x[1] <= offset < x[2]] if match and match[0] and match[0] in contents: return contents.index(match[0]) if not usingCache: match = [x for x in matches if offset == x[2]] if match and match[0] and match[0] in contents: return contents.index(match[0]) if not self.isTextBlockElement(obj): return -1 child = self.getChildAtOffset(obj, offset) if child and not self.isTextBlockElement(child): matches = [x for x in contents if x[0] == child] if len(matches) == 1: return contents.index(matches[0]) return -1 def isNonEntryTextWidget(self, obj): rv = self._isNonEntryTextWidget.get(hash(obj)) if rv is not None: return rv roles = [pyatspi.ROLE_CHECK_BOX, pyatspi.ROLE_CHECK_MENU_ITEM, pyatspi.ROLE_MENU, pyatspi.ROLE_MENU_ITEM, pyatspi.ROLE_PAGE_TAB, pyatspi.ROLE_RADIO_MENU_ITEM, pyatspi.ROLE_RADIO_BUTTON, pyatspi.ROLE_PUSH_BUTTON, pyatspi.ROLE_TOGGLE_BUTTON] role = obj.getRole() if role in roles: rv = True elif role == pyatspi.ROLE_LIST_ITEM: rv = obj.parent.getRole() != pyatspi.ROLE_LIST elif role == pyatspi.ROLE_TABLE_CELL: if obj.getState().contains(pyatspi.STATE_EDITABLE): rv = False else: rv = not self.isTextBlockElement(obj) self._isNonEntryTextWidget[hash(obj)] = rv return rv def queryNonEmptyText(self, obj, excludeNonEntryTextWidgets=True): if not (obj and self.inDocumentContent(obj)) or self._script.browseModeIsSticky(): return super().queryNonEmptyText(obj) if hash(obj) in self._text: return self._text.get(hash(obj)) try: rv = obj.queryText() characterCount = rv.characterCount except NotImplementedError: msg = "WEB: %s doesn't implement text interface" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None except: msg = "WEB: Exception getting character count for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None else: if not characterCount: msg = "WEB: %s reports 0 characters" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if self.isCellWithNameFromHeader(obj): pass elif self._treatObjectAsWhole(obj) and obj.name: msg = "WEB: Treating %s as non-text: named object treated as whole." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None elif not self.isLiveRegion(obj): doNotQuery = [pyatspi.ROLE_LIST_BOX] role = obj.getRole() if rv and role in doNotQuery: msg = "WEB: Treating %s as non-text due to role." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if rv and excludeNonEntryTextWidgets and self.isNonEntryTextWidget(obj): msg = "WEB: Treating %s as non-text: is non-entry text widget." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if rv and (self.isHidden(obj) or self.isOffScreenLabel(obj)): msg = "WEB: Treating %s as non-text: is hidden or off-screen label." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if rv and self.isNonNavigableEmbeddedDocument(obj): msg = "WEB: Treating %s as non-text: is non-navigable embedded document." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if rv and self.isFakePlaceholderForEntry(obj): msg = "WEB: Treating %s as non-text: is fake placeholder for entry." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None self._text[hash(obj)] = rv return rv def hasNameAndActionAndNoUsefulChildren(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._hasNameAndActionAndNoUsefulChildren.get(hash(obj)) if rv is not None: return rv rv = False if self.hasExplicitName(obj) and "Action" in pyatspi.listInterfaces(obj): for child in obj: if not self.isUselessEmptyElement(child) or self.isUselessImage(child): break else: rv = True if rv: msg = "WEB: %s has name and action and no useful children" % obj debug.println(debug.LEVEL_INFO, msg, True) self._hasNameAndActionAndNoUsefulChildren[hash(obj)] = rv return rv def _treatObjectAsWhole(self, obj): roles = [pyatspi.ROLE_CHECK_BOX, pyatspi.ROLE_CHECK_MENU_ITEM, pyatspi.ROLE_LIST_BOX, pyatspi.ROLE_MENU, pyatspi.ROLE_MENU_BAR, pyatspi.ROLE_MENU_ITEM, pyatspi.ROLE_RADIO_MENU_ITEM, pyatspi.ROLE_RADIO_BUTTON, pyatspi.ROLE_PUSH_BUTTON, pyatspi.ROLE_TOGGLE_BUTTON, pyatspi.ROLE_TOOL_BAR, pyatspi.ROLE_TREE, pyatspi.ROLE_TREE_ITEM, pyatspi.ROLE_TREE_TABLE] role = obj.getRole() if role in roles: return True state = obj.getState() if state.contains(pyatspi.STATE_EDITABLE): return False if role == pyatspi.ROLE_TABLE_CELL: if self.isFocusModeWidget(obj): return True if self.hasNameAndActionAndNoUsefulChildren(obj): return True if role in [pyatspi.ROLE_COLUMN_HEADER, pyatspi.ROLE_ROW_HEADER] \ and self.hasExplicitName(obj): return True if role == pyatspi.ROLE_COMBO_BOX: return True if role == pyatspi.ROLE_EMBEDDED: return not self._script.browseModeIsSticky() if role == pyatspi.ROLE_LINK: return self.hasExplicitName(obj) or self.hasUselessCanvasDescendant(obj) if self.isNonNavigableEmbeddedDocument(obj): return True if self.isFakePlaceholderForEntry(obj): return True return False def __findRange(self, text, offset, start, end, boundary): # We should not have to do any of this. Seriously. This is why # We can't have nice things. allText = text.getText(0, -1) if boundary == pyatspi.TEXT_BOUNDARY_CHAR: try: string = allText[offset] except IndexError: string = "" return string, offset, offset + 1 extents = list(text.getRangeExtents(offset, offset + 1, 0)) def _inThisSpan(span): return span[0] <= offset <= span[1] def _onThisLine(span): start, end = span startExtents = list(text.getRangeExtents(start, start + 1, 0)) endExtents = list(text.getRangeExtents(end - 1, end, 0)) delta = max(startExtents[3], endExtents[3]) if not self.extentsAreOnSameLine(startExtents, endExtents, delta): msg = "FAIL: Start %s and end %s of '%s' not on same line" \ % (startExtents, endExtents, allText[start:end]) debug.println(debug.LEVEL_INFO, msg, True) startExtents = endExtents return self.extentsAreOnSameLine(extents, startExtents) spans = [] charCount = text.characterCount if boundary == pyatspi.TEXT_BOUNDARY_SENTENCE_START: spans = [m.span() for m in re.finditer(r"\S*[^\.\?\!]+((?<!\w)[\.\?\!]+(?!\w)|\S*)", allText)] elif boundary is not None: spans = [m.span() for m in re.finditer("[^\n\r]+", allText)] if not spans: spans = [(0, charCount)] rangeStart, rangeEnd = 0, charCount for span in spans: if _inThisSpan(span): rangeStart, rangeEnd = span[0], span[1] + 1 break string = allText[rangeStart:rangeEnd] if string and boundary in [pyatspi.TEXT_BOUNDARY_SENTENCE_START, None]: return string, rangeStart, rangeEnd words = [m.span() for m in re.finditer("[^\\s\ufffc]+", string)] words = list(map(lambda x: (x[0] + rangeStart, x[1] + rangeStart), words)) if boundary == pyatspi.TEXT_BOUNDARY_WORD_START: spans = list(filter(_inThisSpan, words)) if boundary == pyatspi.TEXT_BOUNDARY_LINE_START: spans = list(filter(_onThisLine, words)) if spans: rangeStart, rangeEnd = spans[0][0], spans[-1][1] + 1 string = allText[rangeStart:rangeEnd] if not (rangeStart <= offset <= rangeEnd): return allText[start:end], start, end return string, rangeStart, rangeEnd def _attemptBrokenTextRecovery(self, obj, **args): return False def _getTextAtOffset(self, obj, offset, boundary): if not obj: msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '', Start: 0, End: 0. (obj is None)" % (offset, obj, boundary) debug.println(debug.LEVEL_INFO, msg, True) return '', 0, 0 text = self.queryNonEmptyText(obj) if not text: msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '', Start: 0, End: 1. (queryNonEmptyText() returned None)" \ % (offset, obj, boundary) debug.println(debug.LEVEL_INFO, msg, True) return '', 0, 1 if boundary is None: string, start, end = text.getText(0, -1), 0, text.characterCount s = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i." % (offset, obj, boundary, s, start, end) debug.println(debug.LEVEL_INFO, msg, True) return string, start, end if boundary == pyatspi.TEXT_BOUNDARY_SENTENCE_START \ and not obj.getState().contains(pyatspi.STATE_EDITABLE): allText = text.getText(0, -1) if obj.getRole() in [pyatspi.ROLE_LIST_ITEM, pyatspi.ROLE_HEADING] \ or not (re.search(r"\w", allText) and self.isTextBlockElement(obj)): string, start, end = allText, 0, text.characterCount s = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i." % (offset, obj, boundary, s, start, end) debug.println(debug.LEVEL_INFO, msg, True) return string, start, end if boundary == pyatspi.TEXT_BOUNDARY_LINE_START and self.treatAsEndOfLine(obj, offset): offset -= 1 msg = "WEB: Line sought for %s at end of text. Adjusting offset to %i." % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) offset = max(0, offset) string, start, end = text.getTextAtOffset(offset, boundary) # The above should be all that we need to do, but.... if not self._attemptBrokenTextRecovery(obj, boundary=boundary): s = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " Not checking for broken text." % (offset, obj, boundary, s, start, end) debug.println(debug.LEVEL_INFO, msg, True) return string, start, end needSadHack = False testString, testStart, testEnd = text.getTextAtOffset(start, boundary) if (string, start, end) != (testString, testStart, testEnd): s1 = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") s2 = testString.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "FAIL: Bad results for text at offset for %s using %s.\n" \ " For offset %i - String: '%s', Start: %i, End: %i.\n" \ " For offset %i - String: '%s', Start: %i, End: %i.\n" \ " The bug is the above results should be the same.\n" \ " This very likely needs to be fixed by the toolkit." \ % (obj, boundary, offset, s1, start, end, start, s2, testStart, testEnd) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True elif not string and 0 <= offset < text.characterCount: s1 = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") s2 = text.getText(0, -1).replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "FAIL: Bad results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " The bug is no text reported for a valid offset.\n" \ " Character count: %i, Full text: '%s'.\n" \ " This very likely needs to be fixed by the toolkit." \ % (offset, obj, boundary, s1, start, end, text.characterCount, s2) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True elif not (start <= offset < end) and not self.isPlainText(): s1 = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "FAIL: Bad results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " The bug is the range returned is outside of the offset.\n" \ " This very likely needs to be fixed by the toolkit." \ % (offset, obj, boundary, s1, start, end) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True elif len(string) < end - start: s1 = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "FAIL: Bad results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " The bug is that the length of string is less than the text range.\n" \ " This very likely needs to be fixed by the toolkit." \ % (offset, obj, boundary, s1, start, end) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True elif boundary == pyatspi.TEXT_BOUNDARY_CHAR and string == "\ufffd": msg = "FAIL: Bad results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " The bug is that we didn't seem to get a valid character.\n" \ " This very likely needs to be fixed by the toolkit." \ % (offset, obj, boundary, string, start, end) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True if needSadHack: sadString, sadStart, sadEnd = self.__findRange(text, offset, start, end, boundary) s = sadString.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "HACK: Attempting to recover from above failure.\n" \ " String: '%s', Start: %i, End: %i." % (s, sadStart, sadEnd) debug.println(debug.LEVEL_INFO, msg, True) return sadString, sadStart, sadEnd s = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i." % (offset, obj, boundary, s, start, end) debug.println(debug.LEVEL_INFO, msg, True) return string, start, end def _getContentsForObj(self, obj, offset, boundary): if not obj: return [] if boundary == pyatspi.TEXT_BOUNDARY_LINE_START: if self.isMath(obj): if self.isMathTopLevel(obj): math = obj else: math = self.getMathAncestor(obj) return [[math, 0, 1, '']] text = self.queryNonEmptyText(obj) if self.elementLinesAreSingleChars(obj): if obj.name and text: msg = "WEB: Returning name as contents for %s (single-char lines)" % obj debug.println(debug.LEVEL_INFO, msg, True) return [[obj, 0, text.characterCount, obj.name]] msg = "WEB: Returning all text as contents for %s (single-char lines)" % obj debug.println(debug.LEVEL_INFO, msg, True) boundary = None if self.elementLinesAreSingleWords(obj): if obj.name and text: msg = "WEB: Returning name as contents for %s (single-word lines)" % obj debug.println(debug.LEVEL_INFO, msg, True) return [[obj, 0, text.characterCount, obj.name]] msg = "WEB: Returning all text as contents for %s (single-word lines)" % obj debug.println(debug.LEVEL_INFO, msg, True) boundary = None role = obj.getRole() if role == pyatspi.ROLE_INTERNAL_FRAME and obj.childCount == 1: return self._getContentsForObj(obj[0], 0, boundary) string, start, end = self._getTextAtOffset(obj, offset, boundary) if not string: return [[obj, start, end, string]] stringOffset = offset - start try: char = string[stringOffset] except: pass else: if char == self.EMBEDDED_OBJECT_CHARACTER: child = self.getChildAtOffset(obj, offset) if child: return self._getContentsForObj(child, 0, boundary) ranges = [m.span() for m in re.finditer("[^\ufffc]+", string)] strings = list(filter(lambda x: x[0] <= stringOffset <= x[1], ranges)) if len(strings) == 1: rangeStart, rangeEnd = strings[0] start += rangeStart string = string[rangeStart:rangeEnd] end = start + len(string) return [[obj, start, end, string]] def getSentenceContentsAtOffset(self, obj, offset, useCache=True): if not obj: return [] offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentSentenceContents, usingCache=True) != -1: return self._currentSentenceContents boundary = pyatspi.TEXT_BOUNDARY_SENTENCE_START objects = self._getContentsForObj(obj, offset, boundary) state = obj.getState() if state.contains(pyatspi.STATE_EDITABLE) \ and state.contains(pyatspi.STATE_FOCUSED): return objects def _treatAsSentenceEnd(x): xObj, xStart, xEnd, xString = x if not self.isTextBlockElement(xObj): return False text = self.queryNonEmptyText(xObj) if text and 0 < text.characterCount <= xEnd: return True if 0 <= xStart <= 5: xString = " ".join(xString.split()[1:]) match = re.search(r"\S[\.\!\?]+(\s|\Z)", xString) return match is not None # Check for things in the same sentence before this object. firstObj, firstStart, firstEnd, firstString = objects[0] while firstObj and firstString: if self.isTextBlockElement(firstObj): if firstStart == 0: break elif self.isTextBlockElement(firstObj.parent): if self.characterOffsetInParent(firstObj) == 0: break prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) onLeft = self._getContentsForObj(prevObj, pOffset, boundary) onLeft = list(filter(lambda x: x not in objects, onLeft)) endsOnLeft = list(filter(_treatAsSentenceEnd, onLeft)) if endsOnLeft: i = onLeft.index(endsOnLeft[-1]) onLeft = onLeft[i+1:] if not onLeft: break objects[0:0] = onLeft firstObj, firstStart, firstEnd, firstString = objects[0] # Check for things in the same sentence after this object. while not _treatAsSentenceEnd(objects[-1]): lastObj, lastStart, lastEnd, lastString = objects[-1] nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) onRight = self._getContentsForObj(nextObj, nOffset, boundary) onRight = list(filter(lambda x: x not in objects, onRight)) if not onRight: break objects.extend(onRight) if useCache: self._currentSentenceContents = objects return objects def getCharacterContentsAtOffset(self, obj, offset, useCache=True): if not obj: return [] offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentCharacterContents, usingCache=True) != -1: return self._currentCharacterContents boundary = pyatspi.TEXT_BOUNDARY_CHAR objects = self._getContentsForObj(obj, offset, boundary) if useCache: self._currentCharacterContents = objects return objects def getWordContentsAtOffset(self, obj, offset, useCache=True): if not obj: return [] offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentWordContents, usingCache=True) != -1: self._debugContentsInfo(obj, offset, self._currentWordContents, "Word (cached)") return self._currentWordContents boundary = pyatspi.TEXT_BOUNDARY_WORD_START objects = self._getContentsForObj(obj, offset, boundary) extents = self.getExtents(obj, offset, offset + 1) def _include(x): if x in objects: return False xObj, xStart, xEnd, xString = x if xStart == xEnd or not xString: return False xExtents = self.getExtents(xObj, xStart, xStart + 1) return self.extentsAreOnSameLine(extents, xExtents) # Check for things in the same word to the left of this object. firstObj, firstStart, firstEnd, firstString = objects[0] prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) while prevObj and firstString and prevObj != firstObj: text = self.queryNonEmptyText(prevObj) if not text or text.getText(pOffset, pOffset + 1).isspace(): break onLeft = self._getContentsForObj(prevObj, pOffset, boundary) onLeft = list(filter(_include, onLeft)) if not onLeft: break if self._contentIsSubsetOf(objects[0], onLeft[-1]): objects.pop(0) objects[0:0] = onLeft firstObj, firstStart, firstEnd, firstString = objects[0] prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) # Check for things in the same word to the right of this object. lastObj, lastStart, lastEnd, lastString = objects[-1] while lastObj and lastString and not lastString[-1].isspace(): nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) if nextObj == lastObj: break onRight = self._getContentsForObj(nextObj, nOffset, boundary) if onRight and self._contentIsSubsetOf(objects[0], onRight[-1]): onRight = onRight[0:-1] onRight = list(filter(_include, onRight)) if not onRight: break objects.extend(onRight) lastObj, lastStart, lastEnd, lastString = objects[-1] # We want to treat the list item marker as its own word. firstObj, firstStart, firstEnd, firstString = objects[0] if firstStart == 0 and firstObj.getRole() == pyatspi.ROLE_LIST_ITEM: objects = [objects[0]] if useCache: self._currentWordContents = objects self._debugContentsInfo(obj, offset, objects, "Word (not cached)") return objects def getObjectContentsAtOffset(self, obj, offset=0, useCache=True): if not obj: return [] offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentObjectContents, usingCache=True) != -1: return self._currentObjectContents objIsLandmark = self.isLandmark(obj) def _isInObject(x): if not x: return False if x == obj: return True return _isInObject(x.parent) def _include(x): if x in objects: return False xObj, xStart, xEnd, xString = x if xStart == xEnd: return False if objIsLandmark and self.isLandmark(xObj) and obj != xObj: return False return _isInObject(xObj) objects = self._getContentsForObj(obj, offset, None) lastObj, lastStart, lastEnd, lastString = objects[-1] nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) while nextObj: onRight = self._getContentsForObj(nextObj, nOffset, None) onRight = list(filter(_include, onRight)) if not onRight: break objects.extend(onRight) lastObj, lastEnd = objects[-1][0], objects[-1][2] nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) if useCache: self._currentObjectContents = objects return objects def _contentIsSubsetOf(self, contentA, contentB): objA, startA, endA, stringA = contentA objB, startB, endB, stringB = contentB if objA == objB: setA = set(range(startA, endA)) setB = set(range(startB, endB)) return setA.issubset(setB) return False def _debugContentsInfo(self, obj, offset, contents, contentsMsg=""): if debug.LEVEL_INFO < debug.debugLevel: return msg = "WEB: %s for %s at offset %i:" % (contentsMsg, obj, offset) debug.println(debug.LEVEL_INFO, msg, True) for i, (acc, start, end, string) in enumerate(contents): indent = " " * 8 try: extents = self.getExtents(acc, start, end) except: extents = "(exception)" states = debug.statesToString(acc, indent) attrs = debug.attributesToString(acc, indent) msg = " %i. %s (chars: %i-%i) '%s' extents=%s\n%s\n%s" % \ (i, acc, start, end, string, extents, states, attrs) debug.println(debug.LEVEL_INFO, msg, True) def treatAsEndOfLine(self, obj, offset): if not self.isContentEditableWithEmbeddedObjects(obj): return False if "Text" not in pyatspi.listInterfaces(obj): return False if self.isDocument(obj): return False text = obj.queryText() if offset == text.characterCount: msg = "WEB: %s offset %i is end of line: offset is characterCount" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return True # Do not treat a literal newline char as the end of line. When there is an # actual newline character present, user agents should give us the right value # for the line at that offset. Here we are trying to figure out where asking # for the line at offset will give us the next line rather than the line where # the cursor is physically blinking. char = text.getText(offset, offset + 1) if char == self.EMBEDDED_OBJECT_CHARACTER: prevExtents = self.getExtents(obj, offset - 1, offset) thisExtents = self.getExtents(obj, offset, offset + 1) sameLine = self.extentsAreOnSameLine(prevExtents, thisExtents) msg = "WEB: %s offset %i is [obj]. Same line: %s Is end of line: %s" % \ (obj, offset, sameLine, not sameLine) debug.println(debug.LEVEL_INFO, msg, True) return not sameLine return False def getLineContentsAtOffset(self, obj, offset, layoutMode=None, useCache=True): if not obj: return [] text = self.queryNonEmptyText(obj) offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentLineContents, usingCache=True) != -1: self._debugContentsInfo(obj, offset, self._currentLineContents, "Line (cached)") return self._currentLineContents if layoutMode is None: layoutMode = _settingsManager.getSetting('layoutMode') or self._script.inFocusMode() objects = [] if offset > 0 and self.treatAsEndOfLine(obj, offset): extents = self.getExtents(obj, offset - 1, offset) else: extents = self.getExtents(obj, offset, offset + 1) if self.isInlineListDescendant(obj): container = self.listForInlineListDescendant(obj) if container: extents = self.getExtents(container, 0, 1) objBanner = pyatspi.findAncestor(obj, self.isLandmarkBanner) def _include(x): if x in objects: return False xObj, xStart, xEnd, xString = x if xStart == xEnd: return False xExtents = self.getExtents(xObj, xStart, xStart + 1) if obj != xObj: if self.isLandmark(obj) and self.isLandmark(xObj): return False if self.isLink(obj) and self.isLink(xObj): xObjBanner = pyatspi.findAncestor(xObj, self.isLandmarkBanner) if (objBanner or xObjBanner) and objBanner != xObjBanner: return False if abs(extents[0] - xExtents[0]) <= 1 and abs(extents[1] - xExtents[1]) <= 1: # This happens with dynamic skip links such as found on Wikipedia. return False elif self.isBlockListDescendant(obj) != self.isBlockListDescendant(xObj): return False if self.isMathTopLevel(xObj) or self.isMath(obj): onSameLine = self.extentsAreOnSameLine(extents, xExtents, extents[3]) else: onSameLine = self.extentsAreOnSameLine(extents, xExtents) return onSameLine boundary = pyatspi.TEXT_BOUNDARY_LINE_START objects = self._getContentsForObj(obj, offset, boundary) if not layoutMode: if useCache: self._currentLineContents = objects self._debugContentsInfo(obj, offset, objects, "Line (not layout mode)") return objects firstObj, firstStart, firstEnd, firstString = objects[0] if (extents[2] == 0 and extents[3] == 0) or self.isMath(firstObj): extents = self.getExtents(firstObj, firstStart, firstEnd) lastObj, lastStart, lastEnd, lastString = objects[-1] if self.isMathTopLevel(lastObj): lastObj, lastEnd = self.lastContext(lastObj) lastEnd += 1 document = self.getDocumentForObject(obj) prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) # Check for things on the same line to the left of this object. while prevObj and self.getDocumentForObject(prevObj) == document: text = self.queryNonEmptyText(prevObj) if text and text.getText(pOffset, pOffset + 1) in [" ", "\xa0"]: prevObj, pOffset = self.findPreviousCaretInOrder(prevObj, pOffset) onLeft = self._getContentsForObj(prevObj, pOffset, boundary) onLeft = list(filter(_include, onLeft)) if not onLeft: break if self._contentIsSubsetOf(objects[0], onLeft[-1]): objects.pop(0) objects[0:0] = onLeft firstObj, firstStart = objects[0][0], objects[0][1] prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) # Check for things on the same line to the right of this object. while nextObj and self.getDocumentForObject(nextObj) == document: text = self.queryNonEmptyText(nextObj) if text and text.getText(nOffset, nOffset + 1) in [" ", "\xa0"]: nextObj, nOffset = self.findNextCaretInOrder(nextObj, nOffset) onRight = self._getContentsForObj(nextObj, nOffset, boundary) if onRight and self._contentIsSubsetOf(objects[0], onRight[-1]): onRight = onRight[0:-1] onRight = list(filter(_include, onRight)) if not onRight: break objects.extend(onRight) lastObj, lastEnd = objects[-1][0], objects[-1][2] if self.isMathTopLevel(lastObj): lastObj, lastEnd = self.lastContext(lastObj) lastEnd += 1 nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) firstObj, firstStart, firstEnd, firstString = objects[0] if firstString == "\n" and len(objects) > 1: objects.pop(0) if useCache: self._currentLineContents = objects self._debugContentsInfo(obj, offset, objects, "Line (layout mode)") return objects def getPreviousLineContents(self, obj=None, offset=-1, layoutMode=None, useCache=True): if obj is None: obj, offset = self.getCaretContext() msg = "WEB: Current context is: %s, %i (focus: %s)" \ % (obj, offset, orca_state.locusOfFocus) debug.println(debug.LEVEL_INFO, msg, True) if obj and self.isZombie(obj): msg = "WEB: Current context obj %s is zombie. Clearing cache." % obj debug.println(debug.LEVEL_INFO, msg, True) self.clearCachedObjects() obj, offset = self.getCaretContext() msg = "WEB: Now Current context is: %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) line = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if not (line and line[0]): return [] firstObj, firstOffset = line[0][0], line[0][1] msg = "WEB: First context on line is: %s, %i" % (firstObj, firstOffset) debug.println(debug.LEVEL_INFO, msg, True) obj, offset = self.previousContext(firstObj, firstOffset, True) if not obj and firstObj: msg = "WEB: Previous context is: %s, %i. Trying again." % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) self.clearCachedObjects() obj, offset = self.previousContext(firstObj, firstOffset, True) msg = "WEB: Previous context is: %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) contents = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if not contents: msg = "WEB: Could not get line contents for %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return [] return contents def getNextLineContents(self, obj=None, offset=-1, layoutMode=None, useCache=True): if obj is None: obj, offset = self.getCaretContext() msg = "WEB: Current context is: %s, %i (focus: %s)" \ % (obj, offset, orca_state.locusOfFocus) debug.println(debug.LEVEL_INFO, msg, True) if obj and self.isZombie(obj): msg = "WEB: Current context obj %s is zombie. Clearing cache." % obj debug.println(debug.LEVEL_INFO, msg, True) self.clearCachedObjects() obj, offset = self.getCaretContext() msg = "WEB: Now Current context is: %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) line = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if not (line and line[0]): return [] lastObj, lastOffset = line[-1][0], line[-1][2] - 1 math = self.getMathAncestor(lastObj) if math: lastObj, lastOffset = self.lastContext(math) msg = "WEB: Last context on line is: %s, %i" % (lastObj, lastOffset) debug.println(debug.LEVEL_INFO, msg, True) obj, offset = self.nextContext(lastObj, lastOffset, True) if not obj and lastObj: msg = "WEB: Next context is: %s, %i. Trying again." % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) self.clearCachedObjects() obj, offset = self.nextContext(lastObj, lastOffset, True) msg = "WEB: Next context is: %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) contents = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if line == contents: obj, offset = self.nextContext(obj, offset, True) msg = "WEB: Got same line. Trying again with %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) contents = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if not contents: msg = "WEB: Could not get line contents for %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return [] return contents def updateCachedTextSelection(self, obj): if not self.inDocumentContent(obj): super().updateCachedTextSelection(obj) return if self.hasPresentableText(obj): super().updateCachedTextSelection(obj) def handleTextSelectionChange(self, obj, speakMessage=True): if not self.inDocumentContent(obj): return super().handleTextSelectionChange(obj) oldStart, oldEnd = self._script.pointOfReference.get('selectionAnchorAndFocus', (None, None)) start, end = self._getSelectionAnchorAndFocus(obj) self._script.pointOfReference['selectionAnchorAndFocus'] = (start, end) def _cmp(obj1, obj2): return self.pathComparison(pyatspi.getPath(obj1), pyatspi.getPath(obj2)) oldSubtree = self._getSubtree(oldStart, oldEnd) if start == oldStart and end == oldEnd: descendants = oldSubtree else: newSubtree = self._getSubtree(start, end) descendants = sorted(set(oldSubtree).union(newSubtree), key=functools.cmp_to_key(_cmp)) if not descendants: return False for descendant in descendants: if descendant not in (oldStart, oldEnd, start, end) \ and pyatspi.findAncestor(descendant, lambda x: x in descendants): super().updateCachedTextSelection(descendant) else: super().handleTextSelectionChange(descendant, speakMessage) return True def inPDFViewer(self, obj=None): uri = self.documentFrameURI() return uri.lower().endswith(".pdf") def inTopLevelWebApp(self, obj=None): if not obj: obj = orca_state.locusOfFocus rv = self._inTopLevelWebApp.get(hash(obj)) if rv is not None: return rv document = self.getDocumentForObject(obj) if not document and self.isDocument(obj): document = obj rv = self.isTopLevelWebApp(document) self._inTopLevelWebApp[hash(obj)] = rv return rv def isTopLevelWebApp(self, obj): try: role = obj.getRole() except: msg = "WEB: Exception getting role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if role == pyatspi.ROLE_EMBEDDED and not self.getDocumentForObject(obj.parent): uri = self.documentFrameURI() rv = bool(uri and uri.startswith("http")) msg = "WEB: %s is top-level web application: %s (URI: %s)" % (obj, rv, uri) debug.println(debug.LEVEL_INFO, msg, True) return rv return False def forceBrowseModeForWebAppDescendant(self, obj): if not self.isWebAppDescendant(obj): return False if obj.getRole() == pyatspi.ROLE_TOOL_TIP: return obj.getState().contains(pyatspi.STATE_FOCUSED) return False def isFocusModeWidget(self, obj): try: role = obj.getRole() state = obj.getState() except: msg = "WEB: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if state.contains(pyatspi.STATE_EDITABLE): msg = "WEB: %s is focus mode widget because it's editable" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if state.contains(pyatspi.STATE_EXPANDABLE) and state.contains(pyatspi.STATE_FOCUSABLE): msg = "WEB: %s is focus mode widget because it's expandable and focusable" % obj debug.println(debug.LEVEL_INFO, msg, True) return True alwaysFocusModeRoles = [pyatspi.ROLE_COMBO_BOX, pyatspi.ROLE_ENTRY, pyatspi.ROLE_LIST_BOX, pyatspi.ROLE_MENU, pyatspi.ROLE_MENU_ITEM, pyatspi.ROLE_CHECK_MENU_ITEM, pyatspi.ROLE_RADIO_MENU_ITEM, pyatspi.ROLE_PAGE_TAB, pyatspi.ROLE_PASSWORD_TEXT, pyatspi.ROLE_PROGRESS_BAR, pyatspi.ROLE_SLIDER, pyatspi.ROLE_SPIN_BUTTON, pyatspi.ROLE_TOOL_BAR, pyatspi.ROLE_TREE_ITEM, pyatspi.ROLE_TREE_TABLE, pyatspi.ROLE_TREE] if role in alwaysFocusModeRoles: msg = "WEB: %s is focus mode widget due to its role" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if role in [pyatspi.ROLE_TABLE_CELL, pyatspi.ROLE_TABLE] \ and self.isLayoutOnly(self.getTable(obj)): msg = "WEB: %s is not focus mode widget because it's layout only" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isButtonWithPopup(obj): msg = "WEB: %s is focus mode widget because it's a button with popup" % obj debug.println(debug.LEVEL_INFO, msg, True) return True focusModeRoles = [pyatspi.ROLE_EMBEDDED, pyatspi.ROLE_LIST_ITEM, pyatspi.ROLE_TABLE_CELL, pyatspi.ROLE_TABLE] if role in focusModeRoles \ and not self.isTextBlockElement(obj) \ and not self.hasNameAndActionAndNoUsefulChildren(obj) \ and not self.inPDFViewer(obj): msg = "WEB: %s is focus mode widget based on presumed functionality" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isGridDescendant(obj): msg = "WEB: %s is focus mode widget because it's a grid descendant" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isMenuDescendant(obj): msg = "WEB: %s is focus mode widget because it's a menu descendant" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isToolBarDescendant(obj): msg = "WEB: %s is focus mode widget because it's a toolbar descendant" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isContentEditableWithEmbeddedObjects(obj): msg = "WEB: %s is focus mode widget because it's content editable" % obj debug.println(debug.LEVEL_INFO, msg, True) return True return False def _cellRoles(self): roles = [pyatspi.ROLE_TABLE_CELL, pyatspi.ROLE_TABLE_COLUMN_HEADER, pyatspi.ROLE_TABLE_ROW_HEADER, pyatspi.ROLE_ROW_HEADER, pyatspi.ROLE_COLUMN_HEADER] return roles def _textBlockElementRoles(self): roles = [pyatspi.ROLE_ARTICLE, pyatspi.ROLE_CAPTION, pyatspi.ROLE_COLUMN_HEADER, pyatspi.ROLE_COMMENT, pyatspi.ROLE_DEFINITION, pyatspi.ROLE_DESCRIPTION_LIST, pyatspi.ROLE_DESCRIPTION_TERM, pyatspi.ROLE_DESCRIPTION_VALUE, pyatspi.ROLE_DOCUMENT_FRAME, pyatspi.ROLE_DOCUMENT_WEB, pyatspi.ROLE_FOOTER, pyatspi.ROLE_FORM, pyatspi.ROLE_HEADING, pyatspi.ROLE_LIST, pyatspi.ROLE_LIST_ITEM, pyatspi.ROLE_PARAGRAPH, pyatspi.ROLE_ROW_HEADER, pyatspi.ROLE_SECTION, pyatspi.ROLE_STATIC, pyatspi.ROLE_TEXT, pyatspi.ROLE_TABLE_CELL] # Remove this check when we bump dependencies to 2.34 try: roles.append(pyatspi.ROLE_CONTENT_DELETION) roles.append(pyatspi.ROLE_CONTENT_INSERTION) except: pass # Remove this check when we bump dependencies to 2.36 try: roles.append(pyatspi.ROLE_MARK) roles.append(pyatspi.ROLE_SUGGESTION) except: pass return roles def mnemonicShortcutAccelerator(self, obj): if not (obj and self.inDocumentContent(obj)): return super().mnemonicShortcutAccelerator(obj) attrs = self.objectAttributes(obj) keys = map(lambda x: x.replace("+", " "), attrs.get("keyshortcuts", "").split(" ")) keys = map(lambda x: x.replace(" ", "+"), map(self.labelFromKeySequence, keys)) rv = ["", " ".join(keys), ""] if list(filter(lambda x: x, rv)): return rv return super().mnemonicShortcutAccelerator(obj) def unrelatedLabels(self, root, onlyShowing=True, minimumWords=3): if not (root and self.inDocumentContent(root)): return super().unrelatedLabels(root, onlyShowing, minimumWords) return [] def isFocusableWithMathChild(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isFocusableWithMathChild.get(hash(obj)) if rv is not None: return rv try: state = obj.getState() except: msg = "WEB: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False rv = False if state.contains(pyatspi.STATE_FOCUSABLE) and not self.isDocument(obj): for child in obj: if self.isMathTopLevel(child): rv = True break self._isFocusableWithMathChild[hash(obj)] = rv return rv def isFocusedWithMathChild(self, obj): if not self.isFocusableWithMathChild(obj): return False try: state = obj.getState() except: msg = "WEB: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False return state.contains(pyatspi.STATE_FOCUSED) def isTextBlockElement(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isTextBlockElement.get(hash(obj)) if rv is not None: return rv try: role = obj.getRole() state = obj.getState() interfaces = pyatspi.listInterfaces(obj) except: msg = "WEB: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False textBlockElements = self._textBlockElementRoles() if not role in textBlockElements: rv = False elif not "Text" in interfaces: rv = False elif not obj.queryText().characterCount: rv = False elif state.contains(pyatspi.STATE_EDITABLE): rv = False elif role in [pyatspi.ROLE_DOCUMENT_FRAME, pyatspi.ROLE_DOCUMENT_WEB]: rv = True elif not state.contains(pyatspi.STATE_FOCUSABLE) and not state.contains(pyatspi.STATE_FOCUSED): rv = not self.hasNameAndActionAndNoUsefulChildren(obj) else: rv = False self._isTextBlockElement[hash(obj)] = rv return rv def _advanceCaretInEmptyObject(self, obj): role = obj.getRole() if role == pyatspi.ROLE_TABLE_CELL and not self.queryNonEmptyText(obj): return not self._script._lastCommandWasStructNav return True def textAtPoint(self, obj, x, y, coordType=None, boundary=None): if coordType is None: coordType = pyatspi.DESKTOP_COORDS if boundary is None: boundary = pyatspi.TEXT_BOUNDARY_LINE_START string, start, end = super().textAtPoint(obj, x, y, coordType, boundary) if string == self.EMBEDDED_OBJECT_CHARACTER: child = self.getChildAtOffset(obj, start) if child: return self.textAtPoint(child, x, y, coordType, boundary) return string, start, end def _treatAlertsAsDialogs(self): return False def treatAsDiv(self, obj, offset=None): if not (obj and self.inDocumentContent(obj)): return False try: role = obj.getRole() childCount = obj.childCount except: msg = "WEB: Exception getting role and childCount for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if role == pyatspi.ROLE_LIST and offset is not None: string = self.substring(obj, offset, offset + 1) if string and string != self.EMBEDDED_OBJECT_CHARACTER: return True if role == pyatspi.ROLE_PANEL and not childCount: return True rv = self._treatAsDiv.get(hash(obj)) if rv is not None: return rv validRoles = self._validChildRoles.get(role) if validRoles: if not childCount: rv = True else: rv = bool([x for x in obj if x and x.getRole() not in validRoles]) if not rv: validRoles = self._validChildRoles.get(obj.parent) if validRoles: rv = bool([x for x in obj.parent if x and x.getRole() not in validRoles]) self._treatAsDiv[hash(obj)] = rv return rv def isBlockquote(self, obj): if super().isBlockquote(obj): return True return self._getTag(obj) == 'blockquote' def isComment(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isComment(obj) if obj.getRole() == pyatspi.ROLE_COMMENT: return True return 'comment' in self._getXMLRoles(obj) def isContentDeletion(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentDeletion(obj) # Remove this check when we bump dependencies to 2.34 try: if obj.getRole() == pyatspi.ROLE_CONTENT_DELETION: return True except: pass return 'deletion' in self._getXMLRoles(obj) or 'del' == self._getTag(obj) def isContentError(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentError(obj) if obj.getRole() not in self._textBlockElementRoles(): return False return obj.getState().contains(pyatspi.STATE_INVALID_ENTRY) def isContentInsertion(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentInsertion(obj) # Remove this check when we bump dependencies to 2.34 try: if obj.getRole() == pyatspi.ROLE_CONTENT_INSERTION: return True except: pass return 'insertion' in self._getXMLRoles(obj) or 'ins' == self._getTag(obj) def isContentMarked(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentMarked(obj) # Remove this check when we bump dependencies to 2.36 try: if obj.getRole() == pyatspi.ROLE_MARK: return True except: pass return 'mark' in self._getXMLRoles(obj) or 'mark' == self._getTag(obj) def isContentSuggestion(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentSuggestion(obj) # Remove this check when we bump dependencies to 2.36 try: if obj.getRole() == pyatspi.ROLE_SUGGESTION: return True except: pass return 'suggestion' in self._getXMLRoles(obj) def isInlineIframe(self, obj): if not (obj and obj.getRole() == pyatspi.ROLE_INTERNAL_FRAME): return False displayStyle = self._getDisplayStyle(obj) if "inline" not in displayStyle: return False return self.documentForObject(obj) is not None def isInlineIframeDescendant(self, obj): if not obj: return False rv = self._isInlineIframeDescendant.get(hash(obj)) if rv is not None: return rv ancestor = pyatspi.findAncestor(obj, self.isInlineIframe) rv = ancestor is not None self._isInlineIframeDescendant[hash(obj)] = rv return rv def isInlineSuggestion(self, obj): if not self.isContentSuggestion(obj): return False displayStyle = self._getDisplayStyle(obj) return "inline" in displayStyle def isFirstItemInInlineContentSuggestion(self, obj): suggestion = pyatspi.findAncestor(obj, self.isInlineSuggestion) if not (suggestion and suggestion.childCount): return False return suggestion[0] == obj def isLastItemInInlineContentSuggestion(self, obj): suggestion = pyatspi.findAncestor(obj, self.isInlineSuggestion) if not (suggestion and suggestion.childCount): return False return suggestion[-1] == obj def speakMathSymbolNames(self, obj=None): obj = obj or orca_state.locusOfFocus return self.isMath(obj) def isInMath(self): return self.isMath(orca_state.locusOfFocus) def isMath(self, obj): tag = self._getTag(obj) rv = tag in ['math', 'maction', 'maligngroup', 'malignmark', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mlongdiv', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot', 'mrow', 'ms', 'mscarries', 'mscarry', 'msgroup', 'msline', 'mspace', 'msqrt', 'msrow', 'mstack', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover'] return rv def isNoneElement(self, obj): return self._getTag(obj) == 'none' def isMathLayoutOnly(self, obj): return self._getTag(obj) in ['mrow', 'mstyle', 'merror', 'mpadded'] def isMathMultiline(self, obj): return self._getTag(obj) in ['mtable', 'mstack', 'mlongdiv'] def isMathEnclose(self, obj): return self._getTag(obj) == 'menclose' def isMathFenced(self, obj): return self._getTag(obj) == 'mfenced' def isMathFractionWithoutBar(self, obj): try: role = obj.getRole() except: msg = "ERROR: Exception getting role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) if role != pyatspi.ROLE_MATH_FRACTION: return False attrs = self.objectAttributes(obj) linethickness = attrs.get('linethickness') if not linethickness: return False for char in linethickness: if char.isnumeric() and char != '0': return False return True def isMathPhantom(self, obj): return self._getTag(obj) == 'mphantom' def isMathMultiScript(self, obj): return self._getTag(obj) == 'mmultiscripts' def _isMathPrePostScriptSeparator(self, obj): return self._getTag(obj) == 'mprescripts' def isMathSubOrSuperScript(self, obj): return self._getTag(obj) in ['msub', 'msup', 'msubsup'] def isMathTable(self, obj): return self._getTag(obj) == 'mtable' def isMathTableRow(self, obj): return self._getTag(obj) in ['mtr', 'mlabeledtr'] def isMathTableCell(self, obj): return self._getTag(obj) == 'mtd' def isMathUnderOrOverScript(self, obj): return self._getTag(obj) in ['mover', 'munder', 'munderover'] def _isMathSubElement(self, obj): return self._getTag(obj) == 'msub' def _isMathSupElement(self, obj): return self._getTag(obj) == 'msup' def _isMathSubsupElement(self, obj): return self._getTag(obj) == 'msubsup' def _isMathUnderElement(self, obj): return self._getTag(obj) == 'munder' def _isMathOverElement(self, obj): return self._getTag(obj) == 'mover' def _isMathUnderOverElement(self, obj): return self._getTag(obj) == 'munderover' def isMathSquareRoot(self, obj): return self._getTag(obj) == 'msqrt' def isMathToken(self, obj): return self._getTag(obj) in ['mi', 'mn', 'mo', 'mtext', 'ms', 'mspace'] def isMathTopLevel(self, obj): return obj.getRole() == pyatspi.ROLE_MATH def getMathAncestor(self, obj): if not self.isMath(obj): return None if self.isMathTopLevel(obj): return obj return pyatspi.findAncestor(obj, self.isMathTopLevel) def getMathDenominator(self, obj): try: return obj[1] except: pass return None def getMathNumerator(self, obj): try: return obj[0] except: pass return None def getMathRootBase(self, obj): if self.isMathSquareRoot(obj): return obj try: return obj[0] except: pass return None def getMathRootIndex(self, obj): try: return obj[1] except: pass return None def getMathScriptBase(self, obj): if self.isMathSubOrSuperScript(obj) \ or self.isMathUnderOrOverScript(obj) \ or self.isMathMultiScript(obj): return obj[0] return None def getMathScriptSubscript(self, obj): if self._isMathSubElement(obj) or self._isMathSubsupElement(obj): return obj[1] return None def getMathScriptSuperscript(self, obj): if self._isMathSupElement(obj): return obj[1] if self._isMathSubsupElement(obj): return obj[2] return None def getMathScriptUnderscript(self, obj): if self._isMathUnderElement(obj) or self._isMathUnderOverElement(obj): return obj[1] return None def getMathScriptOverscript(self, obj): if self._isMathOverElement(obj): return obj[1] if self._isMathUnderOverElement(obj): return obj[2] return None def _getMathPrePostScriptSeparator(self, obj): for child in obj: if self._isMathPrePostScriptSeparator(child): return child return None def getMathPrescripts(self, obj): separator = self._getMathPrePostScriptSeparator(obj) if not separator: return [] index = separator.getIndexInParent() return [obj[i] for i in range(index+1, obj.childCount)] def getMathPostscripts(self, obj): separator = self._getMathPrePostScriptSeparator(obj) if separator: index = separator.getIndexInParent() else: index = obj.childCount return [obj[i] for i in range(1, index)] def getMathEnclosures(self, obj): if not self.isMathEnclose(obj): return [] attrs = self.objectAttributes(obj) return attrs.get('notation', 'longdiv').split() def getMathFencedSeparators(self, obj): if not self.isMathFenced(obj): return [''] attrs = self.objectAttributes(obj) return list(attrs.get('separators', ',')) def getMathFences(self, obj): if not self.isMathFenced(obj): return ['', ''] attrs = self.objectAttributes(obj) return [attrs.get('open', '('), attrs.get('close', ')')] def getMathNestingLevel(self, obj, test=None): rv = self._mathNestingLevel.get(hash(obj)) if rv is not None: return rv if not test: test = lambda x: self._getTag(x) == self._getTag(obj) rv = -1 ancestor = obj while ancestor: ancestor = pyatspi.findAncestor(ancestor, test) rv += 1 self._mathNestingLevel[hash(obj)] = rv return rv def filterContentsForPresentation(self, contents, inferLabels=False): def _include(x): obj, start, end, string = x if not obj: return False rv = self._shouldFilter.get(hash(obj)) if rv is not None: return rv displayedText = string or obj.name rv = True if ((self.isTextBlockElement(obj) or self.isLink(obj)) and not displayedText) \ or (self.isContentEditableWithEmbeddedObjects(obj) and not string.strip()) \ or self.isEmptyAnchor(obj) \ or (self.hasNoSize(obj) and not displayedText) \ or self.isHidden(obj) \ or self.isOffScreenLabel(obj) \ or self.isUselessImage(obj) \ or self.isErrorForContents(obj, contents) \ or self.isLabellingContents(obj, contents): rv = False elif obj.getRole() == pyatspi.ROLE_TABLE_ROW: rv = self.hasExplicitName(obj) else: widget = self.isInferredLabelForContents(x, contents) alwaysFilter = [pyatspi.ROLE_RADIO_BUTTON, pyatspi.ROLE_CHECK_BOX] if widget and (inferLabels or widget.getRole() in alwaysFilter): rv = False self._shouldFilter[hash(obj)] = rv return rv if len(contents) == 1: return contents rv = list(filter(_include, contents)) self._shouldFilter = {} return rv def needsSeparator(self, lastChar, nextChar): if lastChar.isspace() or nextChar.isspace(): return False openingPunctuation = ["(", "[", "{", "<"] closingPunctuation = [".", "?", "!", ":", ",", ";", ")", "]", "}", ">"] if lastChar in closingPunctuation or nextChar in openingPunctuation: return True if lastChar in openingPunctuation or nextChar in closingPunctuation: return False return lastChar.isalnum() def supportsSelectionAndTable(self, obj): interfaces = pyatspi.listInterfaces(obj) return 'Table' in interfaces and 'Selection' in interfaces def isGridDescendant(self, obj): if not obj: return False rv = self._isGridDescendant.get(hash(obj)) if rv is not None: return rv rv = pyatspi.findAncestor(obj, self.supportsSelectionAndTable) is not None self._isGridDescendant[hash(obj)] = rv return rv def isSorted(self, obj): attrs = self.objectAttributes(obj, False) return not attrs.get("sort") in ("none", None) def isAscending(self, obj): attrs = self.objectAttributes(obj, False) return attrs.get("sort") == "ascending" def isDescending(self, obj): attrs = self.objectAttributes(obj, False) return attrs.get("sort") == "descending" def _rowAndColumnIndices(self, obj): rowindex = colindex = None attrs = self.objectAttributes(obj) rowindex = attrs.get('rowindex') colindex = attrs.get('colindex') if rowindex is not None and colindex is not None: return rowindex, colindex isRow = lambda x: x and x.getRole() == pyatspi.ROLE_TABLE_ROW row = pyatspi.findAncestor(obj, isRow) if not row: return rowindex, colindex attrs = self.objectAttributes(row) rowindex = attrs.get('rowindex', rowindex) colindex = attrs.get('colindex', colindex) return rowindex, colindex def isCellWithNameFromHeader(self, obj): role = obj.getRole() if role != pyatspi.ROLE_TABLE_CELL: return False header = self.columnHeaderForCell(obj) if header and header.name and header.name == obj.name: return True header = self.rowHeaderForCell(obj) if header and header.name and header.name == obj.name: return True return False def labelForCellCoordinates(self, obj): attrs = self.objectAttributes(obj) # The ARIA feature is still in the process of being discussed. collabel = attrs.get('colindextext', attrs.get('coltext')) rowlabel = attrs.get('rowindextext', attrs.get('rowtext')) if collabel is not None and rowlabel is not None: return '%s%s' % (collabel, rowlabel) isRow = lambda x: x and x.getRole() == pyatspi.ROLE_TABLE_ROW row = pyatspi.findAncestor(obj, isRow) if not row: return '' attrs = self.objectAttributes(row) collabel = attrs.get('colindextext', attrs.get('coltext', collabel)) rowlabel = attrs.get('rowindextext', attrs.get('rowtext', rowlabel)) if collabel is not None and rowlabel is not None: return '%s%s' % (collabel, rowlabel) return '' def coordinatesForCell(self, obj): roles = [pyatspi.ROLE_TABLE_CELL, pyatspi.ROLE_TABLE_COLUMN_HEADER, pyatspi.ROLE_TABLE_ROW_HEADER, pyatspi.ROLE_COLUMN_HEADER, pyatspi.ROLE_ROW_HEADER] if not (obj and obj.getRole() in roles): return -1, -1 rowindex, colindex = self._rowAndColumnIndices(obj) if rowindex is not None and colindex is not None: return int(rowindex) - 1, int(colindex) - 1 return super().coordinatesForCell(obj) def rowAndColumnCount(self, obj): rows, cols = super().rowAndColumnCount(obj) attrs = self.objectAttributes(obj) rows = attrs.get('rowcount', rows) cols = attrs.get('colcount', cols) return int(rows), int(cols) def shouldReadFullRow(self, obj): if not (obj and self.inDocumentContent(obj)): return super().shouldReadFullRow(obj) if not super().shouldReadFullRow(obj): return False if self.isGridDescendant(obj): return not self._script.inFocusMode() if self.lastInputEventWasLineNav(): return False return True def isEntryDescendant(self, obj): if not obj: return False rv = self._isEntryDescendant.get(hash(obj)) if rv is not None: return rv isEntry = lambda x: x and x.getRole() == pyatspi.ROLE_ENTRY rv = pyatspi.findAncestor(obj, isEntry) is not None self._isEntryDescendant[hash(obj)] = rv return rv def isLabelDescendant(self, obj): if not obj: return False rv = self._isLabelDescendant.get(hash(obj)) if rv is not None: return rv isLabel = lambda x: x and x.getRole() == pyatspi.ROLE_LABEL rv = pyatspi.findAncestor(obj, isLabel) is not None self._isLabelDescendant[hash(obj)] = rv return rv def isMenuInCollapsedSelectElement(self, obj): return False def isMenuDescendant(self, obj): if not obj: return False rv = self._isMenuDescendant.get(hash(obj)) if rv is not None: return rv isMenu = lambda x: x and x.getRole() == pyatspi.ROLE_MENU rv = pyatspi.findAncestor(obj, isMenu) is not None self._isMenuDescendant[hash(obj)] = rv return rv def isNavigableToolTipDescendant(self, obj): if not obj: return False rv = self._isNavigableToolTipDescendant.get(hash(obj)) if rv is not None: return rv isToolTip = lambda x: x and x.getRole() == pyatspi.ROLE_TOOL_TIP if isToolTip(obj): ancestor = obj else: ancestor = pyatspi.findAncestor(obj, isToolTip) rv = ancestor and not self.isNonNavigablePopup(ancestor) self._isNavigableToolTipDescendant[hash(obj)] = rv return rv def isToolBarDescendant(self, obj): if not obj: return False rv = self._isToolBarDescendant.get(hash(obj)) if rv is not None: return rv isToolBar = lambda x: x and x.getRole() == pyatspi.ROLE_TOOL_BAR rv = pyatspi.findAncestor(obj, isToolBar) is not None self._isToolBarDescendant[hash(obj)] = rv return rv def isWebAppDescendant(self, obj): if not obj: return False rv = self._isWebAppDescendant.get(hash(obj)) if rv is not None: return rv isEmbedded = lambda x: x and x.getRole() == pyatspi.ROLE_EMBEDDED rv = pyatspi.findAncestor(obj, isEmbedded) is not None self._isWebAppDescendant[hash(obj)] = rv return rv def isLayoutOnly(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isLayoutOnly(obj) rv = self._isLayoutOnly.get(hash(obj)) if rv is not None: if rv: msg = "WEB: %s is deemed to be layout only" % obj debug.println(debug.LEVEL_INFO, msg, True) return rv try: role = obj.getRole() state = obj.getState() except: msg = "ERROR: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if role == pyatspi.ROLE_LIST: rv = self.treatAsDiv(obj) elif self.isMath(obj): rv = False elif self.isLandmark(obj): rv = False elif self.isContentDeletion(obj): rv = False elif self.isContentInsertion(obj): rv = False elif self.isContentMarked(obj): rv = False elif self.isContentSuggestion(obj): rv = False elif self.isDPub(obj): rv = False elif self.isFeed(obj): rv = False elif self.isFigure(obj): rv = False elif role in [pyatspi.ROLE_COLUMN_HEADER, pyatspi.ROLE_ROW_HEADER]: rv = False elif role == pyatspi.ROLE_PANEL: rv = not self.hasExplicitName(obj) elif role == pyatspi.ROLE_TABLE_ROW and not state.contains(pyatspi.STATE_EXPANDABLE): rv = not self.hasExplicitName(obj) else: rv = super().isLayoutOnly(obj) if rv: msg = "WEB: %s is deemed to be layout only" % obj debug.println(debug.LEVEL_INFO, msg, True) self._isLayoutOnly[hash(obj)] = rv return rv def elementIsPreformattedText(self, obj): if self._getTag(obj) in ["pre", "code"]: return True if "code" in self._getXMLRoles(obj): return True return False def elementLinesAreSingleWords(self, obj): if not (obj and self.inDocumentContent(obj)): return False if self.elementIsPreformattedText(obj): return False rv = self._elementLinesAreSingleWords.get(hash(obj)) if rv is not None: return rv text = self.queryNonEmptyText(obj) if not text: return False try: nChars = text.characterCount except: return False if not nChars: return False try: obj.clearCache() state = obj.getState() except: msg = "ERROR: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False tokens = list(filter(lambda x: x, re.split(r"[\s\ufffc]", text.getText(0, -1)))) # Note: We cannot check for the editable-text interface, because Gecko # seems to be exposing that for non-editable things. Thanks Gecko. rv = not state.contains(pyatspi.STATE_EDITABLE) and len(tokens) > 1 if rv: boundary = pyatspi.TEXT_BOUNDARY_LINE_START i = 0 while i < nChars: string, start, end = text.getTextAtOffset(i, boundary) if len(string.split()) != 1: rv = False break i = max(i+1, end) self._elementLinesAreSingleWords[hash(obj)] = rv return rv def elementLinesAreSingleChars(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._elementLinesAreSingleChars.get(hash(obj)) if rv is not None: return rv text = self.queryNonEmptyText(obj) if not text: return False try: nChars = text.characterCount except: return False if not nChars: return False # If we have a series of embedded object characters, there's a reasonable chance # they'll look like the one-char-per-line CSSified text we're trying to detect. # We don't want that false positive. By the same token, the one-char-per-line # CSSified text we're trying to detect can have embedded object characters. So # if we have more than 30% EOCs, don't use this workaround. (The 30% is based on # testing with problematic text.) eocs = re.findall(self.EMBEDDED_OBJECT_CHARACTER, text.getText(0, -1)) if len(eocs)/nChars > 0.3: return False try: obj.clearCache() state = obj.getState() except: msg = "ERROR: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False # Note: We cannot check for the editable-text interface, because Gecko # seems to be exposing that for non-editable things. Thanks Gecko. rv = not state.contains(pyatspi.STATE_EDITABLE) if rv: boundary = pyatspi.TEXT_BOUNDARY_LINE_START for i in range(nChars): string, start, end = text.getTextAtOffset(i, boundary) if len(string) != 1: rv = False break self._elementLinesAreSingleChars[hash(obj)] = rv return rv def isOffScreenLabel(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isOffScreenLabel.get(hash(obj)) if rv is not None: return rv rv = False isLabelFor = lambda x: x.getRelationType() == pyatspi.RELATION_LABEL_FOR try: relationSet = obj.getRelationSet() except: pass else: relations = list(filter(isLabelFor, relationSet)) if relations: try: text = obj.queryText() end = text.characterCount except: end = 1 x, y, width, height = self.getExtents(obj, 0, end) if x < 0 or y < 0: rv = True self._isOffScreenLabel[hash(obj)] = rv return rv def isDetachedDocument(self, obj): docRoles = [pyatspi.ROLE_DOCUMENT_FRAME, pyatspi.ROLE_DOCUMENT_WEB] if (obj and obj.getRole() in docRoles): if obj.parent is None or self.isZombie(obj.parent): msg = "WEB: %s is a detached document" % obj debug.println(debug.LEVEL_INFO, msg, True) return True return False def iframeForDetachedDocument(self, obj, root=None): root = root or self.documentFrame() isIframe = lambda x: x and x.getRole() == pyatspi.ROLE_INTERNAL_FRAME iframes = self.findAllDescendants(root, isIframe) for iframe in iframes: if obj in iframe: # We won't change behavior, but we do want to log all bogosity. self._isBrokenChildParentTree(obj, iframe) msg = "WEB: Returning %s as iframe parent of detached %s" % (iframe, obj) debug.println(debug.LEVEL_INFO, msg, True) return iframe return None def _objectBoundsMightBeBogus(self, obj): if not (obj and self.inDocumentContent(obj)): return super()._objectBoundsMightBeBogus(obj) if obj.getRole() != pyatspi.ROLE_LINK or "Text" not in pyatspi.listInterfaces(obj): return False text = obj.queryText() start = list(text.getRangeExtents(0, 1, 0)) end = list(text.getRangeExtents(text.characterCount - 1, text.characterCount, 0)) if self.extentsAreOnSameLine(start, end): return False if not self.hasPresentableText(obj.parent): return False msg = "WEB: Objects bounds of %s might be bogus" % obj debug.println(debug.LEVEL_INFO, msg, True) return True def _isBrokenChildParentTree(self, child, parent): if not (child and parent): return False try: childIsChildOfParent = child in parent except: msg = "WEB: Exception checking if %s is in %s" % (child, parent) debug.println(debug.LEVEL_INFO, msg, True) childIsChildOfParent = False else: msg = "WEB: %s is child of %s: %s" % (child, parent, childIsChildOfParent) debug.println(debug.LEVEL_INFO, msg, True) try: parentIsParentOfChild = child.parent == parent except: msg = "WEB: Exception getting parent of %s" % child debug.println(debug.LEVEL_INFO, msg, True) parentIsParentOfChild = False else: msg = "WEB: %s is parent of %s: %s" % (parent, child, parentIsParentOfChild) debug.println(debug.LEVEL_INFO, msg, True) if parentIsParentOfChild != childIsChildOfParent: msg = "FAIL: The above is broken and likely needs to be fixed by the toolkit." debug.println(debug.LEVEL_INFO, msg, True) return True return False def labelTargets(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._labelTargets.get(hash(obj)) if rv is not None: return rv rv = False isLabel = lambda r: r.getRelationType() == pyatspi.RELATION_LABEL_FOR try: relations = list(filter(isLabel, obj.getRelationSet())) except: msg = "WEB: Exception getting relations of %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return [] if not relations: return [] r = relations[0] rv = [r.getTarget(i) for i in range(r.getNTargets())] rv = [hash(x) for x in rv if x is not None] self._labelTargets[hash(obj)] = rv return rv def isLinkAncestorOfImageInContents(self, link, contents): if not self.isLink(link): return False for obj, start, end, string in contents: if obj.getRole() != pyatspi.ROLE_IMAGE: continue if pyatspi.findAncestor(obj, lambda x: x == link): return True return False def isInferredLabelForContents(self, content, contents): obj, start, end, string = content objs = list(filter(self.shouldInferLabelFor, [x[0] for x in contents])) if not objs: return None for o in objs: label, sources = self.inferLabelFor(o) if obj in sources and label.strip() == string.strip(): return o return None def isLabellingContents(self, obj, contents=[]): if self.isFocusModeWidget(obj): return False targets = self.labelTargets(obj) if not contents: return bool(targets) for acc, start, end, string in contents: if hash(acc) in targets: return True if not self.isTextBlockElement(obj): return False if not self.isLabelDescendant(obj): return False for acc, start, end, string in contents: if not self.isLabelDescendant(acc) or self.isTextBlockElement(acc): continue ancestor = self.commonAncestor(acc, obj) if ancestor and ancestor.getRole() == pyatspi.ROLE_LABEL: return True return False def isAnchor(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isAnchor.get(hash(obj)) if rv is not None: return rv rv = False if obj.getRole() == pyatspi.ROLE_LINK \ and not obj.getState().contains(pyatspi.STATE_FOCUSABLE) \ and not 'jump' in self._getActionNames(obj) \ and not self._getXMLRoles(obj): rv = True self._isAnchor[hash(obj)] = rv return rv def isEmptyAnchor(self, obj): if not self.isAnchor(obj): return False return self.queryNonEmptyText(obj) is None def isBrowserUIAlert(self, obj): if not (obj and obj.getRole() == pyatspi.ROLE_ALERT): return False if self.inDocumentContent(obj): return False return True def isTopLevelBrowserUIAlert(self, obj): if not self.isBrowserUIAlert(obj): return False parent = obj.parent while parent and self.isLayoutOnly(parent): parent = parent.parent return parent.getRole() == pyatspi.ROLE_FRAME def _getActionNames(self, obj): try: action = obj.queryAction() names = [action.getName(i).lower() for i in range(action.nActions)] except NotImplementedError: return [] except: msg = "WEB: Exception getting actions for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return [] return list(filter(lambda x: x, names)) def isClickableElement(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isClickableElement.get(hash(obj)) if rv is not None: return rv rv = False if not obj.getState().contains(pyatspi.STATE_FOCUSABLE) \ and not self.isFocusModeWidget(obj): names = self._getActionNames(obj) rv = "click" in names if rv and not obj.name and "Text" in pyatspi.listInterfaces(obj): string = obj.queryText().getText(0, -1) if not string.strip(): rv = obj.getRole() not in [pyatspi.ROLE_STATIC, pyatspi.ROLE_LINK] self._isClickableElement[hash(obj)] = rv return rv def isCodeDescendant(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isCodeDescendant(obj) rv = self._isCodeDescendant.get(hash(obj)) if rv is not None: return rv rv = pyatspi.findAncestor(obj, self.isCode) is not None self._isCodeDescendant[hash(obj)] = rv return rv def isCode(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isCode(obj) return self._getTag(obj) == "code" or "code" in self._getXMLRoles(obj) def getComboBoxValue(self, obj): attrs = self.objectAttributes(obj, False) return attrs.get("valuetext", super().getComboBoxValue(obj)) def isEditableComboBox(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isEditableComboBox(obj) rv = self._isEditableComboBox.get(hash(obj)) if rv is not None: return rv try: role = obj.getRole() state = obj.getState() except: msg = "ERROR: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False rv = False if role == pyatspi.ROLE_COMBO_BOX: rv = state.contains(pyatspi.STATE_EDITABLE) self._isEditableComboBox[hash(obj)] = rv return rv def isDPub(self, obj): if not (obj and self.inDocumentContent(obj)): return False roles = self._getXMLRoles(obj) rv = bool(list(filter(lambda x: x.startswith("doc-"), roles))) return rv def isDPubAbstract(self, obj): return 'doc-abstract' in self._getXMLRoles(obj) def isDPubAcknowledgments(self, obj): return 'doc-acknowledgments' in self._getXMLRoles(obj) def isDPubAfterword(self, obj): return 'doc-afterword' in self._getXMLRoles(obj) def isDPubAppendix(self, obj): return 'doc-appendix' in self._getXMLRoles(obj) def isDPubBacklink(self, obj): return 'doc-backlink' in self._getXMLRoles(obj) def isDPubBiblioref(self, obj): return 'doc-biblioref' in self._getXMLRoles(obj) def isDPubBibliography(self, obj): return 'doc-bibliography' in self._getXMLRoles(obj) def isDPubChapter(self, obj): return 'doc-chapter' in self._getXMLRoles(obj) def isDPubColophon(self, obj): return 'doc-colophon' in self._getXMLRoles(obj) def isDPubConclusion(self, obj): return 'doc-conclusion' in self._getXMLRoles(obj) def isDPubCover(self, obj): return 'doc-cover' in self._getXMLRoles(obj) def isDPubCredit(self, obj): return 'doc-credit' in self._getXMLRoles(obj) def isDPubCredits(self, obj): return 'doc-credits' in self._getXMLRoles(obj) def isDPubDedication(self, obj): return 'doc-dedication' in self._getXMLRoles(obj) def isDPubEndnote(self, obj): return 'doc-endnote' in self._getXMLRoles(obj) def isDPubEndnotes(self, obj): return 'doc-endnotes' in self._getXMLRoles(obj) def isDPubEpigraph(self, obj): return 'doc-epigraph' in self._getXMLRoles(obj) def isDPubEpilogue(self, obj): return 'doc-epilogue' in self._getXMLRoles(obj) def isDPubErrata(self, obj): return 'doc-errata' in self._getXMLRoles(obj) def isDPubExample(self, obj): return 'doc-example' in self._getXMLRoles(obj) def isDPubFootnote(self, obj): return 'doc-footnote' in self._getXMLRoles(obj) def isDPubForeword(self, obj): return 'doc-foreword' in self._getXMLRoles(obj) def isDPubGlossary(self, obj): return 'doc-glossary' in self._getXMLRoles(obj) def isDPubGlossref(self, obj): return 'doc-glossref' in self._getXMLRoles(obj) def isDPubIndex(self, obj): return 'doc-index' in self._getXMLRoles(obj) def isDPubIntroduction(self, obj): return 'doc-introduction' in self._getXMLRoles(obj) def isDPubNoteref(self, obj): return 'doc-noteref' in self._getXMLRoles(obj) def isDPubPagelist(self, obj): return 'doc-pagelist' in self._getXMLRoles(obj) def isDPubPagebreak(self, obj): return 'doc-pagebreak' in self._getXMLRoles(obj) def isDPubPart(self, obj): return 'doc-part' in self._getXMLRoles(obj) def isDPubPreface(self, obj): return 'doc-preface' in self._getXMLRoles(obj) def isDPubPrologue(self, obj): return 'doc-prologue' in self._getXMLRoles(obj) def isDPubPullquote(self, obj): return 'doc-pullquote' in self._getXMLRoles(obj) def isDPubQna(self, obj): return 'doc-qna' in self._getXMLRoles(obj) def isDPubSubtitle(self, obj): return 'doc-subtitle' in self._getXMLRoles(obj) def isDPubToc(self, obj): return 'doc-toc' in self._getXMLRoles(obj) def isErrorMessage(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isErrorMessage(obj) rv = self._isErrorMessage.get(hash(obj)) if rv is not None: return rv # Remove this when we bump dependencies to 2.26 try: relationType = pyatspi.RELATION_ERROR_FOR except: rv = False else: isMessage = lambda r: r.getRelationType() == relationType rv = bool(list(filter(isMessage, obj.getRelationSet()))) self._isErrorMessage[hash(obj)] = rv return rv def isFakePlaceholderForEntry(self, obj): if not (obj and self.inDocumentContent(obj) and obj.parent): return False if not (obj.parent.getRole() == pyatspi.ROLE_ENTRY and obj.parent.name): return False def _isMatch(x): try: role = x.getRole() string = x.queryText().getText(0, -1).strip() except: return False return role in [pyatspi.ROLE_SECTION, pyatspi.ROLE_STATIC] and obj.parent.name == string if _isMatch(obj): return True return pyatspi.findDescendant(obj, _isMatch) is not None def isInlineListItem(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isInlineListItem.get(hash(obj)) if rv is not None: return rv if obj.getRole() != pyatspi.ROLE_LIST_ITEM: rv = False else: displayStyle = self._getDisplayStyle(obj) rv = displayStyle and "inline" in displayStyle self._isInlineListItem[hash(obj)] = rv return rv def isBlockListDescendant(self, obj): if not self.isListDescendant(obj): return False return not self.isInlineListDescendant(obj) def isListDescendant(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isListDescendant.get(hash(obj)) if rv is not None: return rv isList = lambda x: x and x.getRole() == pyatspi.ROLE_LIST ancestor = pyatspi.findAncestor(obj, isList) rv = ancestor is not None self._isListDescendant[hash(obj)] = rv return rv def isInlineListDescendant(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isInlineListDescendant.get(hash(obj)) if rv is not None: return rv if self.isInlineListItem(obj): rv = True else: ancestor = pyatspi.findAncestor(obj, self.isInlineListItem) rv = ancestor is not None self._isInlineListDescendant[hash(obj)] = rv return rv def listForInlineListDescendant(self, obj): if not self.isInlineListDescendant(obj): return None isList = lambda x: x and x.getRole() == pyatspi.ROLE_LIST return pyatspi.findAncestor(obj, isList) def isFeed(self, obj): return 'feed' in self._getXMLRoles(obj) def isFigure(self, obj): return 'figure' in self._getXMLRoles(obj) def isLandmark(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isLandmark.get(hash(obj)) if rv is not None: return rv if obj.getRole() == pyatspi.ROLE_LANDMARK: rv = True elif self.isLandmarkRegion(obj): rv = bool(obj.name) else: roles = self._getXMLRoles(obj) rv = bool(list(filter(lambda x: x in self.getLandmarkTypes(), roles))) self._isLandmark[hash(obj)] = rv return rv def isLandmarkWithoutType(self, obj): roles = self._getXMLRoles(obj) return not roles def isLandmarkBanner(self, obj): return 'banner' in self._getXMLRoles(obj) def isLandmarkComplementary(self, obj): return 'complementary' in self._getXMLRoles(obj) def isLandmarkContentInfo(self, obj): return 'contentinfo' in self._getXMLRoles(obj) def isLandmarkForm(self, obj): return 'form' in self._getXMLRoles(obj) def isLandmarkMain(self, obj): return 'main' in self._getXMLRoles(obj) def isLandmarkNavigation(self, obj): return 'navigation' in self._getXMLRoles(obj) def isLandmarkRegion(self, obj): return 'region' in self._getXMLRoles(obj) def isLandmarkSearch(self, obj): return 'search' in self._getXMLRoles(obj) def isLiveRegion(self, obj): if not (obj and self.inDocumentContent(obj)): return False attrs = self.objectAttributes(obj) return 'container-live' in attrs def isLink(self, obj): if not obj: return False rv = self._isLink.get(hash(obj)) if rv is not None: return rv role = obj.getRole() if role == pyatspi.ROLE_LINK and not self.isAnchor(obj): rv = True elif role == pyatspi.ROLE_STATIC \ and obj.parent.getRole() == pyatspi.ROLE_LINK \ and obj.name and obj.name == obj.parent.name: rv = True else: rv = False self._isLink[hash(obj)] = rv return rv def isNonNavigablePopup(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isNonNavigablePopup.get(hash(obj)) if rv is not None: return rv rv = obj.getRole() == pyatspi.ROLE_TOOL_TIP \ and not obj.getState().contains(pyatspi.STATE_FOCUSABLE) self._isNonNavigablePopup[hash(obj)] = rv return rv def hasUselessCanvasDescendant(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._hasUselessCanvasDescendant.get(hash(obj)) if rv is not None: return rv isCanvas = lambda x: x and x.getRole() == pyatspi.ROLE_CANVAS canvases = self.findAllDescendants(obj, isCanvas) rv = len(list(filter(self.isUselessImage, canvases))) > 0 self._hasUselessCanvasDescendant[hash(obj)] = rv return rv def isSwitch(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isSwitch(obj) return 'switch' in self._getXMLRoles(obj) def isNonNavigableEmbeddedDocument(self, obj): rv = self._isNonNavigableEmbeddedDocument.get(hash(obj)) if rv is not None: return rv rv = False if self.isDocument(obj) and self.getDocumentForObject(obj): try: name = obj.name except: rv = True else: rv = "doubleclick" in name self._isNonNavigableEmbeddedDocument[hash(obj)] = rv return rv def isRedundantSVG(self, obj): if self._getTag(obj) != 'svg' or obj.parent.childCount == 1: return False rv = self._isRedundantSVG.get(hash(obj)) if rv is not None: return rv rv = False children = [x for x in obj.parent if self._getTag(x) == 'svg'] if len(children) == obj.parent.childCount: sortedChildren = sorted(children, key=functools.cmp_to_key(self.sizeComparison)) if obj != sortedChildren[-1]: objExtents = self.getExtents(obj, 0, -1) largestExtents = self.getExtents(sortedChildren[-1], 0, -1) rv = self.intersection(objExtents, largestExtents) == tuple(objExtents) self._isRedundantSVG[hash(obj)] = rv return rv def isUselessImage(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isUselessImage.get(hash(obj)) if rv is not None: return rv rv = True if obj.getRole() not in [pyatspi.ROLE_IMAGE, pyatspi.ROLE_CANVAS] \ and self._getTag(obj) != 'svg': rv = False if rv and (obj.name or obj.description): rv = False if rv and (self.isClickableElement(obj) or self.hasLongDesc(obj)): rv = False if rv and obj.getState().contains(pyatspi.STATE_FOCUSABLE): rv = False if rv and obj.parent.getRole() == pyatspi.ROLE_LINK: uri = self.uri(obj.parent) if uri and not uri.startswith('javascript'): rv = False if rv and 'Image' in pyatspi.listInterfaces(obj): image = obj.queryImage() if image.imageDescription: rv = False elif not self.hasExplicitName(obj) and not self.isRedundantSVG(obj): width, height = image.getImageSize() if width > 25 and height > 25: rv = False if rv and 'Text' in pyatspi.listInterfaces(obj): rv = self.queryNonEmptyText(obj) is None if rv and obj.childCount: for i in range(min(obj.childCount, 50)): if not self.isUselessImage(obj[i]): rv = False break self._isUselessImage[hash(obj)] = rv return rv def hasValidName(self, obj): if not obj.name: return False if len(obj.name.split()) > 1: return True parsed = urllib.parse.parse_qs(obj.name) if len(parsed) > 2: msg = "WEB: name of %s is suspected query string" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if len(obj.name) == 1 and ord(obj.name) in range(0xe000, 0xf8ff): msg = "WEB: name of %s is in unicode private use area" % obj debug.println(debug.LEVEL_INFO, msg, True) return False return True def isUselessEmptyElement(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isUselessEmptyElement.get(hash(obj)) if rv is not None: return rv try: role = obj.getRole() state = obj.getState() interfaces = pyatspi.listInterfaces(obj) except: msg = "WEB: Exception getting role, state, and interfaces for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False roles = [pyatspi.ROLE_PARAGRAPH, pyatspi.ROLE_SECTION, pyatspi.ROLE_STATIC, pyatspi.ROLE_TABLE_ROW] if role not in roles: rv = False elif state.contains(pyatspi.STATE_FOCUSABLE) or state.contains(pyatspi.STATE_FOCUSED): rv = False elif state.contains(pyatspi.STATE_EDITABLE): rv = False elif self.hasValidName(obj) or obj.description or obj.childCount: rv = False elif "Text" in interfaces and obj.queryText().characterCount \ and obj.queryText().getText(0, -1) != obj.name: rv = False elif "Action" in interfaces and self._getActionNames(obj): rv = False else: rv = True self._isUselessEmptyElement[hash(obj)] = rv return rv def isParentOfNullChild(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isParentOfNullChild.get(hash(obj)) if rv is not None: return rv rv = False try: childCount = obj.childCount except: msg = "WEB: Exception getting childCount for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) childCount = 0 if childCount and obj[0] is None: msg = "ERROR: %s reports %i children, but obj[0] is None" % (obj, childCount) debug.println(debug.LEVEL_INFO, msg, True) rv = True self._isParentOfNullChild[hash(obj)] = rv return rv def hasExplicitName(self, obj): if not (obj and self.inDocumentContent(obj)): return False attrs = self.objectAttributes(obj) return attrs.get('explicit-name') == 'true' def hasLongDesc(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._hasLongDesc.get(hash(obj)) if rv is not None: return rv names = self._getActionNames(obj) rv = "showlongdesc" in names self._hasLongDesc[hash(obj)] = rv return rv def hasDetails(self, obj): if not (obj and self.inDocumentContent(obj)): return super().hasDetails(obj) rv = self._hasDetails.get(hash(obj)) if rv is not None: return rv try: relations = obj.getRelationSet() except: msg = 'ERROR: Exception getting relationset for %s' % obj debug.println(debug.LEVEL_INFO, msg, True) return False rv = False relation = filter(lambda x: x.getRelationType() == pyatspi.RELATION_DETAILS, relations) for r in relation: if r.getNTargets() > 0: rv = True break self._hasDetails[hash(obj)] = rv return rv def detailsIn(self, obj): if not self.hasDetails(obj): return [] try: relations = obj.getRelationSet() except: msg = 'ERROR: Exception getting relationset for %s' % obj debug.println(debug.LEVEL_INFO, msg, True) return [] rv = [] relation = filter(lambda x: x.getRelationType() == pyatspi.RELATION_DETAILS, relations) for r in relation: for i in range(r.getNTargets()): rv.append(r.getTarget(i)) return rv def isDetails(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isDetails(obj) rv = self._isDetails.get(hash(obj)) if rv is not None: return rv try: relations = obj.getRelationSet() except: msg = 'ERROR: Exception getting relationset for %s' % obj debug.println(debug.LEVEL_INFO, msg, True) return False rv = False relation = filter(lambda x: x.getRelationType() == pyatspi.RELATION_DETAILS_FOR, relations) for r in relation: if r.getNTargets() > 0: rv = True break self._isDetails[hash(obj)] = rv return rv def detailsFor(self, obj): if not self.isDetails(obj): return [] try: relations = obj.getRelationSet() except: msg = 'ERROR: Exception getting relationset for %s' % obj debug.println(debug.LEVEL_INFO, msg, True) return [] rv = [] relation = filter(lambda x: x.getRelationType() == pyatspi.RELATION_DETAILS_FOR, relations) for r in relation: for i in range(r.getNTargets()): rv.append(r.getTarget(i)) return rv def popupType(self, obj): if not (obj and self.inDocumentContent(obj)): return 'false' attrs = self.objectAttributes(obj) return attrs.get('haspopup', 'false').lower() def inferLabelFor(self, obj): if not self.shouldInferLabelFor(obj): return None, [] rv = self._inferredLabels.get(hash(obj)) if rv is not None: return rv rv = self._script.labelInference.infer(obj, False) self._inferredLabels[hash(obj)] = rv return rv def shouldInferLabelFor(self, obj): if not self.inDocumentContent() or self.isWebAppDescendant(obj): return False rv = self._shouldInferLabelFor.get(hash(obj)) if rv and not self._script._lastCommandWasCaretNav: return not self._script.inSayAll() if rv == False: return rv try: role = obj.getRole() name = obj.name except: msg = "WEB: Exception getting role and name for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = False else: if name: rv = False elif not rv: roles = [pyatspi.ROLE_CHECK_BOX, pyatspi.ROLE_COMBO_BOX, pyatspi.ROLE_ENTRY, pyatspi.ROLE_LIST_BOX, pyatspi.ROLE_PASSWORD_TEXT, pyatspi.ROLE_RADIO_BUTTON] rv = role in roles and not self.displayedLabel(obj) self._shouldInferLabelFor[hash(obj)] = rv # TODO - JD: This is private. if self._script._lastCommandWasCaretNav \ and role not in [pyatspi.ROLE_RADIO_BUTTON, pyatspi.ROLE_CHECK_BOX]: return False return rv def displayedLabel(self, obj): if not (obj and self.inDocumentContent(obj)): return super().displayedLabel(obj) rv = self._displayedLabelText.get(hash(obj)) if rv is not None: return rv labels = self.labelsForObject(obj) strings = [l.name or self.displayedText(l) for l in labels if l is not None] rv = " ".join(strings) self._displayedLabelText[hash(obj)] = rv return rv def labelsForObject(self, obj): if not obj: return [] rv = self._actualLabels.get(hash(obj)) if rv is not None: return rv rv = super().labelsForObject(obj) if not self.inDocumentContent(obj): return rv rv = list(filter(lambda x: x and x.getRole() == pyatspi.ROLE_LABEL, rv)) self._actualLabels[hash(obj)] = rv return rv def isSpinnerEntry(self, obj): if not self.inDocumentContent(obj): return False if not obj.getState().contains(pyatspi.STATE_EDITABLE): return False if pyatspi.ROLE_SPIN_BUTTON in [obj.getRole(), obj.parent.getRole()]: return True return False def eventIsSpinnerNoise(self, event): if not self.isSpinnerEntry(event.source): return False if event.type.startswith("object:text-changed") \ or event.type.startswith("object:text-selection-changed"): lastKey, mods = self.lastKeyAndModifiers() if lastKey in ["Down", "Up"]: return True return False def treatEventAsSpinnerValueChange(self, event): if event.type.startswith("object:text-caret-moved") and self.isSpinnerEntry(event.source): lastKey, mods = self.lastKeyAndModifiers() if lastKey in ["Down", "Up"]: obj, offset = self.getCaretContext() return event.source == obj return False def eventIsBrowserUINoise(self, event): if self.inDocumentContent(event.source): return False try: role = event.source.getRole() except: msg = "WEB: Exception getting role for %s" % event.source debug.println(debug.LEVEL_INFO, msg, True) return False eType = event.type if eType.startswith("object:text-") or eType.endswith("accessible-name"): return role in [pyatspi.ROLE_STATUS_BAR, pyatspi.ROLE_LABEL] if eType.startswith("object:children-changed"): return True return False def eventIsAutocompleteNoise(self, event): if not self.inDocumentContent(event.source): return False isListBoxItem = lambda x: x and x.parent and x.parent.getRole() == pyatspi.ROLE_LIST_BOX isMenuItem = lambda x: x and x.parent and x.parent.getRole() == pyatspi.ROLE_MENU isComboBoxItem = lambda x: x and x.parent and x.parent.getRole() == pyatspi.ROLE_COMBO_BOX if event.source.getState().contains(pyatspi.STATE_EDITABLE) \ and event.type.startswith("object:text-"): obj, offset = self.getCaretContext() if isListBoxItem(obj) or isMenuItem(obj): return True if obj == event.source and isComboBoxItem(obj): lastKey, mods = self.lastKeyAndModifiers() if lastKey in ["Down", "Up"]: return True return False def eventIsBrowserUIAutocompleteNoise(self, event): if self.inDocumentContent(event.source): return False selection = ["object:selection-changed", "object:state-changed:selected"] if not event.type in selection: return False try: focusRole = orca_state.locusOfFocus.getRole() focusState = orca_state.locusOfFocus.getState() except: msg = "WEB: Exception getting role and state for %s" % orca_state.locusOfFocus debug.println(debug.LEVEL_INFO, msg, True) return False try: role = event.source.getRole() except: msg = "WEB: Exception getting role for %s" % event.source debug.println(debug.LEVEL_INFO, msg, True) return False if role in [pyatspi.ROLE_MENU, pyatspi.ROLE_MENU_ITEM] \ and focusRole == pyatspi.ROLE_ENTRY \ and focusState.contains(pyatspi.STATE_FOCUSED): lastKey, mods = self.lastKeyAndModifiers() if lastKey not in ["Down", "Up"]: return True return False def eventIsBrowserUIPageSwitch(self, event): selection = ["object:selection-changed", "object:state-changed:selected"] if not event.type in selection: return False roles = [pyatspi.ROLE_PAGE_TAB, pyatspi.ROLE_PAGE_TAB_LIST] if not event.source.getRole() in roles: return False if self.inDocumentContent(event.source): return False if not self.inDocumentContent(orca_state.locusOfFocus): return False return True def eventIsFromLocusOfFocusDocument(self, event): source = self.getDocumentForObject(event.source) focus = self.getDocumentForObject(orca_state.locusOfFocus) if not (source and focus): return False if source == focus: return True if self.isZombie(focus) and not self.isZombie(source): if self.activeDocument() == source: msg = "WEB: Treating active doc as locusOfFocus doc" debug.println(debug.LEVEL_INFO, msg, True) return True return False def textEventIsDueToDeletion(self, event): if not self.inDocumentContent(event.source) \ or not event.source.getState().contains(pyatspi.STATE_EDITABLE): return False if self.isDeleteCommandTextDeletionEvent(event) \ or self.isBackSpaceCommandTextDeletionEvent(event): return True return False def textEventIsDueToInsertion(self, event): if not event.type.startswith("object:text-"): return False if not self.inDocumentContent(event.source) \ or not event.source.getState().contains(pyatspi.STATE_EDITABLE) \ or not event.source == orca_state.locusOfFocus: return False if isinstance(orca_state.lastInputEvent, input_event.KeyboardEvent): inputEvent = orca_state.lastNonModifierKeyEvent return inputEvent and inputEvent.isPrintableKey() and not inputEvent.modifiers return False def textEventIsForNonNavigableTextObject(self, event): if not event.type.startswith("object:text-"): return False return self._treatObjectAsWhole(event.source) def eventIsEOCAdded(self, event): if not self.inDocumentContent(event.source): return False if event.type.startswith("object:text-changed:insert") \ and self.EMBEDDED_OBJECT_CHARACTER in event.any_data: return not re.match("[^\s\ufffc]", event.any_data) return False def caretMovedOutsideActiveGrid(self, event, oldFocus=None): if not (event and event.type.startswith("object:text-caret-moved")): return False oldFocus = oldFocus or orca_state.locusOfFocus if not self.isGridDescendant(oldFocus): return False return not self.isGridDescendant(event.source) def caretMovedToSamePageFragment(self, event, oldFocus=None): if not (event and event.type.startswith("object:text-caret-moved")): return False if event.source.getState().contains(pyatspi.STATE_EDITABLE): return False docURI = self.documentFrameURI() fragment = urllib.parse.urlparse(docURI).fragment if not fragment: return False sourceID = self._getID(event.source) if sourceID and fragment == sourceID: return True oldFocus = oldFocus or orca_state.locusOfFocus if self.isLink(oldFocus): link = oldFocus else: link = pyatspi.findAncestor(oldFocus, self.isLink) return link and self.uri(link) == docURI def isChildOfCurrentFragment(self, obj): parseResult = urllib.parse.urlparse(self.documentFrameURI()) if not parseResult.fragment: return False isSameFragment = lambda x: self._getID(x) == parseResult.fragment return pyatspi.findAncestor(obj, isSameFragment) is not None def documentFragment(self, documentFrame): parseResult = urllib.parse.urlparse(self.documentFrameURI(documentFrame)) return parseResult.fragment def isContentEditableWithEmbeddedObjects(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isContentEditableWithEmbeddedObjects.get(hash(obj)) if rv is not None: return rv rv = False try: state = obj.getState() role = obj.getRole() except: msg = "WEB: Exception getting state and role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return rv hasTextBlockRole = lambda x: x and x.getRole() in self._textBlockElementRoles() if role == pyatspi.ROLE_ENTRY and state.contains(pyatspi.STATE_MULTI_LINE): rv = pyatspi.findDescendant(obj, hasTextBlockRole) elif state.contains(pyatspi.STATE_EDITABLE): rv = hasTextBlockRole(obj) or self.isLink(obj) elif not self.isDocument(obj): document = self.getDocumentForObject(obj) rv = self.isContentEditableWithEmbeddedObjects(document) self._isContentEditableWithEmbeddedObjects[hash(obj)] = rv return rv def characterOffsetInParent(self, obj): start, end, length = self._rangeInParentWithLength(obj) return start def _rangeInParentWithLength(self, obj): if not obj: return -1, -1, 0 text = self.queryNonEmptyText(obj.parent) if not text: return -1, -1, 0 start, end = self.getHyperlinkRange(obj) return start, end, text.characterCount def getError(self, obj): if not (obj and self.inDocumentContent(obj)): return super().getError(obj) try: state = obj.getState() except: msg = "ERROR: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if not state.contains(pyatspi.STATE_INVALID_ENTRY): return False try: self._currentTextAttrs.pop(hash(obj)) except: pass attrs, start, end = self.textAttributes(obj, 0, True) error = attrs.get("invalid") if error == "false": return False if error not in ["spelling", "grammar"]: return True return error def _getErrorMessageContainer(self, obj): if not (obj and self.inDocumentContent(obj)): return None if not self.getError(obj): return None # Remove this when we bump dependencies to 2.26 try: relationType = pyatspi.RELATION_ERROR_MESSAGE except: return None isMessage = lambda r: r.getRelationType() == relationType relations = list(filter(isMessage, obj.getRelationSet())) if not relations: return None return relations[0].getTarget(0) def getErrorMessage(self, obj): return self.expandEOCs(self._getErrorMessageContainer(obj)) def isErrorForContents(self, obj, contents=[]): if not self.isErrorMessage(obj): return False for acc, start, end, string in contents: if self._getErrorMessageContainer(acc) == obj: return True return False def hasNoSize(self, obj): if not (obj and self.inDocumentContent(obj)): return super().hasNoSize(obj) rv = self._hasNoSize.get(hash(obj)) if rv is not None: return rv rv = super().hasNoSize(obj) self._hasNoSize[hash(obj)] = rv return rv def _canHaveCaretContext(self, obj): if not obj: return False if self.isDead(obj): msg = "WEB: Dead object cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isZombie(obj): msg = "WEB: Zombie object cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isHidden(obj): msg = "WEB: Hidden object cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isOffScreenLabel(obj): msg = "WEB: Off-screen label cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isNonNavigablePopup(obj): msg = "WEB: Non-navigable popup cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isUselessImage(obj): msg = "WEB: Useless image cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isUselessEmptyElement(obj): msg = "WEB: Useless empty element cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isEmptyAnchor(obj): msg = "WEB: Empty anchor cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.hasNoSize(obj): msg = "WEB: Allowing sizeless object to have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isParentOfNullChild(obj): msg = "WEB: Parent of null child cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isPseudoElement(obj): msg = "WEB: Pseudo element cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isStaticTextLeaf(obj): msg = "WEB: Static text leaf cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isFakePlaceholderForEntry(obj): msg = "WEB: Fake placeholder for entry cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False return True def isPseudoElement(self, obj): return False def searchForCaretContext(self, obj): contextObj, contextOffset = None, -1 while obj: try: offset = obj.queryText().caretOffset except: obj = None else: contextObj, contextOffset = obj, offset child = self.getChildAtOffset(obj, offset) if child: obj = child else: break if contextObj: return self.findNextCaretInOrder(contextObj, max(-1, contextOffset - 1)) return None, -1 def _getCaretContextViaLocusOfFocus(self): obj = orca_state.locusOfFocus if not self.inDocumentContent(obj): return None, -1 try: offset = obj.queryText().caretOffset except NotImplementedError: offset = 0 except: offset = -1 return obj, offset def getCaretContext(self, documentFrame=None, getZombieReplicant=False): if not documentFrame or self.isZombie(documentFrame): documentFrame = self.documentFrame() if not documentFrame: return self._getCaretContextViaLocusOfFocus() context = self._caretContexts.get(hash(documentFrame.parent)) if not context or documentFrame != self.getTopLevelDocumentForObject(context[0]): obj, offset = self.searchForCaretContext(documentFrame) elif not getZombieReplicant: return context elif self.isZombie(context[0]): obj, offset = self.findContextReplicant() if obj: caretObj, caretOffset = self.searchForCaretContext(obj.parent) if caretObj and not self.isZombie(caretObj): obj, offset = caretObj, caretOffset else: obj, offset = context self.setCaretContext(obj, offset, documentFrame) return obj, offset def getCaretContextPathRoleAndName(self, documentFrame=None): documentFrame = documentFrame or self.documentFrame() if not documentFrame: return [-1], None, None rv = self._contextPathsRolesAndNames.get(hash(documentFrame.parent)) if not rv: return [-1], None, None return rv def getObjectFromPath(self, path): start = self._script.app rv = None for p in path: if p == -1: continue try: start = start[p] except: break else: rv = start return rv def clearCaretContext(self, documentFrame=None): self.clearContentCache() documentFrame = documentFrame or self.documentFrame() if not documentFrame: return parent = documentFrame.parent self._caretContexts.pop(hash(parent), None) self._priorContexts.pop(hash(parent), None) def handleEventFromContextReplicant(self, event, replicant): if self.isDead(replicant): return False if not self.isDead(orca_state.locusOfFocus): return False path, role, name = self.getCaretContextPathRoleAndName() if path != pyatspi.getPath(replicant): return False if role != replicant.getRole(): return False notify = replicant.name != name documentFrame = self.documentFrame() obj, offset = self._caretContexts.get(hash(documentFrame.parent)) orca.setLocusOfFocus(event, replicant, notify) self.setCaretContext(replicant, offset, documentFrame) return True def findContextReplicant(self, documentFrame=None, matchRole=True, matchName=True): path, oldRole, oldName = self.getCaretContextPathRoleAndName(documentFrame) obj = self.getObjectFromPath(path) if obj and matchRole: if obj.getRole() != oldRole: obj = None if obj and matchName: if obj.name != oldName: obj = None if not obj: return None, -1 obj, offset = self.findFirstCaretContext(obj, 0) msg = "WEB: Context replicant is %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return obj, offset def getPriorContext(self, documentFrame=None): if not documentFrame or self.isZombie(documentFrame): documentFrame = self.documentFrame() if documentFrame: context = self._priorContexts.get(hash(documentFrame.parent)) if context: return context return None, -1 def _getPath(self, obj): rv = self._paths.get(hash(obj)) if rv is not None: return rv try: rv = pyatspi.getPath(obj) except: msg = "WEB: Exception getting path for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = [-1] self._paths[hash(obj)] = rv return rv def setCaretContext(self, obj=None, offset=-1, documentFrame=None): documentFrame = documentFrame or self.documentFrame() if not documentFrame: return parent = documentFrame.parent oldObj, oldOffset = self._caretContexts.get(hash(parent), (obj, offset)) self._priorContexts[hash(parent)] = oldObj, oldOffset self._caretContexts[hash(parent)] = obj, offset path = self._getPath(obj) try: role = obj.getRole() name = obj.name except: msg = "WEB: Exception getting role and name for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) role = None name = None self._contextPathsRolesAndNames[hash(parent)] = path, role, name def findFirstCaretContext(self, obj, offset): try: role = obj.getRole() except: msg = "WEB: Exception getting first caret context for %s %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return None, -1 lookInChild = [pyatspi.ROLE_LIST, pyatspi.ROLE_INTERNAL_FRAME, pyatspi.ROLE_TABLE, pyatspi.ROLE_TABLE_ROW] if role in lookInChild and obj.childCount and not self.treatAsDiv(obj, offset): msg = "WEB: First caret context for %s, %i will look in child %s" % (obj, offset, obj[0]) debug.println(debug.LEVEL_INFO, msg, True) return self.findFirstCaretContext(obj[0], 0) text = self.queryNonEmptyText(obj) if not text: if self._advanceCaretInEmptyObject(obj) \ and (self.isTextBlockElement(obj) or self.isEmptyAnchor(obj)): nextObj, nextOffset = self.nextContext(obj, offset) if nextObj: msg = "WEB: First caret context for non-text context %s, %i is next context %s, %i" % \ (obj, offset, nextObj, nextOffset) debug.println(debug.LEVEL_INFO, msg, True) return nextObj, nextOffset if self._canHaveCaretContext(obj): msg = "WEB: First caret context for non-text context %s, %i is %s, %i" % \ (obj, offset, obj, 0) debug.println(debug.LEVEL_INFO, msg, True) return obj, 0 if text and offset >= text.characterCount: if self.isContentEditableWithEmbeddedObjects(obj) \ and not self.lastInputEventWasLineNav() \ and not self.lastInputEventWasLineBoundaryNav(): nextObj, nextOffset = self.nextContext(obj, text.characterCount) if not nextObj: msg = "WEB: No next object found at end of contenteditable %s" % obj debug.println(debug.LEVEL_INFO, msg, True) elif not self.isContentEditableWithEmbeddedObjects(nextObj): msg = "WEB: Next object found at end of contenteditable %s is not editable %s" % (obj, nextObj) debug.println(debug.LEVEL_INFO, msg, True) else: msg = "WEB: First caret context at end of contenteditable %s is next context %s, %i" % \ (obj, nextObj, nextOffset) debug.println(debug.LEVEL_INFO, msg, True) return nextObj, nextOffset msg = "WEB: First caret context at end of %s, %i is %s, %i" % (obj, offset, obj, text.characterCount) debug.println(debug.LEVEL_INFO, msg, True) return obj, text.characterCount offset = max (0, offset) if text: allText = text.getText(0, -1) if allText[offset] != self.EMBEDDED_OBJECT_CHARACTER or role == pyatspi.ROLE_ENTRY: msg = "WEB: First caret context for %s, %i is unchanged" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return obj, offset child = self.getChildAtOffset(obj, offset) if not child: msg = "WEB: Child at offset is null. Returning %s, %i unchanged." % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return obj, offset if self.isListItemMarker(child): msg = "WEB: First caret context for %s, %i is %s, %i (skip list item marker child)" % \ (obj, offset, obj, offset + 1) debug.println(debug.LEVEL_INFO, msg, True) return obj, offset + 1 if not self._canHaveCaretContext(child): nextObj, nextOffset = self.nextContext(obj, offset) msg = "WEB: First caret context for %s, %i is %s, %i (child cannot be context)" % \ (obj, offset, nextObj, nextOffset) debug.println(debug.LEVEL_INFO, msg, True) return nextObj, nextOffset msg = "WEB: Looking in child %s for first caret context for %s, %i" % (child, obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return self.findFirstCaretContext(child, 0) def findNextCaretInOrder(self, obj=None, offset=-1): if not obj: obj, offset = self.getCaretContext() if not obj or not self.inDocumentContent(obj): return None, -1 if self._canHaveCaretContext(obj): text = self.queryNonEmptyText(obj) if text: allText = text.getText(0, -1) for i in range(offset + 1, len(allText)): child = self.getChildAtOffset(obj, i) if child and self._treatObjectAsWhole(child): return child, 0 if self._canHaveCaretContext(child): return self.findNextCaretInOrder(child, -1) if allText[i] not in (self.EMBEDDED_OBJECT_CHARACTER, self.ZERO_WIDTH_NO_BREAK_SPACE): return obj, i elif obj.childCount and not self._treatObjectAsWhole(obj): return self.findNextCaretInOrder(obj[0], -1) elif offset < 0 and not self.isTextBlockElement(obj): return obj, 0 # If we're here, start looking up the the tree, up to the document. documentFrame = self.documentFrame() if self.isSameObject(obj, documentFrame): return None, -1 while obj and obj.parent: if self.isDetachedDocument(obj.parent): obj = self.iframeForDetachedDocument(obj.parent) continue parent = obj.parent if self.isZombie(parent): replicant = self.findReplicant(self.documentFrame(), parent) if replicant and not self.isZombie(replicant): parent = replicant elif parent.parent: obj = parent continue else: break start, end, length = self._rangeInParentWithLength(obj) if start + 1 == end and 0 <= start < end <= length: return self.findNextCaretInOrder(parent, start) index = obj.getIndexInParent() + 1 try: parentChildCount = parent.childCount except: msg = "WEB: Exception getting childCount for %s" % parent debug.println(debug.LEVEL_INFO, msg, True) else: if 0 < index < parentChildCount: return self.findNextCaretInOrder(parent[index], -1) obj = parent return None, -1 def findPreviousCaretInOrder(self, obj=None, offset=-1): if not obj: obj, offset = self.getCaretContext() if not obj or not self.inDocumentContent(obj): return None, -1 if self._canHaveCaretContext(obj): text = self.queryNonEmptyText(obj) if text: allText = text.getText(0, -1) if offset == -1 or offset > len(allText): offset = len(allText) for i in range(offset - 1, -1, -1): child = self.getChildAtOffset(obj, i) if child and self._treatObjectAsWhole(child): return child, 0 if self._canHaveCaretContext(child): return self.findPreviousCaretInOrder(child, -1) if allText[i] not in (self.EMBEDDED_OBJECT_CHARACTER, self.ZERO_WIDTH_NO_BREAK_SPACE): return obj, i elif obj.childCount and not self._treatObjectAsWhole(obj): return self.findPreviousCaretInOrder(obj[obj.childCount - 1], -1) elif offset < 0 and not self.isTextBlockElement(obj): return obj, 0 # If we're here, start looking up the the tree, up to the document. documentFrame = self.documentFrame() if self.isSameObject(obj, documentFrame): return None, -1 while obj and obj.parent: if self.isDetachedDocument(obj.parent): obj = self.iframeForDetachedDocument(obj.parent) continue parent = obj.parent if self.isZombie(parent): replicant = self.findReplicant(self.documentFrame(), parent) if replicant and not self.isZombie(replicant): parent = replicant elif parent.parent: obj = parent continue else: break start, end, length = self._rangeInParentWithLength(obj) if start + 1 == end and 0 <= start < end <= length: return self.findPreviousCaretInOrder(parent, start) index = obj.getIndexInParent() - 1 try: parentChildCount = parent.childCount except: msg = "WEB: Exception getting childCount for %s" % parent debug.println(debug.LEVEL_INFO, msg, True) else: if 0 <= index < parentChildCount: return self.findPreviousCaretInOrder(parent[index], -1) obj = parent return None, -1 def lastQueuedLiveRegion(self): if self._lastQueuedLiveRegionEvent is None: return None if self._lastQueuedLiveRegionEvent.type.startswith("object:text-changed:insert"): return self._lastQueuedLiveRegionEvent.source if self._lastQueuedLiveRegionEvent.type.startswith("object:children-changed:add"): return self._lastQueuedLiveRegionEvent.any_data return None def handleAsLiveRegion(self, event): if not _settingsManager.getSetting('inferLiveRegions'): return False if not self.isLiveRegion(event.source): return False if not _settingsManager.getSetting('presentLiveRegionFromInactiveTab') \ and self.getTopLevelDocumentForObject(event.source) != self.activeDocument(): msg = "WEB: Live region source is not in active tab." debug.println(debug.LEVEL_INFO, msg, True) return False if event.type.startswith("object:text-changed:insert"): isAlert = lambda x: x and x.getRole() == pyatspi.ROLE_ALERT alert = pyatspi.findAncestor(event.source, isAlert) if alert and self.focusedObject(alert) == event.source: msg = "WEB: Focused source will be presented as part of alert" debug.println(debug.LEVEL_INFO, msg, True) return False if self._lastQueuedLiveRegionEvent \ and self._lastQueuedLiveRegionEvent.type == event.type \ and self._lastQueuedLiveRegionEvent.any_data == event.any_data: msg = "WEB: Event is believed to be duplicate message" debug.println(debug.LEVEL_INFO, msg, True) return False if isinstance(event.any_data, pyatspi.Accessible): try: role = event.any_data.getRole() except: msg = "WEB: Exception getting role for %s" % event.any_data debug.println(debug.LEVEL_INFO, msg, True) return False if role in [pyatspi.ROLE_UNKNOWN, pyatspi.ROLE_REDUNDANT_OBJECT] \ and self._getTag(event.any_data) in ["", None, "br"]: msg = "WEB: Child has unknown role and no tag %s" % event.any_data debug.println(debug.LEVEL_INFO, msg, True) return False if self.lastQueuedLiveRegion() == event.any_data \ and self._lastQueuedLiveRegionEvent.type != event.type: msg = "WEB: Event is believed to be redundant live region notification" debug.println(debug.LEVEL_INFO, msg, True) return False self._lastQueuedLiveRegionEvent = event return True def getPageObjectCount(self, obj): result = {'landmarks': 0, 'headings': 0, 'forms': 0, 'tables': 0, 'visitedLinks': 0, 'unvisitedLinks': 0} docframe = self.documentFrame(obj) msg = "WEB: Document frame for %s is %s" % (obj, docframe) debug.println(debug.LEVEL_INFO, msg, True) col = docframe.queryCollection() stateset = pyatspi.StateSet() roles = [pyatspi.ROLE_HEADING, pyatspi.ROLE_LINK, pyatspi.ROLE_TABLE, pyatspi.ROLE_FORM, pyatspi.ROLE_LANDMARK] if not self.supportsLandmarkRole(): roles.append(pyatspi.ROLE_SECTION) rule = col.createMatchRule(stateset.raw(), col.MATCH_NONE, "", col.MATCH_NONE, roles, col.MATCH_ANY, "", col.MATCH_NONE, False) matches = col.getMatches(rule, col.SORT_ORDER_CANONICAL, 0, True) col.freeMatchRule(rule) for obj in matches: role = obj.getRole() if role == pyatspi.ROLE_HEADING: result['headings'] += 1 elif role == pyatspi.ROLE_FORM: result['forms'] += 1 elif role == pyatspi.ROLE_TABLE and not self.isLayoutOnly(obj): result['tables'] += 1 elif role == pyatspi.ROLE_LINK: if self.isLink(obj): if obj.getState().contains(pyatspi.STATE_VISITED): result['visitedLinks'] += 1 else: result['unvisitedLinks'] += 1 elif self.isLandmark(obj): result['landmarks'] += 1 return result def getPageSummary(self, obj, onlyIfFound=True): result = [] counts = self.getPageObjectCount(obj) result.append(messages.landmarkCount(counts.get('landmarks', 0), onlyIfFound)) result.append(messages.headingCount(counts.get('headings', 0), onlyIfFound)) result.append(messages.formCount(counts.get('forms', 0), onlyIfFound)) result.append(messages.tableCount(counts.get('tables', 0), onlyIfFound)) result.append(messages.visitedLinkCount(counts.get('visitedLinks', 0), onlyIfFound)) result.append(messages.unvisitedLinkCount(counts.get('unvisitedLinks', 0), onlyIfFound)) result = list(filter(lambda x: x, result)) if not result: return "" return messages.PAGE_SUMMARY_PREFIX % ", ".join(result) def preferDescriptionOverName(self, obj): if not self.inDocumentContent(obj): return super().preferDescriptionOverName(obj) rv = self._preferDescriptionOverName.get(hash(obj)) if rv is not None: return rv try: role = obj.getRole() name = obj.name description = obj.description except: msg = "WEB: Exception getting name, description, and role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = False else: if len(obj.name) == 1 and ord(obj.name) in range(0xe000, 0xf8ff): msg = "WEB: name of %s is in unicode private use area" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = True else: roles = [pyatspi.ROLE_PUSH_BUTTON] rv = role in roles and len(name) == 1 and description self._preferDescriptionOverName[hash(obj)] = rv return rv def _getCtrlShiftSelectionsStrings(self): """Hacky and to-be-obsoleted method.""" return [messages.LINE_SELECTED_DOWN, messages.LINE_UNSELECTED_DOWN, messages.LINE_SELECTED_UP, messages.LINE_UNSELECTED_UP] def lastInputEventWasCopy(self): if super().lastInputEventWasCopy(): return True if not self.inDocumentContent(): return False if not self.topLevelObjectIsActiveAndCurrent(): return False if 'Action' in pyatspi.listInterfaces(orca_state.locusOfFocus): msg = "WEB: Treating %s as source of copy" % orca_state.locusOfFocus debug.println(debug.LEVEL_INFO, msg, True) return True return False Only update context at end of contenteditable element during char nav We were updating the caret content when the caret moved to the end of a contenteditable element unless the movement resulted from line nav or line boundary nav. The idea was that if char nav or word nav were used, the behavior would be wanted. But some editors give us caret-moved events for the end of an object as a consequence of inserting or deleting text. In those instances, updating our context can cause the default script to not present the caret moved event. More research should be done to determine if this update should be done for word navigation. # Orca # # Copyright 2010 Joanmarie Diggs. # Copyright 2014-2015 Igalia, S.L. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA. __id__ = "$Id$" __version__ = "$Revision$" __date__ = "$Date$" __copyright__ = "Copyright (c) 2010 Joanmarie Diggs." \ "Copyright (c) 2014-2015 Igalia, S.L." __license__ = "LGPL" import functools import pyatspi import re import time import urllib from orca import debug from orca import input_event from orca import messages from orca import mouse_review from orca import orca from orca import orca_state from orca import script_utilities from orca import script_manager from orca import settings from orca import settings_manager _scriptManager = script_manager.getManager() _settingsManager = settings_manager.getManager() class Utilities(script_utilities.Utilities): def __init__(self, script): super().__init__(script) self._objectAttributes = {} self._currentTextAttrs = {} self._caretContexts = {} self._priorContexts = {} self._contextPathsRolesAndNames = {} self._paths = {} self._inDocumentContent = {} self._inTopLevelWebApp = {} self._isTextBlockElement = {} self._isContentEditableWithEmbeddedObjects = {} self._isCodeDescendant = {} self._isEntryDescendant = {} self._isGridDescendant = {} self._isLabelDescendant = {} self._isMenuDescendant = {} self._isNavigableToolTipDescendant = {} self._isToolBarDescendant = {} self._isWebAppDescendant = {} self._isLayoutOnly = {} self._isFocusableWithMathChild = {} self._mathNestingLevel = {} self._isOffScreenLabel = {} self._elementLinesAreSingleChars= {} self._elementLinesAreSingleWords= {} self._hasNoSize = {} self._hasLongDesc = {} self._hasDetails = {} self._isDetails = {} self._hasUselessCanvasDescendant = {} self._isClickableElement = {} self._isAnchor = {} self._isEditableComboBox = {} self._isErrorMessage = {} self._isInlineIframeDescendant = {} self._isInlineListItem = {} self._isInlineListDescendant = {} self._isLandmark = {} self._isLink = {} self._isListDescendant = {} self._isNonNavigablePopup = {} self._isNonEntryTextWidget = {} self._isUselessImage = {} self._isRedundantSVG = {} self._isUselessEmptyElement = {} self._hasNameAndActionAndNoUsefulChildren = {} self._isNonNavigableEmbeddedDocument = {} self._isParentOfNullChild = {} self._inferredLabels = {} self._actualLabels = {} self._labelTargets = {} self._displayedLabelText = {} self._mimeType = {} self._preferDescriptionOverName = {} self._shouldFilter = {} self._shouldInferLabelFor = {} self._text = {} self._treatAsDiv = {} self._currentObjectContents = None self._currentSentenceContents = None self._currentLineContents = None self._currentWordContents = None self._currentCharacterContents = None self._lastQueuedLiveRegionEvent = None self._findContainer = None self._validChildRoles = {pyatspi.ROLE_LIST: [pyatspi.ROLE_LIST_ITEM]} def _cleanupContexts(self): toRemove = [] for key, [obj, offset] in self._caretContexts.items(): if self.isZombie(obj): toRemove.append(key) for key in toRemove: self._caretContexts.pop(key, None) def clearCachedObjects(self): debug.println(debug.LEVEL_INFO, "WEB: cleaning up cached objects", True) self._objectAttributes = {} self._inDocumentContent = {} self._inTopLevelWebApp = {} self._isTextBlockElement = {} self._isContentEditableWithEmbeddedObjects = {} self._isCodeDescendant = {} self._isEntryDescendant = {} self._isGridDescendant = {} self._isLabelDescendant = {} self._isMenuDescendant = {} self._isNavigableToolTipDescendant = {} self._isToolBarDescendant = {} self._isWebAppDescendant = {} self._isLayoutOnly = {} self._isFocusableWithMathChild = {} self._mathNestingLevel = {} self._isOffScreenLabel = {} self._elementLinesAreSingleChars= {} self._elementLinesAreSingleWords= {} self._hasNoSize = {} self._hasLongDesc = {} self._hasDetails = {} self._isDetails = {} self._hasUselessCanvasDescendant = {} self._isClickableElement = {} self._isAnchor = {} self._isEditableComboBox = {} self._isErrorMessage = {} self._isInlineIframeDescendant = {} self._isInlineListItem = {} self._isInlineListDescendant = {} self._isLandmark = {} self._isLink = {} self._isListDescendant = {} self._isNonNavigablePopup = {} self._isNonEntryTextWidget = {} self._isUselessImage = {} self._isRedundantSVG = {} self._isUselessEmptyElement = {} self._hasNameAndActionAndNoUsefulChildren = {} self._isNonNavigableEmbeddedDocument = {} self._isParentOfNullChild = {} self._inferredLabels = {} self._actualLabels = {} self._labelTargets = {} self._displayedLabelText = {} self._mimeType = {} self._preferDescriptionOverName = {} self._shouldFilter = {} self._shouldInferLabelFor = {} self._treatAsDiv = {} self._paths = {} self._contextPathsRolesAndNames = {} self._cleanupContexts() self._priorContexts = {} self._lastQueuedLiveRegionEvent = None self._findContainer = None def clearContentCache(self): self._currentObjectContents = None self._currentSentenceContents = None self._currentLineContents = None self._currentWordContents = None self._currentCharacterContents = None self._currentTextAttrs = {} self._text = {} def isDocument(self, obj): if not obj: return False roles = [pyatspi.ROLE_DOCUMENT_FRAME, pyatspi.ROLE_DOCUMENT_WEB, pyatspi.ROLE_EMBEDDED] try: rv = obj.getRole() in roles except: msg = "WEB: Exception getting role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = False return rv def inDocumentContent(self, obj=None): if not obj: obj = orca_state.locusOfFocus if self.isDocument(obj): return True rv = self._inDocumentContent.get(hash(obj)) if rv is not None: return rv document = self.getDocumentForObject(obj) rv = document is not None self._inDocumentContent[hash(obj)] = rv return rv def _getDocumentsEmbeddedBy(self, frame): if not frame: return [] isEmbeds = lambda r: r.getRelationType() == pyatspi.RELATION_EMBEDS try: relations = list(filter(isEmbeds, frame.getRelationSet())) except: msg = "ERROR: Exception getting embeds relation for %s" % frame debug.println(debug.LEVEL_INFO, msg, True) return [] if not relations: return [] relation = relations[0] targets = [relation.getTarget(i) for i in range(relation.getNTargets())] if not targets: return [] return list(filter(self.isDocument, targets)) def sanityCheckActiveWindow(self): app = self._script.app try: windowInApp = orca_state.activeWindow in app except: msg = "ERROR: Exception checking if %s is in %s" % (orca_state.activeWindow, app) debug.println(debug.LEVEL_INFO, msg, True) windowInApp = False if windowInApp: return True msg = "WARNING: %s is not in %s" % (orca_state.activeWindow, app) debug.println(debug.LEVEL_INFO, msg, True) try: script = _scriptManager.getScript(app, orca_state.activeWindow) msg = "WEB: Script for active Window is %s" % script debug.println(debug.LEVEL_INFO, msg, True) except: msg = "ERROR: Exception getting script for active window" debug.println(debug.LEVEL_INFO, msg, True) else: if type(script) == type(self._script): attrs = script.getTransferableAttributes() for attr, value in attrs.items(): msg = "WEB: Setting %s to %s" % (attr, value) debug.println(debug.LEVEL_INFO, msg, True) setattr(self._script, attr, value) window = self.activeWindow(app) try: self._script.app = window.getApplication() msg = "WEB: updating script's app to %s" % self._script.app debug.println(debug.LEVEL_INFO, msg, True) except: msg = "ERROR: Exception getting app for %s" % window debug.println(debug.LEVEL_INFO, msg, True) return False orca_state.activeWindow = window return True def activeDocument(self, window=None): isShowing = lambda x: x and x.getState().contains(pyatspi.STATE_SHOWING) documents = self._getDocumentsEmbeddedBy(window or orca_state.activeWindow) documents = list(filter(isShowing, documents)) if len(documents) == 1: return documents[0] return None def documentFrame(self, obj=None): if not obj and self.sanityCheckActiveWindow(): document = self.activeDocument() if document: return document return self.getDocumentForObject(obj or orca_state.locusOfFocus) def documentFrameURI(self, documentFrame=None): documentFrame = documentFrame or self.documentFrame() if documentFrame and not self.isZombie(documentFrame): try: document = documentFrame.queryDocument() except NotImplementedError: msg = "WEB: %s does not implement document interface" % documentFrame debug.println(debug.LEVEL_INFO, msg, True) except: msg = "ERROR: Exception querying document interface of %s" % documentFrame debug.println(debug.LEVEL_INFO, msg, True) else: return document.getAttributeValue('DocURL') or document.getAttributeValue('URI') return "" def isPlainText(self, documentFrame=None): return self.mimeType(documentFrame) == "text/plain" def mimeType(self, documentFrame=None): documentFrame = documentFrame or self.documentFrame() rv = self._mimeType.get(hash(documentFrame)) if rv is not None: return rv try: document = documentFrame.queryDocument() attrs = dict([attr.split(":", 1) for attr in document.getAttributes()]) except NotImplementedError: msg = "WEB: %s does not implement document interface" % documentFrame debug.println(debug.LEVEL_INFO, msg, True) except: msg = "ERROR: Exception getting document attributes of %s" % documentFrame debug.println(debug.LEVEL_INFO, msg, True) else: rv = attrs.get("MimeType") msg = "WEB: MimeType of %s is '%s'" % (documentFrame, rv) self._mimeType[hash(documentFrame)] = rv return rv def grabFocusWhenSettingCaret(self, obj): try: role = obj.getRole() state = obj.getState() childCount = obj.childCount except: msg = "WEB: Exception getting role, state, and childCount for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False # To avoid triggering popup lists. if role == pyatspi.ROLE_ENTRY: return False if role == pyatspi.ROLE_IMAGE: isLink = lambda x: x and x.getRole() == pyatspi.ROLE_LINK return pyatspi.utils.findAncestor(obj, isLink) is not None if role == pyatspi.ROLE_HEADING and childCount == 1: return self.isLink(obj[0]) return state.contains(pyatspi.STATE_FOCUSABLE) def grabFocus(self, obj): try: obj.queryComponent().grabFocus() except NotImplementedError: msg = "WEB: %s does not implement the component interface" % obj debug.println(debug.LEVEL_INFO, msg, True) except: msg = "WEB: Exception grabbing focus on %s" % obj debug.println(debug.LEVEL_INFO, msg, True) def setCaretPosition(self, obj, offset, documentFrame=None): if self._script.flatReviewContext: self._script.toggleFlatReviewMode() grabFocus = self.grabFocusWhenSettingCaret(obj) obj, offset = self.findFirstCaretContext(obj, offset) self.setCaretContext(obj, offset, documentFrame) if self._script.focusModeIsSticky(): return oldFocus = orca_state.locusOfFocus self.clearTextSelection(oldFocus) orca.setLocusOfFocus(None, obj, notifyScript=False) if grabFocus: self.grabFocus(obj) # Don't use queryNonEmptyText() because we need to try to force-update focus. if "Text" in pyatspi.listInterfaces(obj): try: obj.queryText().setCaretOffset(offset) except: msg = "WEB: Exception setting caret to %i in %s" % (offset, obj) debug.println(debug.LEVEL_INFO, msg, True) else: msg = "WEB: Caret set to %i in %s" % (offset, obj) debug.println(debug.LEVEL_INFO, msg, True) if self._script.useFocusMode(obj, oldFocus) != self._script.inFocusMode(): self._script.togglePresentationMode(None) if obj: obj.clearCache() # TODO - JD: This is private. self._script._saveFocusedObjectInfo(obj) def getNextObjectInDocument(self, obj, documentFrame): if not obj: return None for relation in obj.getRelationSet(): if relation.getRelationType() == pyatspi.RELATION_FLOWS_TO: return relation.getTarget(0) if obj == documentFrame: obj, offset = self.getCaretContext(documentFrame) for child in documentFrame: if self.characterOffsetInParent(child) > offset: return child if obj and obj.childCount: return obj[0] nextObj = None while obj and not nextObj: index = obj.getIndexInParent() + 1 if 0 < index < obj.parent.childCount: nextObj = obj.parent[index] elif obj.parent != documentFrame: obj = obj.parent else: break return nextObj def getPreviousObjectInDocument(self, obj, documentFrame): if not obj: return None for relation in obj.getRelationSet(): if relation.getRelationType() == pyatspi.RELATION_FLOWS_FROM: return relation.getTarget(0) if obj == documentFrame: obj, offset = self.getCaretContext(documentFrame) for child in documentFrame: if self.characterOffsetInParent(child) < offset: return child index = obj.getIndexInParent() - 1 if not 0 <= index < obj.parent.childCount: obj = obj.parent index = obj.getIndexInParent() - 1 previousObj = obj.parent[index] while previousObj and previousObj.childCount: previousObj = previousObj[previousObj.childCount - 1] return previousObj def getTopOfFile(self): return self.findFirstCaretContext(self.documentFrame(), 0) def getBottomOfFile(self): obj = self.getLastObjectInDocument(self.documentFrame()) offset = 0 text = self.queryNonEmptyText(obj) if text: offset = text.characterCount - 1 while obj: lastobj, lastoffset = self.nextContext(obj, offset) if not lastobj: break obj, offset = lastobj, lastoffset return [obj, offset] def getLastObjectInDocument(self, documentFrame): try: lastChild = documentFrame[documentFrame.childCount - 1] except: lastChild = documentFrame while lastChild: lastObj = self.getNextObjectInDocument(lastChild, documentFrame) if lastObj and lastObj != lastChild: lastChild = lastObj else: break return lastChild def objectAttributes(self, obj, useCache=True): if not (obj and self.inDocumentContent(obj)): return super().objectAttributes(obj) if useCache: rv = self._objectAttributes.get(hash(obj)) if rv is not None: return rv try: rv = dict([attr.split(':', 1) for attr in obj.getAttributes()]) except: rv = {} self._objectAttributes[hash(obj)] = rv return rv def getRoleDescription(self, obj): attrs = self.objectAttributes(obj) return attrs.get('roledescription', '') def nodeLevel(self, obj): if not (obj and self.inDocumentContent(obj)): return super().nodeLevel(obj) rv = -1 if not (self.inMenu(obj) or obj.getRole() == pyatspi.ROLE_HEADING): attrs = self.objectAttributes(obj) # ARIA levels are 1-based; non-web content is 0-based. Be consistent. rv = int(attrs.get('level', 0)) -1 return rv def getPositionInSet(self, obj): attrs = self.objectAttributes(obj, False) position = attrs.get('posinset') if position is not None: return int(position) if obj.getRole() == pyatspi.ROLE_TABLE_ROW: rowindex = attrs.get('rowindex') if rowindex is None and obj.childCount: roles = self._cellRoles() cell = pyatspi.findDescendant(obj, lambda x: x and x.getRole() in roles) rowindex = self.objectAttributes(cell, False).get('rowindex') if rowindex is not None: return int(rowindex) return None def getSetSize(self, obj): attrs = self.objectAttributes(obj, False) setsize = attrs.get('setsize') if setsize is not None: return int(setsize) if obj.getRole() == pyatspi.ROLE_TABLE_ROW: rows, cols = self.rowAndColumnCount(self.getTable(obj)) if rows != -1: return rows return None def _getID(self, obj): attrs = self.objectAttributes(obj) return attrs.get('id') def _getDisplayStyle(self, obj): attrs = self.objectAttributes(obj) return attrs.get('display') def _getTag(self, obj): attrs = self.objectAttributes(obj) return attrs.get('tag') def _getXMLRoles(self, obj): attrs = self.objectAttributes(obj) return attrs.get('xml-roles', '').split() def inFindContainer(self, obj=None): if not obj: obj = orca_state.locusOfFocus if self.inDocumentContent(obj): return False return super().inFindContainer(obj) def isEmpty(self, obj): if not self.isTextBlockElement(obj): return False if obj.name: return False return self.queryNonEmptyText(obj, False) is None def isHidden(self, obj): attrs = self.objectAttributes(obj) return attrs.get('hidden', False) def _isOrIsIn(self, child, parent): if not (child and parent): return False if child == parent: return True return pyatspi.findAncestor(child, lambda x: x == parent) def isShowingAndVisible(self, obj): rv = super().isShowingAndVisible(obj) if rv or not self.inDocumentContent(obj): return rv if not mouse_review.reviewer.inMouseEvent: if not self._isOrIsIn(orca_state.locusOfFocus, obj): return rv msg = "WEB: %s contains locusOfFocus but not showing and visible" % obj debug.println(debug.LEVEL_INFO, msg, True) obj.clearCache() rv = super().isShowingAndVisible(obj) if rv: msg = "WEB: Clearing cache fixed state of %s. Missing event?" % obj debug.println(debug.LEVEL_INFO, msg, True) return rv def isTextArea(self, obj): if not self.inDocumentContent(obj): return super().isTextArea(obj) if self.isLink(obj): return False try: role = obj.getRole() state = obj.getState() except: msg = "WEB: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if role == pyatspi.ROLE_COMBO_BOX \ and state.contains(pyatspi.STATE_EDITABLE) \ and not obj.childCount: return True if role in self._textBlockElementRoles(): document = self.getDocumentForObject(obj) if document and document.getState().contains(pyatspi.STATE_EDITABLE): return True return super().isTextArea(obj) def isReadOnlyTextArea(self, obj): # NOTE: This method is deliberately more conservative than isTextArea. if obj.getRole() != pyatspi.ROLE_ENTRY: return False state = obj.getState() readOnly = state.contains(pyatspi.STATE_FOCUSABLE) \ and not state.contains(pyatspi.STATE_EDITABLE) return readOnly def setCaretOffset(self, obj, characterOffset): self.setCaretPosition(obj, characterOffset) self._script.updateBraille(obj) def nextContext(self, obj=None, offset=-1, skipSpace=False): if not obj: obj, offset = self.getCaretContext() nextobj, nextoffset = self.findNextCaretInOrder(obj, offset) if (obj, offset) == (nextobj, nextoffset): nextobj, nextoffset = self.findNextCaretInOrder(nextobj, nextoffset) if skipSpace: text = self.queryNonEmptyText(nextobj) while text and text.getText(nextoffset, nextoffset + 1).isspace(): nextobj, nextoffset = self.findNextCaretInOrder(nextobj, nextoffset) text = self.queryNonEmptyText(nextobj) return nextobj, nextoffset def previousContext(self, obj=None, offset=-1, skipSpace=False): if not obj: obj, offset = self.getCaretContext() prevobj, prevoffset = self.findPreviousCaretInOrder(obj, offset) if (obj, offset) == (prevobj, prevoffset): prevobj, prevoffset = self.findPreviousCaretInOrder(prevobj, prevoffset) if skipSpace: text = self.queryNonEmptyText(prevobj) while text and text.getText(prevoffset, prevoffset + 1).isspace(): prevobj, prevoffset = self.findPreviousCaretInOrder(prevobj, prevoffset) text = self.queryNonEmptyText(prevobj) return prevobj, prevoffset def lastContext(self, root): offset = 0 text = self.queryNonEmptyText(root) if text: offset = text.characterCount - 1 def _isInRoot(o): return o == root or pyatspi.utils.findAncestor(o, lambda x: x == root) obj = root while obj: lastobj, lastoffset = self.nextContext(obj, offset) if not (lastobj and _isInRoot(lastobj)): break obj, offset = lastobj, lastoffset return obj, offset def contextsAreOnSameLine(self, a, b): if a == b: return True aObj, aOffset = a bObj, bOffset = b aExtents = self.getExtents(aObj, aOffset, aOffset + 1) bExtents = self.getExtents(bObj, bOffset, bOffset + 1) return self.extentsAreOnSameLine(aExtents, bExtents) @staticmethod def extentsAreOnSameLine(a, b, pixelDelta=5): if a == b: return True aX, aY, aWidth, aHeight = a bX, bY, bWidth, bHeight = b if aWidth == 0 and aHeight == 0: return bY <= aY <= bY + bHeight if bWidth == 0 and bHeight == 0: return aY <= bY <= aY + aHeight highestBottom = min(aY + aHeight, bY + bHeight) lowestTop = max(aY, bY) if lowestTop >= highestBottom: return False aMiddle = aY + aHeight / 2 bMiddle = bY + bHeight / 2 if abs(aMiddle - bMiddle) > pixelDelta: return False return True @staticmethod def getExtents(obj, startOffset, endOffset): if not obj: return [0, 0, 0, 0] result = [0, 0, 0, 0] try: text = obj.queryText() if text.characterCount and 0 <= startOffset < endOffset: result = list(text.getRangeExtents(startOffset, endOffset, 0)) except NotImplementedError: pass except: msg = "WEB: Exception getting range extents for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] else: if result[0] and result[1] and result[2] == 0 and result[3] == 0 \ and text.getText(startOffset, endOffset).strip(): msg = "WEB: Suspected bogus range extents for %s (chars: %i, %i): %s" % \ (obj, startOffset, endOffset, result) debug.println(debug.LEVEL_INFO, msg, True) elif text.characterCount: return result role = obj.getRole() try: parentRole = obj.parent.getRole() except: msg = "WEB: Exception getting role of parent (%s) of %s" % (obj.parent, obj) debug.println(debug.LEVEL_INFO, msg, True) parentRole = None if role in [pyatspi.ROLE_MENU, pyatspi.ROLE_LIST_ITEM] \ and parentRole in [pyatspi.ROLE_COMBO_BOX, pyatspi.ROLE_LIST_BOX]: try: ext = obj.parent.queryComponent().getExtents(0) except NotImplementedError: msg = "WEB: %s does not implement the component interface" % obj.parent debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] except: msg = "WEB: Exception getting extents for %s" % obj.parent debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] else: try: ext = obj.queryComponent().getExtents(0) except NotImplementedError: msg = "WEB: %s does not implement the component interface" % obj debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] except: msg = "WEB: Exception getting extents for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return [0, 0, 0, 0] return [ext.x, ext.y, ext.width, ext.height] def _preserveTree(self, obj): if not (obj and obj.childCount): return False if self.isMathTopLevel(obj): return True return False def expandEOCs(self, obj, startOffset=0, endOffset=-1): if not self.inDocumentContent(obj): return super().expandEOCs(obj, startOffset, endOffset) text = self.queryNonEmptyText(obj) if not text: return "" if self._preserveTree(obj): utterances = self._script.speechGenerator.generateSpeech(obj) return self._script.speechGenerator.utterancesToString(utterances) return super().expandEOCs(obj, startOffset, endOffset).strip() def substring(self, obj, startOffset, endOffset): if not self.inDocumentContent(obj): return super().substring(obj, startOffset, endOffset) text = self.queryNonEmptyText(obj) if text: return text.getText(startOffset, endOffset) return "" def textAttributes(self, acc, offset, get_defaults=False): attrsForObj = self._currentTextAttrs.get(hash(acc)) or {} if offset in attrsForObj: return attrsForObj.get(offset) attrs = super().textAttributes(acc, offset, get_defaults) self._currentTextAttrs[hash(acc)] = {offset:attrs} return attrs def findObjectInContents(self, obj, offset, contents, usingCache=False): if not obj or not contents: return -1 offset = max(0, offset) matches = [x for x in contents if x[0] == obj] match = [x for x in matches if x[1] <= offset < x[2]] if match and match[0] and match[0] in contents: return contents.index(match[0]) if not usingCache: match = [x for x in matches if offset == x[2]] if match and match[0] and match[0] in contents: return contents.index(match[0]) if not self.isTextBlockElement(obj): return -1 child = self.getChildAtOffset(obj, offset) if child and not self.isTextBlockElement(child): matches = [x for x in contents if x[0] == child] if len(matches) == 1: return contents.index(matches[0]) return -1 def isNonEntryTextWidget(self, obj): rv = self._isNonEntryTextWidget.get(hash(obj)) if rv is not None: return rv roles = [pyatspi.ROLE_CHECK_BOX, pyatspi.ROLE_CHECK_MENU_ITEM, pyatspi.ROLE_MENU, pyatspi.ROLE_MENU_ITEM, pyatspi.ROLE_PAGE_TAB, pyatspi.ROLE_RADIO_MENU_ITEM, pyatspi.ROLE_RADIO_BUTTON, pyatspi.ROLE_PUSH_BUTTON, pyatspi.ROLE_TOGGLE_BUTTON] role = obj.getRole() if role in roles: rv = True elif role == pyatspi.ROLE_LIST_ITEM: rv = obj.parent.getRole() != pyatspi.ROLE_LIST elif role == pyatspi.ROLE_TABLE_CELL: if obj.getState().contains(pyatspi.STATE_EDITABLE): rv = False else: rv = not self.isTextBlockElement(obj) self._isNonEntryTextWidget[hash(obj)] = rv return rv def queryNonEmptyText(self, obj, excludeNonEntryTextWidgets=True): if not (obj and self.inDocumentContent(obj)) or self._script.browseModeIsSticky(): return super().queryNonEmptyText(obj) if hash(obj) in self._text: return self._text.get(hash(obj)) try: rv = obj.queryText() characterCount = rv.characterCount except NotImplementedError: msg = "WEB: %s doesn't implement text interface" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None except: msg = "WEB: Exception getting character count for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None else: if not characterCount: msg = "WEB: %s reports 0 characters" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if self.isCellWithNameFromHeader(obj): pass elif self._treatObjectAsWhole(obj) and obj.name: msg = "WEB: Treating %s as non-text: named object treated as whole." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None elif not self.isLiveRegion(obj): doNotQuery = [pyatspi.ROLE_LIST_BOX] role = obj.getRole() if rv and role in doNotQuery: msg = "WEB: Treating %s as non-text due to role." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if rv and excludeNonEntryTextWidgets and self.isNonEntryTextWidget(obj): msg = "WEB: Treating %s as non-text: is non-entry text widget." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if rv and (self.isHidden(obj) or self.isOffScreenLabel(obj)): msg = "WEB: Treating %s as non-text: is hidden or off-screen label." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if rv and self.isNonNavigableEmbeddedDocument(obj): msg = "WEB: Treating %s as non-text: is non-navigable embedded document." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None if rv and self.isFakePlaceholderForEntry(obj): msg = "WEB: Treating %s as non-text: is fake placeholder for entry." % obj debug.println(debug.LEVEL_INFO, msg, True) rv = None self._text[hash(obj)] = rv return rv def hasNameAndActionAndNoUsefulChildren(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._hasNameAndActionAndNoUsefulChildren.get(hash(obj)) if rv is not None: return rv rv = False if self.hasExplicitName(obj) and "Action" in pyatspi.listInterfaces(obj): for child in obj: if not self.isUselessEmptyElement(child) or self.isUselessImage(child): break else: rv = True if rv: msg = "WEB: %s has name and action and no useful children" % obj debug.println(debug.LEVEL_INFO, msg, True) self._hasNameAndActionAndNoUsefulChildren[hash(obj)] = rv return rv def _treatObjectAsWhole(self, obj): roles = [pyatspi.ROLE_CHECK_BOX, pyatspi.ROLE_CHECK_MENU_ITEM, pyatspi.ROLE_LIST_BOX, pyatspi.ROLE_MENU, pyatspi.ROLE_MENU_BAR, pyatspi.ROLE_MENU_ITEM, pyatspi.ROLE_RADIO_MENU_ITEM, pyatspi.ROLE_RADIO_BUTTON, pyatspi.ROLE_PUSH_BUTTON, pyatspi.ROLE_TOGGLE_BUTTON, pyatspi.ROLE_TOOL_BAR, pyatspi.ROLE_TREE, pyatspi.ROLE_TREE_ITEM, pyatspi.ROLE_TREE_TABLE] role = obj.getRole() if role in roles: return True state = obj.getState() if state.contains(pyatspi.STATE_EDITABLE): return False if role == pyatspi.ROLE_TABLE_CELL: if self.isFocusModeWidget(obj): return True if self.hasNameAndActionAndNoUsefulChildren(obj): return True if role in [pyatspi.ROLE_COLUMN_HEADER, pyatspi.ROLE_ROW_HEADER] \ and self.hasExplicitName(obj): return True if role == pyatspi.ROLE_COMBO_BOX: return True if role == pyatspi.ROLE_EMBEDDED: return not self._script.browseModeIsSticky() if role == pyatspi.ROLE_LINK: return self.hasExplicitName(obj) or self.hasUselessCanvasDescendant(obj) if self.isNonNavigableEmbeddedDocument(obj): return True if self.isFakePlaceholderForEntry(obj): return True return False def __findRange(self, text, offset, start, end, boundary): # We should not have to do any of this. Seriously. This is why # We can't have nice things. allText = text.getText(0, -1) if boundary == pyatspi.TEXT_BOUNDARY_CHAR: try: string = allText[offset] except IndexError: string = "" return string, offset, offset + 1 extents = list(text.getRangeExtents(offset, offset + 1, 0)) def _inThisSpan(span): return span[0] <= offset <= span[1] def _onThisLine(span): start, end = span startExtents = list(text.getRangeExtents(start, start + 1, 0)) endExtents = list(text.getRangeExtents(end - 1, end, 0)) delta = max(startExtents[3], endExtents[3]) if not self.extentsAreOnSameLine(startExtents, endExtents, delta): msg = "FAIL: Start %s and end %s of '%s' not on same line" \ % (startExtents, endExtents, allText[start:end]) debug.println(debug.LEVEL_INFO, msg, True) startExtents = endExtents return self.extentsAreOnSameLine(extents, startExtents) spans = [] charCount = text.characterCount if boundary == pyatspi.TEXT_BOUNDARY_SENTENCE_START: spans = [m.span() for m in re.finditer(r"\S*[^\.\?\!]+((?<!\w)[\.\?\!]+(?!\w)|\S*)", allText)] elif boundary is not None: spans = [m.span() for m in re.finditer("[^\n\r]+", allText)] if not spans: spans = [(0, charCount)] rangeStart, rangeEnd = 0, charCount for span in spans: if _inThisSpan(span): rangeStart, rangeEnd = span[0], span[1] + 1 break string = allText[rangeStart:rangeEnd] if string and boundary in [pyatspi.TEXT_BOUNDARY_SENTENCE_START, None]: return string, rangeStart, rangeEnd words = [m.span() for m in re.finditer("[^\\s\ufffc]+", string)] words = list(map(lambda x: (x[0] + rangeStart, x[1] + rangeStart), words)) if boundary == pyatspi.TEXT_BOUNDARY_WORD_START: spans = list(filter(_inThisSpan, words)) if boundary == pyatspi.TEXT_BOUNDARY_LINE_START: spans = list(filter(_onThisLine, words)) if spans: rangeStart, rangeEnd = spans[0][0], spans[-1][1] + 1 string = allText[rangeStart:rangeEnd] if not (rangeStart <= offset <= rangeEnd): return allText[start:end], start, end return string, rangeStart, rangeEnd def _attemptBrokenTextRecovery(self, obj, **args): return False def _getTextAtOffset(self, obj, offset, boundary): if not obj: msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '', Start: 0, End: 0. (obj is None)" % (offset, obj, boundary) debug.println(debug.LEVEL_INFO, msg, True) return '', 0, 0 text = self.queryNonEmptyText(obj) if not text: msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '', Start: 0, End: 1. (queryNonEmptyText() returned None)" \ % (offset, obj, boundary) debug.println(debug.LEVEL_INFO, msg, True) return '', 0, 1 if boundary is None: string, start, end = text.getText(0, -1), 0, text.characterCount s = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i." % (offset, obj, boundary, s, start, end) debug.println(debug.LEVEL_INFO, msg, True) return string, start, end if boundary == pyatspi.TEXT_BOUNDARY_SENTENCE_START \ and not obj.getState().contains(pyatspi.STATE_EDITABLE): allText = text.getText(0, -1) if obj.getRole() in [pyatspi.ROLE_LIST_ITEM, pyatspi.ROLE_HEADING] \ or not (re.search(r"\w", allText) and self.isTextBlockElement(obj)): string, start, end = allText, 0, text.characterCount s = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i." % (offset, obj, boundary, s, start, end) debug.println(debug.LEVEL_INFO, msg, True) return string, start, end if boundary == pyatspi.TEXT_BOUNDARY_LINE_START and self.treatAsEndOfLine(obj, offset): offset -= 1 msg = "WEB: Line sought for %s at end of text. Adjusting offset to %i." % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) offset = max(0, offset) string, start, end = text.getTextAtOffset(offset, boundary) # The above should be all that we need to do, but.... if not self._attemptBrokenTextRecovery(obj, boundary=boundary): s = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " Not checking for broken text." % (offset, obj, boundary, s, start, end) debug.println(debug.LEVEL_INFO, msg, True) return string, start, end needSadHack = False testString, testStart, testEnd = text.getTextAtOffset(start, boundary) if (string, start, end) != (testString, testStart, testEnd): s1 = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") s2 = testString.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "FAIL: Bad results for text at offset for %s using %s.\n" \ " For offset %i - String: '%s', Start: %i, End: %i.\n" \ " For offset %i - String: '%s', Start: %i, End: %i.\n" \ " The bug is the above results should be the same.\n" \ " This very likely needs to be fixed by the toolkit." \ % (obj, boundary, offset, s1, start, end, start, s2, testStart, testEnd) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True elif not string and 0 <= offset < text.characterCount: s1 = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") s2 = text.getText(0, -1).replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "FAIL: Bad results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " The bug is no text reported for a valid offset.\n" \ " Character count: %i, Full text: '%s'.\n" \ " This very likely needs to be fixed by the toolkit." \ % (offset, obj, boundary, s1, start, end, text.characterCount, s2) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True elif not (start <= offset < end) and not self.isPlainText(): s1 = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "FAIL: Bad results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " The bug is the range returned is outside of the offset.\n" \ " This very likely needs to be fixed by the toolkit." \ % (offset, obj, boundary, s1, start, end) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True elif len(string) < end - start: s1 = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "FAIL: Bad results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " The bug is that the length of string is less than the text range.\n" \ " This very likely needs to be fixed by the toolkit." \ % (offset, obj, boundary, s1, start, end) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True elif boundary == pyatspi.TEXT_BOUNDARY_CHAR and string == "\ufffd": msg = "FAIL: Bad results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i.\n" \ " The bug is that we didn't seem to get a valid character.\n" \ " This very likely needs to be fixed by the toolkit." \ % (offset, obj, boundary, string, start, end) debug.println(debug.LEVEL_INFO, msg, True) needSadHack = True if needSadHack: sadString, sadStart, sadEnd = self.__findRange(text, offset, start, end, boundary) s = sadString.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "HACK: Attempting to recover from above failure.\n" \ " String: '%s', Start: %i, End: %i." % (s, sadStart, sadEnd) debug.println(debug.LEVEL_INFO, msg, True) return sadString, sadStart, sadEnd s = string.replace(self.EMBEDDED_OBJECT_CHARACTER, "[OBJ]").replace("\n", "\\n") msg = "WEB: Results for text at offset %i for %s using %s:\n" \ " String: '%s', Start: %i, End: %i." % (offset, obj, boundary, s, start, end) debug.println(debug.LEVEL_INFO, msg, True) return string, start, end def _getContentsForObj(self, obj, offset, boundary): if not obj: return [] if boundary == pyatspi.TEXT_BOUNDARY_LINE_START: if self.isMath(obj): if self.isMathTopLevel(obj): math = obj else: math = self.getMathAncestor(obj) return [[math, 0, 1, '']] text = self.queryNonEmptyText(obj) if self.elementLinesAreSingleChars(obj): if obj.name and text: msg = "WEB: Returning name as contents for %s (single-char lines)" % obj debug.println(debug.LEVEL_INFO, msg, True) return [[obj, 0, text.characterCount, obj.name]] msg = "WEB: Returning all text as contents for %s (single-char lines)" % obj debug.println(debug.LEVEL_INFO, msg, True) boundary = None if self.elementLinesAreSingleWords(obj): if obj.name and text: msg = "WEB: Returning name as contents for %s (single-word lines)" % obj debug.println(debug.LEVEL_INFO, msg, True) return [[obj, 0, text.characterCount, obj.name]] msg = "WEB: Returning all text as contents for %s (single-word lines)" % obj debug.println(debug.LEVEL_INFO, msg, True) boundary = None role = obj.getRole() if role == pyatspi.ROLE_INTERNAL_FRAME and obj.childCount == 1: return self._getContentsForObj(obj[0], 0, boundary) string, start, end = self._getTextAtOffset(obj, offset, boundary) if not string: return [[obj, start, end, string]] stringOffset = offset - start try: char = string[stringOffset] except: pass else: if char == self.EMBEDDED_OBJECT_CHARACTER: child = self.getChildAtOffset(obj, offset) if child: return self._getContentsForObj(child, 0, boundary) ranges = [m.span() for m in re.finditer("[^\ufffc]+", string)] strings = list(filter(lambda x: x[0] <= stringOffset <= x[1], ranges)) if len(strings) == 1: rangeStart, rangeEnd = strings[0] start += rangeStart string = string[rangeStart:rangeEnd] end = start + len(string) return [[obj, start, end, string]] def getSentenceContentsAtOffset(self, obj, offset, useCache=True): if not obj: return [] offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentSentenceContents, usingCache=True) != -1: return self._currentSentenceContents boundary = pyatspi.TEXT_BOUNDARY_SENTENCE_START objects = self._getContentsForObj(obj, offset, boundary) state = obj.getState() if state.contains(pyatspi.STATE_EDITABLE) \ and state.contains(pyatspi.STATE_FOCUSED): return objects def _treatAsSentenceEnd(x): xObj, xStart, xEnd, xString = x if not self.isTextBlockElement(xObj): return False text = self.queryNonEmptyText(xObj) if text and 0 < text.characterCount <= xEnd: return True if 0 <= xStart <= 5: xString = " ".join(xString.split()[1:]) match = re.search(r"\S[\.\!\?]+(\s|\Z)", xString) return match is not None # Check for things in the same sentence before this object. firstObj, firstStart, firstEnd, firstString = objects[0] while firstObj and firstString: if self.isTextBlockElement(firstObj): if firstStart == 0: break elif self.isTextBlockElement(firstObj.parent): if self.characterOffsetInParent(firstObj) == 0: break prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) onLeft = self._getContentsForObj(prevObj, pOffset, boundary) onLeft = list(filter(lambda x: x not in objects, onLeft)) endsOnLeft = list(filter(_treatAsSentenceEnd, onLeft)) if endsOnLeft: i = onLeft.index(endsOnLeft[-1]) onLeft = onLeft[i+1:] if not onLeft: break objects[0:0] = onLeft firstObj, firstStart, firstEnd, firstString = objects[0] # Check for things in the same sentence after this object. while not _treatAsSentenceEnd(objects[-1]): lastObj, lastStart, lastEnd, lastString = objects[-1] nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) onRight = self._getContentsForObj(nextObj, nOffset, boundary) onRight = list(filter(lambda x: x not in objects, onRight)) if not onRight: break objects.extend(onRight) if useCache: self._currentSentenceContents = objects return objects def getCharacterContentsAtOffset(self, obj, offset, useCache=True): if not obj: return [] offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentCharacterContents, usingCache=True) != -1: return self._currentCharacterContents boundary = pyatspi.TEXT_BOUNDARY_CHAR objects = self._getContentsForObj(obj, offset, boundary) if useCache: self._currentCharacterContents = objects return objects def getWordContentsAtOffset(self, obj, offset, useCache=True): if not obj: return [] offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentWordContents, usingCache=True) != -1: self._debugContentsInfo(obj, offset, self._currentWordContents, "Word (cached)") return self._currentWordContents boundary = pyatspi.TEXT_BOUNDARY_WORD_START objects = self._getContentsForObj(obj, offset, boundary) extents = self.getExtents(obj, offset, offset + 1) def _include(x): if x in objects: return False xObj, xStart, xEnd, xString = x if xStart == xEnd or not xString: return False xExtents = self.getExtents(xObj, xStart, xStart + 1) return self.extentsAreOnSameLine(extents, xExtents) # Check for things in the same word to the left of this object. firstObj, firstStart, firstEnd, firstString = objects[0] prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) while prevObj and firstString and prevObj != firstObj: text = self.queryNonEmptyText(prevObj) if not text or text.getText(pOffset, pOffset + 1).isspace(): break onLeft = self._getContentsForObj(prevObj, pOffset, boundary) onLeft = list(filter(_include, onLeft)) if not onLeft: break if self._contentIsSubsetOf(objects[0], onLeft[-1]): objects.pop(0) objects[0:0] = onLeft firstObj, firstStart, firstEnd, firstString = objects[0] prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) # Check for things in the same word to the right of this object. lastObj, lastStart, lastEnd, lastString = objects[-1] while lastObj and lastString and not lastString[-1].isspace(): nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) if nextObj == lastObj: break onRight = self._getContentsForObj(nextObj, nOffset, boundary) if onRight and self._contentIsSubsetOf(objects[0], onRight[-1]): onRight = onRight[0:-1] onRight = list(filter(_include, onRight)) if not onRight: break objects.extend(onRight) lastObj, lastStart, lastEnd, lastString = objects[-1] # We want to treat the list item marker as its own word. firstObj, firstStart, firstEnd, firstString = objects[0] if firstStart == 0 and firstObj.getRole() == pyatspi.ROLE_LIST_ITEM: objects = [objects[0]] if useCache: self._currentWordContents = objects self._debugContentsInfo(obj, offset, objects, "Word (not cached)") return objects def getObjectContentsAtOffset(self, obj, offset=0, useCache=True): if not obj: return [] offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentObjectContents, usingCache=True) != -1: return self._currentObjectContents objIsLandmark = self.isLandmark(obj) def _isInObject(x): if not x: return False if x == obj: return True return _isInObject(x.parent) def _include(x): if x in objects: return False xObj, xStart, xEnd, xString = x if xStart == xEnd: return False if objIsLandmark and self.isLandmark(xObj) and obj != xObj: return False return _isInObject(xObj) objects = self._getContentsForObj(obj, offset, None) lastObj, lastStart, lastEnd, lastString = objects[-1] nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) while nextObj: onRight = self._getContentsForObj(nextObj, nOffset, None) onRight = list(filter(_include, onRight)) if not onRight: break objects.extend(onRight) lastObj, lastEnd = objects[-1][0], objects[-1][2] nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) if useCache: self._currentObjectContents = objects return objects def _contentIsSubsetOf(self, contentA, contentB): objA, startA, endA, stringA = contentA objB, startB, endB, stringB = contentB if objA == objB: setA = set(range(startA, endA)) setB = set(range(startB, endB)) return setA.issubset(setB) return False def _debugContentsInfo(self, obj, offset, contents, contentsMsg=""): if debug.LEVEL_INFO < debug.debugLevel: return msg = "WEB: %s for %s at offset %i:" % (contentsMsg, obj, offset) debug.println(debug.LEVEL_INFO, msg, True) for i, (acc, start, end, string) in enumerate(contents): indent = " " * 8 try: extents = self.getExtents(acc, start, end) except: extents = "(exception)" states = debug.statesToString(acc, indent) attrs = debug.attributesToString(acc, indent) msg = " %i. %s (chars: %i-%i) '%s' extents=%s\n%s\n%s" % \ (i, acc, start, end, string, extents, states, attrs) debug.println(debug.LEVEL_INFO, msg, True) def treatAsEndOfLine(self, obj, offset): if not self.isContentEditableWithEmbeddedObjects(obj): return False if "Text" not in pyatspi.listInterfaces(obj): return False if self.isDocument(obj): return False text = obj.queryText() if offset == text.characterCount: msg = "WEB: %s offset %i is end of line: offset is characterCount" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return True # Do not treat a literal newline char as the end of line. When there is an # actual newline character present, user agents should give us the right value # for the line at that offset. Here we are trying to figure out where asking # for the line at offset will give us the next line rather than the line where # the cursor is physically blinking. char = text.getText(offset, offset + 1) if char == self.EMBEDDED_OBJECT_CHARACTER: prevExtents = self.getExtents(obj, offset - 1, offset) thisExtents = self.getExtents(obj, offset, offset + 1) sameLine = self.extentsAreOnSameLine(prevExtents, thisExtents) msg = "WEB: %s offset %i is [obj]. Same line: %s Is end of line: %s" % \ (obj, offset, sameLine, not sameLine) debug.println(debug.LEVEL_INFO, msg, True) return not sameLine return False def getLineContentsAtOffset(self, obj, offset, layoutMode=None, useCache=True): if not obj: return [] text = self.queryNonEmptyText(obj) offset = max(0, offset) if useCache: if self.findObjectInContents(obj, offset, self._currentLineContents, usingCache=True) != -1: self._debugContentsInfo(obj, offset, self._currentLineContents, "Line (cached)") return self._currentLineContents if layoutMode is None: layoutMode = _settingsManager.getSetting('layoutMode') or self._script.inFocusMode() objects = [] if offset > 0 and self.treatAsEndOfLine(obj, offset): extents = self.getExtents(obj, offset - 1, offset) else: extents = self.getExtents(obj, offset, offset + 1) if self.isInlineListDescendant(obj): container = self.listForInlineListDescendant(obj) if container: extents = self.getExtents(container, 0, 1) objBanner = pyatspi.findAncestor(obj, self.isLandmarkBanner) def _include(x): if x in objects: return False xObj, xStart, xEnd, xString = x if xStart == xEnd: return False xExtents = self.getExtents(xObj, xStart, xStart + 1) if obj != xObj: if self.isLandmark(obj) and self.isLandmark(xObj): return False if self.isLink(obj) and self.isLink(xObj): xObjBanner = pyatspi.findAncestor(xObj, self.isLandmarkBanner) if (objBanner or xObjBanner) and objBanner != xObjBanner: return False if abs(extents[0] - xExtents[0]) <= 1 and abs(extents[1] - xExtents[1]) <= 1: # This happens with dynamic skip links such as found on Wikipedia. return False elif self.isBlockListDescendant(obj) != self.isBlockListDescendant(xObj): return False if self.isMathTopLevel(xObj) or self.isMath(obj): onSameLine = self.extentsAreOnSameLine(extents, xExtents, extents[3]) else: onSameLine = self.extentsAreOnSameLine(extents, xExtents) return onSameLine boundary = pyatspi.TEXT_BOUNDARY_LINE_START objects = self._getContentsForObj(obj, offset, boundary) if not layoutMode: if useCache: self._currentLineContents = objects self._debugContentsInfo(obj, offset, objects, "Line (not layout mode)") return objects firstObj, firstStart, firstEnd, firstString = objects[0] if (extents[2] == 0 and extents[3] == 0) or self.isMath(firstObj): extents = self.getExtents(firstObj, firstStart, firstEnd) lastObj, lastStart, lastEnd, lastString = objects[-1] if self.isMathTopLevel(lastObj): lastObj, lastEnd = self.lastContext(lastObj) lastEnd += 1 document = self.getDocumentForObject(obj) prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) # Check for things on the same line to the left of this object. while prevObj and self.getDocumentForObject(prevObj) == document: text = self.queryNonEmptyText(prevObj) if text and text.getText(pOffset, pOffset + 1) in [" ", "\xa0"]: prevObj, pOffset = self.findPreviousCaretInOrder(prevObj, pOffset) onLeft = self._getContentsForObj(prevObj, pOffset, boundary) onLeft = list(filter(_include, onLeft)) if not onLeft: break if self._contentIsSubsetOf(objects[0], onLeft[-1]): objects.pop(0) objects[0:0] = onLeft firstObj, firstStart = objects[0][0], objects[0][1] prevObj, pOffset = self.findPreviousCaretInOrder(firstObj, firstStart) # Check for things on the same line to the right of this object. while nextObj and self.getDocumentForObject(nextObj) == document: text = self.queryNonEmptyText(nextObj) if text and text.getText(nOffset, nOffset + 1) in [" ", "\xa0"]: nextObj, nOffset = self.findNextCaretInOrder(nextObj, nOffset) onRight = self._getContentsForObj(nextObj, nOffset, boundary) if onRight and self._contentIsSubsetOf(objects[0], onRight[-1]): onRight = onRight[0:-1] onRight = list(filter(_include, onRight)) if not onRight: break objects.extend(onRight) lastObj, lastEnd = objects[-1][0], objects[-1][2] if self.isMathTopLevel(lastObj): lastObj, lastEnd = self.lastContext(lastObj) lastEnd += 1 nextObj, nOffset = self.findNextCaretInOrder(lastObj, lastEnd - 1) firstObj, firstStart, firstEnd, firstString = objects[0] if firstString == "\n" and len(objects) > 1: objects.pop(0) if useCache: self._currentLineContents = objects self._debugContentsInfo(obj, offset, objects, "Line (layout mode)") return objects def getPreviousLineContents(self, obj=None, offset=-1, layoutMode=None, useCache=True): if obj is None: obj, offset = self.getCaretContext() msg = "WEB: Current context is: %s, %i (focus: %s)" \ % (obj, offset, orca_state.locusOfFocus) debug.println(debug.LEVEL_INFO, msg, True) if obj and self.isZombie(obj): msg = "WEB: Current context obj %s is zombie. Clearing cache." % obj debug.println(debug.LEVEL_INFO, msg, True) self.clearCachedObjects() obj, offset = self.getCaretContext() msg = "WEB: Now Current context is: %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) line = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if not (line and line[0]): return [] firstObj, firstOffset = line[0][0], line[0][1] msg = "WEB: First context on line is: %s, %i" % (firstObj, firstOffset) debug.println(debug.LEVEL_INFO, msg, True) obj, offset = self.previousContext(firstObj, firstOffset, True) if not obj and firstObj: msg = "WEB: Previous context is: %s, %i. Trying again." % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) self.clearCachedObjects() obj, offset = self.previousContext(firstObj, firstOffset, True) msg = "WEB: Previous context is: %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) contents = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if not contents: msg = "WEB: Could not get line contents for %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return [] return contents def getNextLineContents(self, obj=None, offset=-1, layoutMode=None, useCache=True): if obj is None: obj, offset = self.getCaretContext() msg = "WEB: Current context is: %s, %i (focus: %s)" \ % (obj, offset, orca_state.locusOfFocus) debug.println(debug.LEVEL_INFO, msg, True) if obj and self.isZombie(obj): msg = "WEB: Current context obj %s is zombie. Clearing cache." % obj debug.println(debug.LEVEL_INFO, msg, True) self.clearCachedObjects() obj, offset = self.getCaretContext() msg = "WEB: Now Current context is: %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) line = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if not (line and line[0]): return [] lastObj, lastOffset = line[-1][0], line[-1][2] - 1 math = self.getMathAncestor(lastObj) if math: lastObj, lastOffset = self.lastContext(math) msg = "WEB: Last context on line is: %s, %i" % (lastObj, lastOffset) debug.println(debug.LEVEL_INFO, msg, True) obj, offset = self.nextContext(lastObj, lastOffset, True) if not obj and lastObj: msg = "WEB: Next context is: %s, %i. Trying again." % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) self.clearCachedObjects() obj, offset = self.nextContext(lastObj, lastOffset, True) msg = "WEB: Next context is: %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) contents = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if line == contents: obj, offset = self.nextContext(obj, offset, True) msg = "WEB: Got same line. Trying again with %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) contents = self.getLineContentsAtOffset(obj, offset, layoutMode, useCache) if not contents: msg = "WEB: Could not get line contents for %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return [] return contents def updateCachedTextSelection(self, obj): if not self.inDocumentContent(obj): super().updateCachedTextSelection(obj) return if self.hasPresentableText(obj): super().updateCachedTextSelection(obj) def handleTextSelectionChange(self, obj, speakMessage=True): if not self.inDocumentContent(obj): return super().handleTextSelectionChange(obj) oldStart, oldEnd = self._script.pointOfReference.get('selectionAnchorAndFocus', (None, None)) start, end = self._getSelectionAnchorAndFocus(obj) self._script.pointOfReference['selectionAnchorAndFocus'] = (start, end) def _cmp(obj1, obj2): return self.pathComparison(pyatspi.getPath(obj1), pyatspi.getPath(obj2)) oldSubtree = self._getSubtree(oldStart, oldEnd) if start == oldStart and end == oldEnd: descendants = oldSubtree else: newSubtree = self._getSubtree(start, end) descendants = sorted(set(oldSubtree).union(newSubtree), key=functools.cmp_to_key(_cmp)) if not descendants: return False for descendant in descendants: if descendant not in (oldStart, oldEnd, start, end) \ and pyatspi.findAncestor(descendant, lambda x: x in descendants): super().updateCachedTextSelection(descendant) else: super().handleTextSelectionChange(descendant, speakMessage) return True def inPDFViewer(self, obj=None): uri = self.documentFrameURI() return uri.lower().endswith(".pdf") def inTopLevelWebApp(self, obj=None): if not obj: obj = orca_state.locusOfFocus rv = self._inTopLevelWebApp.get(hash(obj)) if rv is not None: return rv document = self.getDocumentForObject(obj) if not document and self.isDocument(obj): document = obj rv = self.isTopLevelWebApp(document) self._inTopLevelWebApp[hash(obj)] = rv return rv def isTopLevelWebApp(self, obj): try: role = obj.getRole() except: msg = "WEB: Exception getting role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if role == pyatspi.ROLE_EMBEDDED and not self.getDocumentForObject(obj.parent): uri = self.documentFrameURI() rv = bool(uri and uri.startswith("http")) msg = "WEB: %s is top-level web application: %s (URI: %s)" % (obj, rv, uri) debug.println(debug.LEVEL_INFO, msg, True) return rv return False def forceBrowseModeForWebAppDescendant(self, obj): if not self.isWebAppDescendant(obj): return False if obj.getRole() == pyatspi.ROLE_TOOL_TIP: return obj.getState().contains(pyatspi.STATE_FOCUSED) return False def isFocusModeWidget(self, obj): try: role = obj.getRole() state = obj.getState() except: msg = "WEB: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if state.contains(pyatspi.STATE_EDITABLE): msg = "WEB: %s is focus mode widget because it's editable" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if state.contains(pyatspi.STATE_EXPANDABLE) and state.contains(pyatspi.STATE_FOCUSABLE): msg = "WEB: %s is focus mode widget because it's expandable and focusable" % obj debug.println(debug.LEVEL_INFO, msg, True) return True alwaysFocusModeRoles = [pyatspi.ROLE_COMBO_BOX, pyatspi.ROLE_ENTRY, pyatspi.ROLE_LIST_BOX, pyatspi.ROLE_MENU, pyatspi.ROLE_MENU_ITEM, pyatspi.ROLE_CHECK_MENU_ITEM, pyatspi.ROLE_RADIO_MENU_ITEM, pyatspi.ROLE_PAGE_TAB, pyatspi.ROLE_PASSWORD_TEXT, pyatspi.ROLE_PROGRESS_BAR, pyatspi.ROLE_SLIDER, pyatspi.ROLE_SPIN_BUTTON, pyatspi.ROLE_TOOL_BAR, pyatspi.ROLE_TREE_ITEM, pyatspi.ROLE_TREE_TABLE, pyatspi.ROLE_TREE] if role in alwaysFocusModeRoles: msg = "WEB: %s is focus mode widget due to its role" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if role in [pyatspi.ROLE_TABLE_CELL, pyatspi.ROLE_TABLE] \ and self.isLayoutOnly(self.getTable(obj)): msg = "WEB: %s is not focus mode widget because it's layout only" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isButtonWithPopup(obj): msg = "WEB: %s is focus mode widget because it's a button with popup" % obj debug.println(debug.LEVEL_INFO, msg, True) return True focusModeRoles = [pyatspi.ROLE_EMBEDDED, pyatspi.ROLE_LIST_ITEM, pyatspi.ROLE_TABLE_CELL, pyatspi.ROLE_TABLE] if role in focusModeRoles \ and not self.isTextBlockElement(obj) \ and not self.hasNameAndActionAndNoUsefulChildren(obj) \ and not self.inPDFViewer(obj): msg = "WEB: %s is focus mode widget based on presumed functionality" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isGridDescendant(obj): msg = "WEB: %s is focus mode widget because it's a grid descendant" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isMenuDescendant(obj): msg = "WEB: %s is focus mode widget because it's a menu descendant" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isToolBarDescendant(obj): msg = "WEB: %s is focus mode widget because it's a toolbar descendant" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isContentEditableWithEmbeddedObjects(obj): msg = "WEB: %s is focus mode widget because it's content editable" % obj debug.println(debug.LEVEL_INFO, msg, True) return True return False def _cellRoles(self): roles = [pyatspi.ROLE_TABLE_CELL, pyatspi.ROLE_TABLE_COLUMN_HEADER, pyatspi.ROLE_TABLE_ROW_HEADER, pyatspi.ROLE_ROW_HEADER, pyatspi.ROLE_COLUMN_HEADER] return roles def _textBlockElementRoles(self): roles = [pyatspi.ROLE_ARTICLE, pyatspi.ROLE_CAPTION, pyatspi.ROLE_COLUMN_HEADER, pyatspi.ROLE_COMMENT, pyatspi.ROLE_DEFINITION, pyatspi.ROLE_DESCRIPTION_LIST, pyatspi.ROLE_DESCRIPTION_TERM, pyatspi.ROLE_DESCRIPTION_VALUE, pyatspi.ROLE_DOCUMENT_FRAME, pyatspi.ROLE_DOCUMENT_WEB, pyatspi.ROLE_FOOTER, pyatspi.ROLE_FORM, pyatspi.ROLE_HEADING, pyatspi.ROLE_LIST, pyatspi.ROLE_LIST_ITEM, pyatspi.ROLE_PARAGRAPH, pyatspi.ROLE_ROW_HEADER, pyatspi.ROLE_SECTION, pyatspi.ROLE_STATIC, pyatspi.ROLE_TEXT, pyatspi.ROLE_TABLE_CELL] # Remove this check when we bump dependencies to 2.34 try: roles.append(pyatspi.ROLE_CONTENT_DELETION) roles.append(pyatspi.ROLE_CONTENT_INSERTION) except: pass # Remove this check when we bump dependencies to 2.36 try: roles.append(pyatspi.ROLE_MARK) roles.append(pyatspi.ROLE_SUGGESTION) except: pass return roles def mnemonicShortcutAccelerator(self, obj): if not (obj and self.inDocumentContent(obj)): return super().mnemonicShortcutAccelerator(obj) attrs = self.objectAttributes(obj) keys = map(lambda x: x.replace("+", " "), attrs.get("keyshortcuts", "").split(" ")) keys = map(lambda x: x.replace(" ", "+"), map(self.labelFromKeySequence, keys)) rv = ["", " ".join(keys), ""] if list(filter(lambda x: x, rv)): return rv return super().mnemonicShortcutAccelerator(obj) def unrelatedLabels(self, root, onlyShowing=True, minimumWords=3): if not (root and self.inDocumentContent(root)): return super().unrelatedLabels(root, onlyShowing, minimumWords) return [] def isFocusableWithMathChild(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isFocusableWithMathChild.get(hash(obj)) if rv is not None: return rv try: state = obj.getState() except: msg = "WEB: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False rv = False if state.contains(pyatspi.STATE_FOCUSABLE) and not self.isDocument(obj): for child in obj: if self.isMathTopLevel(child): rv = True break self._isFocusableWithMathChild[hash(obj)] = rv return rv def isFocusedWithMathChild(self, obj): if not self.isFocusableWithMathChild(obj): return False try: state = obj.getState() except: msg = "WEB: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False return state.contains(pyatspi.STATE_FOCUSED) def isTextBlockElement(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isTextBlockElement.get(hash(obj)) if rv is not None: return rv try: role = obj.getRole() state = obj.getState() interfaces = pyatspi.listInterfaces(obj) except: msg = "WEB: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False textBlockElements = self._textBlockElementRoles() if not role in textBlockElements: rv = False elif not "Text" in interfaces: rv = False elif not obj.queryText().characterCount: rv = False elif state.contains(pyatspi.STATE_EDITABLE): rv = False elif role in [pyatspi.ROLE_DOCUMENT_FRAME, pyatspi.ROLE_DOCUMENT_WEB]: rv = True elif not state.contains(pyatspi.STATE_FOCUSABLE) and not state.contains(pyatspi.STATE_FOCUSED): rv = not self.hasNameAndActionAndNoUsefulChildren(obj) else: rv = False self._isTextBlockElement[hash(obj)] = rv return rv def _advanceCaretInEmptyObject(self, obj): role = obj.getRole() if role == pyatspi.ROLE_TABLE_CELL and not self.queryNonEmptyText(obj): return not self._script._lastCommandWasStructNav return True def textAtPoint(self, obj, x, y, coordType=None, boundary=None): if coordType is None: coordType = pyatspi.DESKTOP_COORDS if boundary is None: boundary = pyatspi.TEXT_BOUNDARY_LINE_START string, start, end = super().textAtPoint(obj, x, y, coordType, boundary) if string == self.EMBEDDED_OBJECT_CHARACTER: child = self.getChildAtOffset(obj, start) if child: return self.textAtPoint(child, x, y, coordType, boundary) return string, start, end def _treatAlertsAsDialogs(self): return False def treatAsDiv(self, obj, offset=None): if not (obj and self.inDocumentContent(obj)): return False try: role = obj.getRole() childCount = obj.childCount except: msg = "WEB: Exception getting role and childCount for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if role == pyatspi.ROLE_LIST and offset is not None: string = self.substring(obj, offset, offset + 1) if string and string != self.EMBEDDED_OBJECT_CHARACTER: return True if role == pyatspi.ROLE_PANEL and not childCount: return True rv = self._treatAsDiv.get(hash(obj)) if rv is not None: return rv validRoles = self._validChildRoles.get(role) if validRoles: if not childCount: rv = True else: rv = bool([x for x in obj if x and x.getRole() not in validRoles]) if not rv: validRoles = self._validChildRoles.get(obj.parent) if validRoles: rv = bool([x for x in obj.parent if x and x.getRole() not in validRoles]) self._treatAsDiv[hash(obj)] = rv return rv def isBlockquote(self, obj): if super().isBlockquote(obj): return True return self._getTag(obj) == 'blockquote' def isComment(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isComment(obj) if obj.getRole() == pyatspi.ROLE_COMMENT: return True return 'comment' in self._getXMLRoles(obj) def isContentDeletion(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentDeletion(obj) # Remove this check when we bump dependencies to 2.34 try: if obj.getRole() == pyatspi.ROLE_CONTENT_DELETION: return True except: pass return 'deletion' in self._getXMLRoles(obj) or 'del' == self._getTag(obj) def isContentError(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentError(obj) if obj.getRole() not in self._textBlockElementRoles(): return False return obj.getState().contains(pyatspi.STATE_INVALID_ENTRY) def isContentInsertion(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentInsertion(obj) # Remove this check when we bump dependencies to 2.34 try: if obj.getRole() == pyatspi.ROLE_CONTENT_INSERTION: return True except: pass return 'insertion' in self._getXMLRoles(obj) or 'ins' == self._getTag(obj) def isContentMarked(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentMarked(obj) # Remove this check when we bump dependencies to 2.36 try: if obj.getRole() == pyatspi.ROLE_MARK: return True except: pass return 'mark' in self._getXMLRoles(obj) or 'mark' == self._getTag(obj) def isContentSuggestion(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isContentSuggestion(obj) # Remove this check when we bump dependencies to 2.36 try: if obj.getRole() == pyatspi.ROLE_SUGGESTION: return True except: pass return 'suggestion' in self._getXMLRoles(obj) def isInlineIframe(self, obj): if not (obj and obj.getRole() == pyatspi.ROLE_INTERNAL_FRAME): return False displayStyle = self._getDisplayStyle(obj) if "inline" not in displayStyle: return False return self.documentForObject(obj) is not None def isInlineIframeDescendant(self, obj): if not obj: return False rv = self._isInlineIframeDescendant.get(hash(obj)) if rv is not None: return rv ancestor = pyatspi.findAncestor(obj, self.isInlineIframe) rv = ancestor is not None self._isInlineIframeDescendant[hash(obj)] = rv return rv def isInlineSuggestion(self, obj): if not self.isContentSuggestion(obj): return False displayStyle = self._getDisplayStyle(obj) return "inline" in displayStyle def isFirstItemInInlineContentSuggestion(self, obj): suggestion = pyatspi.findAncestor(obj, self.isInlineSuggestion) if not (suggestion and suggestion.childCount): return False return suggestion[0] == obj def isLastItemInInlineContentSuggestion(self, obj): suggestion = pyatspi.findAncestor(obj, self.isInlineSuggestion) if not (suggestion and suggestion.childCount): return False return suggestion[-1] == obj def speakMathSymbolNames(self, obj=None): obj = obj or orca_state.locusOfFocus return self.isMath(obj) def isInMath(self): return self.isMath(orca_state.locusOfFocus) def isMath(self, obj): tag = self._getTag(obj) rv = tag in ['math', 'maction', 'maligngroup', 'malignmark', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mlongdiv', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot', 'mrow', 'ms', 'mscarries', 'mscarry', 'msgroup', 'msline', 'mspace', 'msqrt', 'msrow', 'mstack', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover'] return rv def isNoneElement(self, obj): return self._getTag(obj) == 'none' def isMathLayoutOnly(self, obj): return self._getTag(obj) in ['mrow', 'mstyle', 'merror', 'mpadded'] def isMathMultiline(self, obj): return self._getTag(obj) in ['mtable', 'mstack', 'mlongdiv'] def isMathEnclose(self, obj): return self._getTag(obj) == 'menclose' def isMathFenced(self, obj): return self._getTag(obj) == 'mfenced' def isMathFractionWithoutBar(self, obj): try: role = obj.getRole() except: msg = "ERROR: Exception getting role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) if role != pyatspi.ROLE_MATH_FRACTION: return False attrs = self.objectAttributes(obj) linethickness = attrs.get('linethickness') if not linethickness: return False for char in linethickness: if char.isnumeric() and char != '0': return False return True def isMathPhantom(self, obj): return self._getTag(obj) == 'mphantom' def isMathMultiScript(self, obj): return self._getTag(obj) == 'mmultiscripts' def _isMathPrePostScriptSeparator(self, obj): return self._getTag(obj) == 'mprescripts' def isMathSubOrSuperScript(self, obj): return self._getTag(obj) in ['msub', 'msup', 'msubsup'] def isMathTable(self, obj): return self._getTag(obj) == 'mtable' def isMathTableRow(self, obj): return self._getTag(obj) in ['mtr', 'mlabeledtr'] def isMathTableCell(self, obj): return self._getTag(obj) == 'mtd' def isMathUnderOrOverScript(self, obj): return self._getTag(obj) in ['mover', 'munder', 'munderover'] def _isMathSubElement(self, obj): return self._getTag(obj) == 'msub' def _isMathSupElement(self, obj): return self._getTag(obj) == 'msup' def _isMathSubsupElement(self, obj): return self._getTag(obj) == 'msubsup' def _isMathUnderElement(self, obj): return self._getTag(obj) == 'munder' def _isMathOverElement(self, obj): return self._getTag(obj) == 'mover' def _isMathUnderOverElement(self, obj): return self._getTag(obj) == 'munderover' def isMathSquareRoot(self, obj): return self._getTag(obj) == 'msqrt' def isMathToken(self, obj): return self._getTag(obj) in ['mi', 'mn', 'mo', 'mtext', 'ms', 'mspace'] def isMathTopLevel(self, obj): return obj.getRole() == pyatspi.ROLE_MATH def getMathAncestor(self, obj): if not self.isMath(obj): return None if self.isMathTopLevel(obj): return obj return pyatspi.findAncestor(obj, self.isMathTopLevel) def getMathDenominator(self, obj): try: return obj[1] except: pass return None def getMathNumerator(self, obj): try: return obj[0] except: pass return None def getMathRootBase(self, obj): if self.isMathSquareRoot(obj): return obj try: return obj[0] except: pass return None def getMathRootIndex(self, obj): try: return obj[1] except: pass return None def getMathScriptBase(self, obj): if self.isMathSubOrSuperScript(obj) \ or self.isMathUnderOrOverScript(obj) \ or self.isMathMultiScript(obj): return obj[0] return None def getMathScriptSubscript(self, obj): if self._isMathSubElement(obj) or self._isMathSubsupElement(obj): return obj[1] return None def getMathScriptSuperscript(self, obj): if self._isMathSupElement(obj): return obj[1] if self._isMathSubsupElement(obj): return obj[2] return None def getMathScriptUnderscript(self, obj): if self._isMathUnderElement(obj) or self._isMathUnderOverElement(obj): return obj[1] return None def getMathScriptOverscript(self, obj): if self._isMathOverElement(obj): return obj[1] if self._isMathUnderOverElement(obj): return obj[2] return None def _getMathPrePostScriptSeparator(self, obj): for child in obj: if self._isMathPrePostScriptSeparator(child): return child return None def getMathPrescripts(self, obj): separator = self._getMathPrePostScriptSeparator(obj) if not separator: return [] index = separator.getIndexInParent() return [obj[i] for i in range(index+1, obj.childCount)] def getMathPostscripts(self, obj): separator = self._getMathPrePostScriptSeparator(obj) if separator: index = separator.getIndexInParent() else: index = obj.childCount return [obj[i] for i in range(1, index)] def getMathEnclosures(self, obj): if not self.isMathEnclose(obj): return [] attrs = self.objectAttributes(obj) return attrs.get('notation', 'longdiv').split() def getMathFencedSeparators(self, obj): if not self.isMathFenced(obj): return [''] attrs = self.objectAttributes(obj) return list(attrs.get('separators', ',')) def getMathFences(self, obj): if not self.isMathFenced(obj): return ['', ''] attrs = self.objectAttributes(obj) return [attrs.get('open', '('), attrs.get('close', ')')] def getMathNestingLevel(self, obj, test=None): rv = self._mathNestingLevel.get(hash(obj)) if rv is not None: return rv if not test: test = lambda x: self._getTag(x) == self._getTag(obj) rv = -1 ancestor = obj while ancestor: ancestor = pyatspi.findAncestor(ancestor, test) rv += 1 self._mathNestingLevel[hash(obj)] = rv return rv def filterContentsForPresentation(self, contents, inferLabels=False): def _include(x): obj, start, end, string = x if not obj: return False rv = self._shouldFilter.get(hash(obj)) if rv is not None: return rv displayedText = string or obj.name rv = True if ((self.isTextBlockElement(obj) or self.isLink(obj)) and not displayedText) \ or (self.isContentEditableWithEmbeddedObjects(obj) and not string.strip()) \ or self.isEmptyAnchor(obj) \ or (self.hasNoSize(obj) and not displayedText) \ or self.isHidden(obj) \ or self.isOffScreenLabel(obj) \ or self.isUselessImage(obj) \ or self.isErrorForContents(obj, contents) \ or self.isLabellingContents(obj, contents): rv = False elif obj.getRole() == pyatspi.ROLE_TABLE_ROW: rv = self.hasExplicitName(obj) else: widget = self.isInferredLabelForContents(x, contents) alwaysFilter = [pyatspi.ROLE_RADIO_BUTTON, pyatspi.ROLE_CHECK_BOX] if widget and (inferLabels or widget.getRole() in alwaysFilter): rv = False self._shouldFilter[hash(obj)] = rv return rv if len(contents) == 1: return contents rv = list(filter(_include, contents)) self._shouldFilter = {} return rv def needsSeparator(self, lastChar, nextChar): if lastChar.isspace() or nextChar.isspace(): return False openingPunctuation = ["(", "[", "{", "<"] closingPunctuation = [".", "?", "!", ":", ",", ";", ")", "]", "}", ">"] if lastChar in closingPunctuation or nextChar in openingPunctuation: return True if lastChar in openingPunctuation or nextChar in closingPunctuation: return False return lastChar.isalnum() def supportsSelectionAndTable(self, obj): interfaces = pyatspi.listInterfaces(obj) return 'Table' in interfaces and 'Selection' in interfaces def isGridDescendant(self, obj): if not obj: return False rv = self._isGridDescendant.get(hash(obj)) if rv is not None: return rv rv = pyatspi.findAncestor(obj, self.supportsSelectionAndTable) is not None self._isGridDescendant[hash(obj)] = rv return rv def isSorted(self, obj): attrs = self.objectAttributes(obj, False) return not attrs.get("sort") in ("none", None) def isAscending(self, obj): attrs = self.objectAttributes(obj, False) return attrs.get("sort") == "ascending" def isDescending(self, obj): attrs = self.objectAttributes(obj, False) return attrs.get("sort") == "descending" def _rowAndColumnIndices(self, obj): rowindex = colindex = None attrs = self.objectAttributes(obj) rowindex = attrs.get('rowindex') colindex = attrs.get('colindex') if rowindex is not None and colindex is not None: return rowindex, colindex isRow = lambda x: x and x.getRole() == pyatspi.ROLE_TABLE_ROW row = pyatspi.findAncestor(obj, isRow) if not row: return rowindex, colindex attrs = self.objectAttributes(row) rowindex = attrs.get('rowindex', rowindex) colindex = attrs.get('colindex', colindex) return rowindex, colindex def isCellWithNameFromHeader(self, obj): role = obj.getRole() if role != pyatspi.ROLE_TABLE_CELL: return False header = self.columnHeaderForCell(obj) if header and header.name and header.name == obj.name: return True header = self.rowHeaderForCell(obj) if header and header.name and header.name == obj.name: return True return False def labelForCellCoordinates(self, obj): attrs = self.objectAttributes(obj) # The ARIA feature is still in the process of being discussed. collabel = attrs.get('colindextext', attrs.get('coltext')) rowlabel = attrs.get('rowindextext', attrs.get('rowtext')) if collabel is not None and rowlabel is not None: return '%s%s' % (collabel, rowlabel) isRow = lambda x: x and x.getRole() == pyatspi.ROLE_TABLE_ROW row = pyatspi.findAncestor(obj, isRow) if not row: return '' attrs = self.objectAttributes(row) collabel = attrs.get('colindextext', attrs.get('coltext', collabel)) rowlabel = attrs.get('rowindextext', attrs.get('rowtext', rowlabel)) if collabel is not None and rowlabel is not None: return '%s%s' % (collabel, rowlabel) return '' def coordinatesForCell(self, obj): roles = [pyatspi.ROLE_TABLE_CELL, pyatspi.ROLE_TABLE_COLUMN_HEADER, pyatspi.ROLE_TABLE_ROW_HEADER, pyatspi.ROLE_COLUMN_HEADER, pyatspi.ROLE_ROW_HEADER] if not (obj and obj.getRole() in roles): return -1, -1 rowindex, colindex = self._rowAndColumnIndices(obj) if rowindex is not None and colindex is not None: return int(rowindex) - 1, int(colindex) - 1 return super().coordinatesForCell(obj) def rowAndColumnCount(self, obj): rows, cols = super().rowAndColumnCount(obj) attrs = self.objectAttributes(obj) rows = attrs.get('rowcount', rows) cols = attrs.get('colcount', cols) return int(rows), int(cols) def shouldReadFullRow(self, obj): if not (obj and self.inDocumentContent(obj)): return super().shouldReadFullRow(obj) if not super().shouldReadFullRow(obj): return False if self.isGridDescendant(obj): return not self._script.inFocusMode() if self.lastInputEventWasLineNav(): return False return True def isEntryDescendant(self, obj): if not obj: return False rv = self._isEntryDescendant.get(hash(obj)) if rv is not None: return rv isEntry = lambda x: x and x.getRole() == pyatspi.ROLE_ENTRY rv = pyatspi.findAncestor(obj, isEntry) is not None self._isEntryDescendant[hash(obj)] = rv return rv def isLabelDescendant(self, obj): if not obj: return False rv = self._isLabelDescendant.get(hash(obj)) if rv is not None: return rv isLabel = lambda x: x and x.getRole() == pyatspi.ROLE_LABEL rv = pyatspi.findAncestor(obj, isLabel) is not None self._isLabelDescendant[hash(obj)] = rv return rv def isMenuInCollapsedSelectElement(self, obj): return False def isMenuDescendant(self, obj): if not obj: return False rv = self._isMenuDescendant.get(hash(obj)) if rv is not None: return rv isMenu = lambda x: x and x.getRole() == pyatspi.ROLE_MENU rv = pyatspi.findAncestor(obj, isMenu) is not None self._isMenuDescendant[hash(obj)] = rv return rv def isNavigableToolTipDescendant(self, obj): if not obj: return False rv = self._isNavigableToolTipDescendant.get(hash(obj)) if rv is not None: return rv isToolTip = lambda x: x and x.getRole() == pyatspi.ROLE_TOOL_TIP if isToolTip(obj): ancestor = obj else: ancestor = pyatspi.findAncestor(obj, isToolTip) rv = ancestor and not self.isNonNavigablePopup(ancestor) self._isNavigableToolTipDescendant[hash(obj)] = rv return rv def isToolBarDescendant(self, obj): if not obj: return False rv = self._isToolBarDescendant.get(hash(obj)) if rv is not None: return rv isToolBar = lambda x: x and x.getRole() == pyatspi.ROLE_TOOL_BAR rv = pyatspi.findAncestor(obj, isToolBar) is not None self._isToolBarDescendant[hash(obj)] = rv return rv def isWebAppDescendant(self, obj): if not obj: return False rv = self._isWebAppDescendant.get(hash(obj)) if rv is not None: return rv isEmbedded = lambda x: x and x.getRole() == pyatspi.ROLE_EMBEDDED rv = pyatspi.findAncestor(obj, isEmbedded) is not None self._isWebAppDescendant[hash(obj)] = rv return rv def isLayoutOnly(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isLayoutOnly(obj) rv = self._isLayoutOnly.get(hash(obj)) if rv is not None: if rv: msg = "WEB: %s is deemed to be layout only" % obj debug.println(debug.LEVEL_INFO, msg, True) return rv try: role = obj.getRole() state = obj.getState() except: msg = "ERROR: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if role == pyatspi.ROLE_LIST: rv = self.treatAsDiv(obj) elif self.isMath(obj): rv = False elif self.isLandmark(obj): rv = False elif self.isContentDeletion(obj): rv = False elif self.isContentInsertion(obj): rv = False elif self.isContentMarked(obj): rv = False elif self.isContentSuggestion(obj): rv = False elif self.isDPub(obj): rv = False elif self.isFeed(obj): rv = False elif self.isFigure(obj): rv = False elif role in [pyatspi.ROLE_COLUMN_HEADER, pyatspi.ROLE_ROW_HEADER]: rv = False elif role == pyatspi.ROLE_PANEL: rv = not self.hasExplicitName(obj) elif role == pyatspi.ROLE_TABLE_ROW and not state.contains(pyatspi.STATE_EXPANDABLE): rv = not self.hasExplicitName(obj) else: rv = super().isLayoutOnly(obj) if rv: msg = "WEB: %s is deemed to be layout only" % obj debug.println(debug.LEVEL_INFO, msg, True) self._isLayoutOnly[hash(obj)] = rv return rv def elementIsPreformattedText(self, obj): if self._getTag(obj) in ["pre", "code"]: return True if "code" in self._getXMLRoles(obj): return True return False def elementLinesAreSingleWords(self, obj): if not (obj and self.inDocumentContent(obj)): return False if self.elementIsPreformattedText(obj): return False rv = self._elementLinesAreSingleWords.get(hash(obj)) if rv is not None: return rv text = self.queryNonEmptyText(obj) if not text: return False try: nChars = text.characterCount except: return False if not nChars: return False try: obj.clearCache() state = obj.getState() except: msg = "ERROR: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False tokens = list(filter(lambda x: x, re.split(r"[\s\ufffc]", text.getText(0, -1)))) # Note: We cannot check for the editable-text interface, because Gecko # seems to be exposing that for non-editable things. Thanks Gecko. rv = not state.contains(pyatspi.STATE_EDITABLE) and len(tokens) > 1 if rv: boundary = pyatspi.TEXT_BOUNDARY_LINE_START i = 0 while i < nChars: string, start, end = text.getTextAtOffset(i, boundary) if len(string.split()) != 1: rv = False break i = max(i+1, end) self._elementLinesAreSingleWords[hash(obj)] = rv return rv def elementLinesAreSingleChars(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._elementLinesAreSingleChars.get(hash(obj)) if rv is not None: return rv text = self.queryNonEmptyText(obj) if not text: return False try: nChars = text.characterCount except: return False if not nChars: return False # If we have a series of embedded object characters, there's a reasonable chance # they'll look like the one-char-per-line CSSified text we're trying to detect. # We don't want that false positive. By the same token, the one-char-per-line # CSSified text we're trying to detect can have embedded object characters. So # if we have more than 30% EOCs, don't use this workaround. (The 30% is based on # testing with problematic text.) eocs = re.findall(self.EMBEDDED_OBJECT_CHARACTER, text.getText(0, -1)) if len(eocs)/nChars > 0.3: return False try: obj.clearCache() state = obj.getState() except: msg = "ERROR: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False # Note: We cannot check for the editable-text interface, because Gecko # seems to be exposing that for non-editable things. Thanks Gecko. rv = not state.contains(pyatspi.STATE_EDITABLE) if rv: boundary = pyatspi.TEXT_BOUNDARY_LINE_START for i in range(nChars): string, start, end = text.getTextAtOffset(i, boundary) if len(string) != 1: rv = False break self._elementLinesAreSingleChars[hash(obj)] = rv return rv def isOffScreenLabel(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isOffScreenLabel.get(hash(obj)) if rv is not None: return rv rv = False isLabelFor = lambda x: x.getRelationType() == pyatspi.RELATION_LABEL_FOR try: relationSet = obj.getRelationSet() except: pass else: relations = list(filter(isLabelFor, relationSet)) if relations: try: text = obj.queryText() end = text.characterCount except: end = 1 x, y, width, height = self.getExtents(obj, 0, end) if x < 0 or y < 0: rv = True self._isOffScreenLabel[hash(obj)] = rv return rv def isDetachedDocument(self, obj): docRoles = [pyatspi.ROLE_DOCUMENT_FRAME, pyatspi.ROLE_DOCUMENT_WEB] if (obj and obj.getRole() in docRoles): if obj.parent is None or self.isZombie(obj.parent): msg = "WEB: %s is a detached document" % obj debug.println(debug.LEVEL_INFO, msg, True) return True return False def iframeForDetachedDocument(self, obj, root=None): root = root or self.documentFrame() isIframe = lambda x: x and x.getRole() == pyatspi.ROLE_INTERNAL_FRAME iframes = self.findAllDescendants(root, isIframe) for iframe in iframes: if obj in iframe: # We won't change behavior, but we do want to log all bogosity. self._isBrokenChildParentTree(obj, iframe) msg = "WEB: Returning %s as iframe parent of detached %s" % (iframe, obj) debug.println(debug.LEVEL_INFO, msg, True) return iframe return None def _objectBoundsMightBeBogus(self, obj): if not (obj and self.inDocumentContent(obj)): return super()._objectBoundsMightBeBogus(obj) if obj.getRole() != pyatspi.ROLE_LINK or "Text" not in pyatspi.listInterfaces(obj): return False text = obj.queryText() start = list(text.getRangeExtents(0, 1, 0)) end = list(text.getRangeExtents(text.characterCount - 1, text.characterCount, 0)) if self.extentsAreOnSameLine(start, end): return False if not self.hasPresentableText(obj.parent): return False msg = "WEB: Objects bounds of %s might be bogus" % obj debug.println(debug.LEVEL_INFO, msg, True) return True def _isBrokenChildParentTree(self, child, parent): if not (child and parent): return False try: childIsChildOfParent = child in parent except: msg = "WEB: Exception checking if %s is in %s" % (child, parent) debug.println(debug.LEVEL_INFO, msg, True) childIsChildOfParent = False else: msg = "WEB: %s is child of %s: %s" % (child, parent, childIsChildOfParent) debug.println(debug.LEVEL_INFO, msg, True) try: parentIsParentOfChild = child.parent == parent except: msg = "WEB: Exception getting parent of %s" % child debug.println(debug.LEVEL_INFO, msg, True) parentIsParentOfChild = False else: msg = "WEB: %s is parent of %s: %s" % (parent, child, parentIsParentOfChild) debug.println(debug.LEVEL_INFO, msg, True) if parentIsParentOfChild != childIsChildOfParent: msg = "FAIL: The above is broken and likely needs to be fixed by the toolkit." debug.println(debug.LEVEL_INFO, msg, True) return True return False def labelTargets(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._labelTargets.get(hash(obj)) if rv is not None: return rv rv = False isLabel = lambda r: r.getRelationType() == pyatspi.RELATION_LABEL_FOR try: relations = list(filter(isLabel, obj.getRelationSet())) except: msg = "WEB: Exception getting relations of %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return [] if not relations: return [] r = relations[0] rv = [r.getTarget(i) for i in range(r.getNTargets())] rv = [hash(x) for x in rv if x is not None] self._labelTargets[hash(obj)] = rv return rv def isLinkAncestorOfImageInContents(self, link, contents): if not self.isLink(link): return False for obj, start, end, string in contents: if obj.getRole() != pyatspi.ROLE_IMAGE: continue if pyatspi.findAncestor(obj, lambda x: x == link): return True return False def isInferredLabelForContents(self, content, contents): obj, start, end, string = content objs = list(filter(self.shouldInferLabelFor, [x[0] for x in contents])) if not objs: return None for o in objs: label, sources = self.inferLabelFor(o) if obj in sources and label.strip() == string.strip(): return o return None def isLabellingContents(self, obj, contents=[]): if self.isFocusModeWidget(obj): return False targets = self.labelTargets(obj) if not contents: return bool(targets) for acc, start, end, string in contents: if hash(acc) in targets: return True if not self.isTextBlockElement(obj): return False if not self.isLabelDescendant(obj): return False for acc, start, end, string in contents: if not self.isLabelDescendant(acc) or self.isTextBlockElement(acc): continue ancestor = self.commonAncestor(acc, obj) if ancestor and ancestor.getRole() == pyatspi.ROLE_LABEL: return True return False def isAnchor(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isAnchor.get(hash(obj)) if rv is not None: return rv rv = False if obj.getRole() == pyatspi.ROLE_LINK \ and not obj.getState().contains(pyatspi.STATE_FOCUSABLE) \ and not 'jump' in self._getActionNames(obj) \ and not self._getXMLRoles(obj): rv = True self._isAnchor[hash(obj)] = rv return rv def isEmptyAnchor(self, obj): if not self.isAnchor(obj): return False return self.queryNonEmptyText(obj) is None def isBrowserUIAlert(self, obj): if not (obj and obj.getRole() == pyatspi.ROLE_ALERT): return False if self.inDocumentContent(obj): return False return True def isTopLevelBrowserUIAlert(self, obj): if not self.isBrowserUIAlert(obj): return False parent = obj.parent while parent and self.isLayoutOnly(parent): parent = parent.parent return parent.getRole() == pyatspi.ROLE_FRAME def _getActionNames(self, obj): try: action = obj.queryAction() names = [action.getName(i).lower() for i in range(action.nActions)] except NotImplementedError: return [] except: msg = "WEB: Exception getting actions for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return [] return list(filter(lambda x: x, names)) def isClickableElement(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isClickableElement.get(hash(obj)) if rv is not None: return rv rv = False if not obj.getState().contains(pyatspi.STATE_FOCUSABLE) \ and not self.isFocusModeWidget(obj): names = self._getActionNames(obj) rv = "click" in names if rv and not obj.name and "Text" in pyatspi.listInterfaces(obj): string = obj.queryText().getText(0, -1) if not string.strip(): rv = obj.getRole() not in [pyatspi.ROLE_STATIC, pyatspi.ROLE_LINK] self._isClickableElement[hash(obj)] = rv return rv def isCodeDescendant(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isCodeDescendant(obj) rv = self._isCodeDescendant.get(hash(obj)) if rv is not None: return rv rv = pyatspi.findAncestor(obj, self.isCode) is not None self._isCodeDescendant[hash(obj)] = rv return rv def isCode(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isCode(obj) return self._getTag(obj) == "code" or "code" in self._getXMLRoles(obj) def getComboBoxValue(self, obj): attrs = self.objectAttributes(obj, False) return attrs.get("valuetext", super().getComboBoxValue(obj)) def isEditableComboBox(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isEditableComboBox(obj) rv = self._isEditableComboBox.get(hash(obj)) if rv is not None: return rv try: role = obj.getRole() state = obj.getState() except: msg = "ERROR: Exception getting role and state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False rv = False if role == pyatspi.ROLE_COMBO_BOX: rv = state.contains(pyatspi.STATE_EDITABLE) self._isEditableComboBox[hash(obj)] = rv return rv def isDPub(self, obj): if not (obj and self.inDocumentContent(obj)): return False roles = self._getXMLRoles(obj) rv = bool(list(filter(lambda x: x.startswith("doc-"), roles))) return rv def isDPubAbstract(self, obj): return 'doc-abstract' in self._getXMLRoles(obj) def isDPubAcknowledgments(self, obj): return 'doc-acknowledgments' in self._getXMLRoles(obj) def isDPubAfterword(self, obj): return 'doc-afterword' in self._getXMLRoles(obj) def isDPubAppendix(self, obj): return 'doc-appendix' in self._getXMLRoles(obj) def isDPubBacklink(self, obj): return 'doc-backlink' in self._getXMLRoles(obj) def isDPubBiblioref(self, obj): return 'doc-biblioref' in self._getXMLRoles(obj) def isDPubBibliography(self, obj): return 'doc-bibliography' in self._getXMLRoles(obj) def isDPubChapter(self, obj): return 'doc-chapter' in self._getXMLRoles(obj) def isDPubColophon(self, obj): return 'doc-colophon' in self._getXMLRoles(obj) def isDPubConclusion(self, obj): return 'doc-conclusion' in self._getXMLRoles(obj) def isDPubCover(self, obj): return 'doc-cover' in self._getXMLRoles(obj) def isDPubCredit(self, obj): return 'doc-credit' in self._getXMLRoles(obj) def isDPubCredits(self, obj): return 'doc-credits' in self._getXMLRoles(obj) def isDPubDedication(self, obj): return 'doc-dedication' in self._getXMLRoles(obj) def isDPubEndnote(self, obj): return 'doc-endnote' in self._getXMLRoles(obj) def isDPubEndnotes(self, obj): return 'doc-endnotes' in self._getXMLRoles(obj) def isDPubEpigraph(self, obj): return 'doc-epigraph' in self._getXMLRoles(obj) def isDPubEpilogue(self, obj): return 'doc-epilogue' in self._getXMLRoles(obj) def isDPubErrata(self, obj): return 'doc-errata' in self._getXMLRoles(obj) def isDPubExample(self, obj): return 'doc-example' in self._getXMLRoles(obj) def isDPubFootnote(self, obj): return 'doc-footnote' in self._getXMLRoles(obj) def isDPubForeword(self, obj): return 'doc-foreword' in self._getXMLRoles(obj) def isDPubGlossary(self, obj): return 'doc-glossary' in self._getXMLRoles(obj) def isDPubGlossref(self, obj): return 'doc-glossref' in self._getXMLRoles(obj) def isDPubIndex(self, obj): return 'doc-index' in self._getXMLRoles(obj) def isDPubIntroduction(self, obj): return 'doc-introduction' in self._getXMLRoles(obj) def isDPubNoteref(self, obj): return 'doc-noteref' in self._getXMLRoles(obj) def isDPubPagelist(self, obj): return 'doc-pagelist' in self._getXMLRoles(obj) def isDPubPagebreak(self, obj): return 'doc-pagebreak' in self._getXMLRoles(obj) def isDPubPart(self, obj): return 'doc-part' in self._getXMLRoles(obj) def isDPubPreface(self, obj): return 'doc-preface' in self._getXMLRoles(obj) def isDPubPrologue(self, obj): return 'doc-prologue' in self._getXMLRoles(obj) def isDPubPullquote(self, obj): return 'doc-pullquote' in self._getXMLRoles(obj) def isDPubQna(self, obj): return 'doc-qna' in self._getXMLRoles(obj) def isDPubSubtitle(self, obj): return 'doc-subtitle' in self._getXMLRoles(obj) def isDPubToc(self, obj): return 'doc-toc' in self._getXMLRoles(obj) def isErrorMessage(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isErrorMessage(obj) rv = self._isErrorMessage.get(hash(obj)) if rv is not None: return rv # Remove this when we bump dependencies to 2.26 try: relationType = pyatspi.RELATION_ERROR_FOR except: rv = False else: isMessage = lambda r: r.getRelationType() == relationType rv = bool(list(filter(isMessage, obj.getRelationSet()))) self._isErrorMessage[hash(obj)] = rv return rv def isFakePlaceholderForEntry(self, obj): if not (obj and self.inDocumentContent(obj) and obj.parent): return False if not (obj.parent.getRole() == pyatspi.ROLE_ENTRY and obj.parent.name): return False def _isMatch(x): try: role = x.getRole() string = x.queryText().getText(0, -1).strip() except: return False return role in [pyatspi.ROLE_SECTION, pyatspi.ROLE_STATIC] and obj.parent.name == string if _isMatch(obj): return True return pyatspi.findDescendant(obj, _isMatch) is not None def isInlineListItem(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isInlineListItem.get(hash(obj)) if rv is not None: return rv if obj.getRole() != pyatspi.ROLE_LIST_ITEM: rv = False else: displayStyle = self._getDisplayStyle(obj) rv = displayStyle and "inline" in displayStyle self._isInlineListItem[hash(obj)] = rv return rv def isBlockListDescendant(self, obj): if not self.isListDescendant(obj): return False return not self.isInlineListDescendant(obj) def isListDescendant(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isListDescendant.get(hash(obj)) if rv is not None: return rv isList = lambda x: x and x.getRole() == pyatspi.ROLE_LIST ancestor = pyatspi.findAncestor(obj, isList) rv = ancestor is not None self._isListDescendant[hash(obj)] = rv return rv def isInlineListDescendant(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isInlineListDescendant.get(hash(obj)) if rv is not None: return rv if self.isInlineListItem(obj): rv = True else: ancestor = pyatspi.findAncestor(obj, self.isInlineListItem) rv = ancestor is not None self._isInlineListDescendant[hash(obj)] = rv return rv def listForInlineListDescendant(self, obj): if not self.isInlineListDescendant(obj): return None isList = lambda x: x and x.getRole() == pyatspi.ROLE_LIST return pyatspi.findAncestor(obj, isList) def isFeed(self, obj): return 'feed' in self._getXMLRoles(obj) def isFigure(self, obj): return 'figure' in self._getXMLRoles(obj) def isLandmark(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isLandmark.get(hash(obj)) if rv is not None: return rv if obj.getRole() == pyatspi.ROLE_LANDMARK: rv = True elif self.isLandmarkRegion(obj): rv = bool(obj.name) else: roles = self._getXMLRoles(obj) rv = bool(list(filter(lambda x: x in self.getLandmarkTypes(), roles))) self._isLandmark[hash(obj)] = rv return rv def isLandmarkWithoutType(self, obj): roles = self._getXMLRoles(obj) return not roles def isLandmarkBanner(self, obj): return 'banner' in self._getXMLRoles(obj) def isLandmarkComplementary(self, obj): return 'complementary' in self._getXMLRoles(obj) def isLandmarkContentInfo(self, obj): return 'contentinfo' in self._getXMLRoles(obj) def isLandmarkForm(self, obj): return 'form' in self._getXMLRoles(obj) def isLandmarkMain(self, obj): return 'main' in self._getXMLRoles(obj) def isLandmarkNavigation(self, obj): return 'navigation' in self._getXMLRoles(obj) def isLandmarkRegion(self, obj): return 'region' in self._getXMLRoles(obj) def isLandmarkSearch(self, obj): return 'search' in self._getXMLRoles(obj) def isLiveRegion(self, obj): if not (obj and self.inDocumentContent(obj)): return False attrs = self.objectAttributes(obj) return 'container-live' in attrs def isLink(self, obj): if not obj: return False rv = self._isLink.get(hash(obj)) if rv is not None: return rv role = obj.getRole() if role == pyatspi.ROLE_LINK and not self.isAnchor(obj): rv = True elif role == pyatspi.ROLE_STATIC \ and obj.parent.getRole() == pyatspi.ROLE_LINK \ and obj.name and obj.name == obj.parent.name: rv = True else: rv = False self._isLink[hash(obj)] = rv return rv def isNonNavigablePopup(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isNonNavigablePopup.get(hash(obj)) if rv is not None: return rv rv = obj.getRole() == pyatspi.ROLE_TOOL_TIP \ and not obj.getState().contains(pyatspi.STATE_FOCUSABLE) self._isNonNavigablePopup[hash(obj)] = rv return rv def hasUselessCanvasDescendant(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._hasUselessCanvasDescendant.get(hash(obj)) if rv is not None: return rv isCanvas = lambda x: x and x.getRole() == pyatspi.ROLE_CANVAS canvases = self.findAllDescendants(obj, isCanvas) rv = len(list(filter(self.isUselessImage, canvases))) > 0 self._hasUselessCanvasDescendant[hash(obj)] = rv return rv def isSwitch(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isSwitch(obj) return 'switch' in self._getXMLRoles(obj) def isNonNavigableEmbeddedDocument(self, obj): rv = self._isNonNavigableEmbeddedDocument.get(hash(obj)) if rv is not None: return rv rv = False if self.isDocument(obj) and self.getDocumentForObject(obj): try: name = obj.name except: rv = True else: rv = "doubleclick" in name self._isNonNavigableEmbeddedDocument[hash(obj)] = rv return rv def isRedundantSVG(self, obj): if self._getTag(obj) != 'svg' or obj.parent.childCount == 1: return False rv = self._isRedundantSVG.get(hash(obj)) if rv is not None: return rv rv = False children = [x for x in obj.parent if self._getTag(x) == 'svg'] if len(children) == obj.parent.childCount: sortedChildren = sorted(children, key=functools.cmp_to_key(self.sizeComparison)) if obj != sortedChildren[-1]: objExtents = self.getExtents(obj, 0, -1) largestExtents = self.getExtents(sortedChildren[-1], 0, -1) rv = self.intersection(objExtents, largestExtents) == tuple(objExtents) self._isRedundantSVG[hash(obj)] = rv return rv def isUselessImage(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isUselessImage.get(hash(obj)) if rv is not None: return rv rv = True if obj.getRole() not in [pyatspi.ROLE_IMAGE, pyatspi.ROLE_CANVAS] \ and self._getTag(obj) != 'svg': rv = False if rv and (obj.name or obj.description): rv = False if rv and (self.isClickableElement(obj) or self.hasLongDesc(obj)): rv = False if rv and obj.getState().contains(pyatspi.STATE_FOCUSABLE): rv = False if rv and obj.parent.getRole() == pyatspi.ROLE_LINK: uri = self.uri(obj.parent) if uri and not uri.startswith('javascript'): rv = False if rv and 'Image' in pyatspi.listInterfaces(obj): image = obj.queryImage() if image.imageDescription: rv = False elif not self.hasExplicitName(obj) and not self.isRedundantSVG(obj): width, height = image.getImageSize() if width > 25 and height > 25: rv = False if rv and 'Text' in pyatspi.listInterfaces(obj): rv = self.queryNonEmptyText(obj) is None if rv and obj.childCount: for i in range(min(obj.childCount, 50)): if not self.isUselessImage(obj[i]): rv = False break self._isUselessImage[hash(obj)] = rv return rv def hasValidName(self, obj): if not obj.name: return False if len(obj.name.split()) > 1: return True parsed = urllib.parse.parse_qs(obj.name) if len(parsed) > 2: msg = "WEB: name of %s is suspected query string" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if len(obj.name) == 1 and ord(obj.name) in range(0xe000, 0xf8ff): msg = "WEB: name of %s is in unicode private use area" % obj debug.println(debug.LEVEL_INFO, msg, True) return False return True def isUselessEmptyElement(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isUselessEmptyElement.get(hash(obj)) if rv is not None: return rv try: role = obj.getRole() state = obj.getState() interfaces = pyatspi.listInterfaces(obj) except: msg = "WEB: Exception getting role, state, and interfaces for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False roles = [pyatspi.ROLE_PARAGRAPH, pyatspi.ROLE_SECTION, pyatspi.ROLE_STATIC, pyatspi.ROLE_TABLE_ROW] if role not in roles: rv = False elif state.contains(pyatspi.STATE_FOCUSABLE) or state.contains(pyatspi.STATE_FOCUSED): rv = False elif state.contains(pyatspi.STATE_EDITABLE): rv = False elif self.hasValidName(obj) or obj.description or obj.childCount: rv = False elif "Text" in interfaces and obj.queryText().characterCount \ and obj.queryText().getText(0, -1) != obj.name: rv = False elif "Action" in interfaces and self._getActionNames(obj): rv = False else: rv = True self._isUselessEmptyElement[hash(obj)] = rv return rv def isParentOfNullChild(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isParentOfNullChild.get(hash(obj)) if rv is not None: return rv rv = False try: childCount = obj.childCount except: msg = "WEB: Exception getting childCount for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) childCount = 0 if childCount and obj[0] is None: msg = "ERROR: %s reports %i children, but obj[0] is None" % (obj, childCount) debug.println(debug.LEVEL_INFO, msg, True) rv = True self._isParentOfNullChild[hash(obj)] = rv return rv def hasExplicitName(self, obj): if not (obj and self.inDocumentContent(obj)): return False attrs = self.objectAttributes(obj) return attrs.get('explicit-name') == 'true' def hasLongDesc(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._hasLongDesc.get(hash(obj)) if rv is not None: return rv names = self._getActionNames(obj) rv = "showlongdesc" in names self._hasLongDesc[hash(obj)] = rv return rv def hasDetails(self, obj): if not (obj and self.inDocumentContent(obj)): return super().hasDetails(obj) rv = self._hasDetails.get(hash(obj)) if rv is not None: return rv try: relations = obj.getRelationSet() except: msg = 'ERROR: Exception getting relationset for %s' % obj debug.println(debug.LEVEL_INFO, msg, True) return False rv = False relation = filter(lambda x: x.getRelationType() == pyatspi.RELATION_DETAILS, relations) for r in relation: if r.getNTargets() > 0: rv = True break self._hasDetails[hash(obj)] = rv return rv def detailsIn(self, obj): if not self.hasDetails(obj): return [] try: relations = obj.getRelationSet() except: msg = 'ERROR: Exception getting relationset for %s' % obj debug.println(debug.LEVEL_INFO, msg, True) return [] rv = [] relation = filter(lambda x: x.getRelationType() == pyatspi.RELATION_DETAILS, relations) for r in relation: for i in range(r.getNTargets()): rv.append(r.getTarget(i)) return rv def isDetails(self, obj): if not (obj and self.inDocumentContent(obj)): return super().isDetails(obj) rv = self._isDetails.get(hash(obj)) if rv is not None: return rv try: relations = obj.getRelationSet() except: msg = 'ERROR: Exception getting relationset for %s' % obj debug.println(debug.LEVEL_INFO, msg, True) return False rv = False relation = filter(lambda x: x.getRelationType() == pyatspi.RELATION_DETAILS_FOR, relations) for r in relation: if r.getNTargets() > 0: rv = True break self._isDetails[hash(obj)] = rv return rv def detailsFor(self, obj): if not self.isDetails(obj): return [] try: relations = obj.getRelationSet() except: msg = 'ERROR: Exception getting relationset for %s' % obj debug.println(debug.LEVEL_INFO, msg, True) return [] rv = [] relation = filter(lambda x: x.getRelationType() == pyatspi.RELATION_DETAILS_FOR, relations) for r in relation: for i in range(r.getNTargets()): rv.append(r.getTarget(i)) return rv def popupType(self, obj): if not (obj and self.inDocumentContent(obj)): return 'false' attrs = self.objectAttributes(obj) return attrs.get('haspopup', 'false').lower() def inferLabelFor(self, obj): if not self.shouldInferLabelFor(obj): return None, [] rv = self._inferredLabels.get(hash(obj)) if rv is not None: return rv rv = self._script.labelInference.infer(obj, False) self._inferredLabels[hash(obj)] = rv return rv def shouldInferLabelFor(self, obj): if not self.inDocumentContent() or self.isWebAppDescendant(obj): return False rv = self._shouldInferLabelFor.get(hash(obj)) if rv and not self._script._lastCommandWasCaretNav: return not self._script.inSayAll() if rv == False: return rv try: role = obj.getRole() name = obj.name except: msg = "WEB: Exception getting role and name for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = False else: if name: rv = False elif not rv: roles = [pyatspi.ROLE_CHECK_BOX, pyatspi.ROLE_COMBO_BOX, pyatspi.ROLE_ENTRY, pyatspi.ROLE_LIST_BOX, pyatspi.ROLE_PASSWORD_TEXT, pyatspi.ROLE_RADIO_BUTTON] rv = role in roles and not self.displayedLabel(obj) self._shouldInferLabelFor[hash(obj)] = rv # TODO - JD: This is private. if self._script._lastCommandWasCaretNav \ and role not in [pyatspi.ROLE_RADIO_BUTTON, pyatspi.ROLE_CHECK_BOX]: return False return rv def displayedLabel(self, obj): if not (obj and self.inDocumentContent(obj)): return super().displayedLabel(obj) rv = self._displayedLabelText.get(hash(obj)) if rv is not None: return rv labels = self.labelsForObject(obj) strings = [l.name or self.displayedText(l) for l in labels if l is not None] rv = " ".join(strings) self._displayedLabelText[hash(obj)] = rv return rv def labelsForObject(self, obj): if not obj: return [] rv = self._actualLabels.get(hash(obj)) if rv is not None: return rv rv = super().labelsForObject(obj) if not self.inDocumentContent(obj): return rv rv = list(filter(lambda x: x and x.getRole() == pyatspi.ROLE_LABEL, rv)) self._actualLabels[hash(obj)] = rv return rv def isSpinnerEntry(self, obj): if not self.inDocumentContent(obj): return False if not obj.getState().contains(pyatspi.STATE_EDITABLE): return False if pyatspi.ROLE_SPIN_BUTTON in [obj.getRole(), obj.parent.getRole()]: return True return False def eventIsSpinnerNoise(self, event): if not self.isSpinnerEntry(event.source): return False if event.type.startswith("object:text-changed") \ or event.type.startswith("object:text-selection-changed"): lastKey, mods = self.lastKeyAndModifiers() if lastKey in ["Down", "Up"]: return True return False def treatEventAsSpinnerValueChange(self, event): if event.type.startswith("object:text-caret-moved") and self.isSpinnerEntry(event.source): lastKey, mods = self.lastKeyAndModifiers() if lastKey in ["Down", "Up"]: obj, offset = self.getCaretContext() return event.source == obj return False def eventIsBrowserUINoise(self, event): if self.inDocumentContent(event.source): return False try: role = event.source.getRole() except: msg = "WEB: Exception getting role for %s" % event.source debug.println(debug.LEVEL_INFO, msg, True) return False eType = event.type if eType.startswith("object:text-") or eType.endswith("accessible-name"): return role in [pyatspi.ROLE_STATUS_BAR, pyatspi.ROLE_LABEL] if eType.startswith("object:children-changed"): return True return False def eventIsAutocompleteNoise(self, event): if not self.inDocumentContent(event.source): return False isListBoxItem = lambda x: x and x.parent and x.parent.getRole() == pyatspi.ROLE_LIST_BOX isMenuItem = lambda x: x and x.parent and x.parent.getRole() == pyatspi.ROLE_MENU isComboBoxItem = lambda x: x and x.parent and x.parent.getRole() == pyatspi.ROLE_COMBO_BOX if event.source.getState().contains(pyatspi.STATE_EDITABLE) \ and event.type.startswith("object:text-"): obj, offset = self.getCaretContext() if isListBoxItem(obj) or isMenuItem(obj): return True if obj == event.source and isComboBoxItem(obj): lastKey, mods = self.lastKeyAndModifiers() if lastKey in ["Down", "Up"]: return True return False def eventIsBrowserUIAutocompleteNoise(self, event): if self.inDocumentContent(event.source): return False selection = ["object:selection-changed", "object:state-changed:selected"] if not event.type in selection: return False try: focusRole = orca_state.locusOfFocus.getRole() focusState = orca_state.locusOfFocus.getState() except: msg = "WEB: Exception getting role and state for %s" % orca_state.locusOfFocus debug.println(debug.LEVEL_INFO, msg, True) return False try: role = event.source.getRole() except: msg = "WEB: Exception getting role for %s" % event.source debug.println(debug.LEVEL_INFO, msg, True) return False if role in [pyatspi.ROLE_MENU, pyatspi.ROLE_MENU_ITEM] \ and focusRole == pyatspi.ROLE_ENTRY \ and focusState.contains(pyatspi.STATE_FOCUSED): lastKey, mods = self.lastKeyAndModifiers() if lastKey not in ["Down", "Up"]: return True return False def eventIsBrowserUIPageSwitch(self, event): selection = ["object:selection-changed", "object:state-changed:selected"] if not event.type in selection: return False roles = [pyatspi.ROLE_PAGE_TAB, pyatspi.ROLE_PAGE_TAB_LIST] if not event.source.getRole() in roles: return False if self.inDocumentContent(event.source): return False if not self.inDocumentContent(orca_state.locusOfFocus): return False return True def eventIsFromLocusOfFocusDocument(self, event): source = self.getDocumentForObject(event.source) focus = self.getDocumentForObject(orca_state.locusOfFocus) if not (source and focus): return False if source == focus: return True if self.isZombie(focus) and not self.isZombie(source): if self.activeDocument() == source: msg = "WEB: Treating active doc as locusOfFocus doc" debug.println(debug.LEVEL_INFO, msg, True) return True return False def textEventIsDueToDeletion(self, event): if not self.inDocumentContent(event.source) \ or not event.source.getState().contains(pyatspi.STATE_EDITABLE): return False if self.isDeleteCommandTextDeletionEvent(event) \ or self.isBackSpaceCommandTextDeletionEvent(event): return True return False def textEventIsDueToInsertion(self, event): if not event.type.startswith("object:text-"): return False if not self.inDocumentContent(event.source) \ or not event.source.getState().contains(pyatspi.STATE_EDITABLE) \ or not event.source == orca_state.locusOfFocus: return False if isinstance(orca_state.lastInputEvent, input_event.KeyboardEvent): inputEvent = orca_state.lastNonModifierKeyEvent return inputEvent and inputEvent.isPrintableKey() and not inputEvent.modifiers return False def textEventIsForNonNavigableTextObject(self, event): if not event.type.startswith("object:text-"): return False return self._treatObjectAsWhole(event.source) def eventIsEOCAdded(self, event): if not self.inDocumentContent(event.source): return False if event.type.startswith("object:text-changed:insert") \ and self.EMBEDDED_OBJECT_CHARACTER in event.any_data: return not re.match("[^\s\ufffc]", event.any_data) return False def caretMovedOutsideActiveGrid(self, event, oldFocus=None): if not (event and event.type.startswith("object:text-caret-moved")): return False oldFocus = oldFocus or orca_state.locusOfFocus if not self.isGridDescendant(oldFocus): return False return not self.isGridDescendant(event.source) def caretMovedToSamePageFragment(self, event, oldFocus=None): if not (event and event.type.startswith("object:text-caret-moved")): return False if event.source.getState().contains(pyatspi.STATE_EDITABLE): return False docURI = self.documentFrameURI() fragment = urllib.parse.urlparse(docURI).fragment if not fragment: return False sourceID = self._getID(event.source) if sourceID and fragment == sourceID: return True oldFocus = oldFocus or orca_state.locusOfFocus if self.isLink(oldFocus): link = oldFocus else: link = pyatspi.findAncestor(oldFocus, self.isLink) return link and self.uri(link) == docURI def isChildOfCurrentFragment(self, obj): parseResult = urllib.parse.urlparse(self.documentFrameURI()) if not parseResult.fragment: return False isSameFragment = lambda x: self._getID(x) == parseResult.fragment return pyatspi.findAncestor(obj, isSameFragment) is not None def documentFragment(self, documentFrame): parseResult = urllib.parse.urlparse(self.documentFrameURI(documentFrame)) return parseResult.fragment def isContentEditableWithEmbeddedObjects(self, obj): if not (obj and self.inDocumentContent(obj)): return False rv = self._isContentEditableWithEmbeddedObjects.get(hash(obj)) if rv is not None: return rv rv = False try: state = obj.getState() role = obj.getRole() except: msg = "WEB: Exception getting state and role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return rv hasTextBlockRole = lambda x: x and x.getRole() in self._textBlockElementRoles() if role == pyatspi.ROLE_ENTRY and state.contains(pyatspi.STATE_MULTI_LINE): rv = pyatspi.findDescendant(obj, hasTextBlockRole) elif state.contains(pyatspi.STATE_EDITABLE): rv = hasTextBlockRole(obj) or self.isLink(obj) elif not self.isDocument(obj): document = self.getDocumentForObject(obj) rv = self.isContentEditableWithEmbeddedObjects(document) self._isContentEditableWithEmbeddedObjects[hash(obj)] = rv return rv def characterOffsetInParent(self, obj): start, end, length = self._rangeInParentWithLength(obj) return start def _rangeInParentWithLength(self, obj): if not obj: return -1, -1, 0 text = self.queryNonEmptyText(obj.parent) if not text: return -1, -1, 0 start, end = self.getHyperlinkRange(obj) return start, end, text.characterCount def getError(self, obj): if not (obj and self.inDocumentContent(obj)): return super().getError(obj) try: state = obj.getState() except: msg = "ERROR: Exception getting state for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if not state.contains(pyatspi.STATE_INVALID_ENTRY): return False try: self._currentTextAttrs.pop(hash(obj)) except: pass attrs, start, end = self.textAttributes(obj, 0, True) error = attrs.get("invalid") if error == "false": return False if error not in ["spelling", "grammar"]: return True return error def _getErrorMessageContainer(self, obj): if not (obj and self.inDocumentContent(obj)): return None if not self.getError(obj): return None # Remove this when we bump dependencies to 2.26 try: relationType = pyatspi.RELATION_ERROR_MESSAGE except: return None isMessage = lambda r: r.getRelationType() == relationType relations = list(filter(isMessage, obj.getRelationSet())) if not relations: return None return relations[0].getTarget(0) def getErrorMessage(self, obj): return self.expandEOCs(self._getErrorMessageContainer(obj)) def isErrorForContents(self, obj, contents=[]): if not self.isErrorMessage(obj): return False for acc, start, end, string in contents: if self._getErrorMessageContainer(acc) == obj: return True return False def hasNoSize(self, obj): if not (obj and self.inDocumentContent(obj)): return super().hasNoSize(obj) rv = self._hasNoSize.get(hash(obj)) if rv is not None: return rv rv = super().hasNoSize(obj) self._hasNoSize[hash(obj)] = rv return rv def _canHaveCaretContext(self, obj): if not obj: return False if self.isDead(obj): msg = "WEB: Dead object cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isZombie(obj): msg = "WEB: Zombie object cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isHidden(obj): msg = "WEB: Hidden object cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isOffScreenLabel(obj): msg = "WEB: Off-screen label cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isNonNavigablePopup(obj): msg = "WEB: Non-navigable popup cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isUselessImage(obj): msg = "WEB: Useless image cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isUselessEmptyElement(obj): msg = "WEB: Useless empty element cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isEmptyAnchor(obj): msg = "WEB: Empty anchor cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.hasNoSize(obj): msg = "WEB: Allowing sizeless object to have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return True if self.isParentOfNullChild(obj): msg = "WEB: Parent of null child cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isPseudoElement(obj): msg = "WEB: Pseudo element cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isStaticTextLeaf(obj): msg = "WEB: Static text leaf cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False if self.isFakePlaceholderForEntry(obj): msg = "WEB: Fake placeholder for entry cannot have caret context %s" % obj debug.println(debug.LEVEL_INFO, msg, True) return False return True def isPseudoElement(self, obj): return False def searchForCaretContext(self, obj): contextObj, contextOffset = None, -1 while obj: try: offset = obj.queryText().caretOffset except: obj = None else: contextObj, contextOffset = obj, offset child = self.getChildAtOffset(obj, offset) if child: obj = child else: break if contextObj: return self.findNextCaretInOrder(contextObj, max(-1, contextOffset - 1)) return None, -1 def _getCaretContextViaLocusOfFocus(self): obj = orca_state.locusOfFocus if not self.inDocumentContent(obj): return None, -1 try: offset = obj.queryText().caretOffset except NotImplementedError: offset = 0 except: offset = -1 return obj, offset def getCaretContext(self, documentFrame=None, getZombieReplicant=False): if not documentFrame or self.isZombie(documentFrame): documentFrame = self.documentFrame() if not documentFrame: return self._getCaretContextViaLocusOfFocus() context = self._caretContexts.get(hash(documentFrame.parent)) if not context or documentFrame != self.getTopLevelDocumentForObject(context[0]): obj, offset = self.searchForCaretContext(documentFrame) elif not getZombieReplicant: return context elif self.isZombie(context[0]): obj, offset = self.findContextReplicant() if obj: caretObj, caretOffset = self.searchForCaretContext(obj.parent) if caretObj and not self.isZombie(caretObj): obj, offset = caretObj, caretOffset else: obj, offset = context self.setCaretContext(obj, offset, documentFrame) return obj, offset def getCaretContextPathRoleAndName(self, documentFrame=None): documentFrame = documentFrame or self.documentFrame() if not documentFrame: return [-1], None, None rv = self._contextPathsRolesAndNames.get(hash(documentFrame.parent)) if not rv: return [-1], None, None return rv def getObjectFromPath(self, path): start = self._script.app rv = None for p in path: if p == -1: continue try: start = start[p] except: break else: rv = start return rv def clearCaretContext(self, documentFrame=None): self.clearContentCache() documentFrame = documentFrame or self.documentFrame() if not documentFrame: return parent = documentFrame.parent self._caretContexts.pop(hash(parent), None) self._priorContexts.pop(hash(parent), None) def handleEventFromContextReplicant(self, event, replicant): if self.isDead(replicant): return False if not self.isDead(orca_state.locusOfFocus): return False path, role, name = self.getCaretContextPathRoleAndName() if path != pyatspi.getPath(replicant): return False if role != replicant.getRole(): return False notify = replicant.name != name documentFrame = self.documentFrame() obj, offset = self._caretContexts.get(hash(documentFrame.parent)) orca.setLocusOfFocus(event, replicant, notify) self.setCaretContext(replicant, offset, documentFrame) return True def findContextReplicant(self, documentFrame=None, matchRole=True, matchName=True): path, oldRole, oldName = self.getCaretContextPathRoleAndName(documentFrame) obj = self.getObjectFromPath(path) if obj and matchRole: if obj.getRole() != oldRole: obj = None if obj and matchName: if obj.name != oldName: obj = None if not obj: return None, -1 obj, offset = self.findFirstCaretContext(obj, 0) msg = "WEB: Context replicant is %s, %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return obj, offset def getPriorContext(self, documentFrame=None): if not documentFrame or self.isZombie(documentFrame): documentFrame = self.documentFrame() if documentFrame: context = self._priorContexts.get(hash(documentFrame.parent)) if context: return context return None, -1 def _getPath(self, obj): rv = self._paths.get(hash(obj)) if rv is not None: return rv try: rv = pyatspi.getPath(obj) except: msg = "WEB: Exception getting path for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = [-1] self._paths[hash(obj)] = rv return rv def setCaretContext(self, obj=None, offset=-1, documentFrame=None): documentFrame = documentFrame or self.documentFrame() if not documentFrame: return parent = documentFrame.parent oldObj, oldOffset = self._caretContexts.get(hash(parent), (obj, offset)) self._priorContexts[hash(parent)] = oldObj, oldOffset self._caretContexts[hash(parent)] = obj, offset path = self._getPath(obj) try: role = obj.getRole() name = obj.name except: msg = "WEB: Exception getting role and name for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) role = None name = None self._contextPathsRolesAndNames[hash(parent)] = path, role, name def findFirstCaretContext(self, obj, offset): try: role = obj.getRole() except: msg = "WEB: Exception getting first caret context for %s %i" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return None, -1 lookInChild = [pyatspi.ROLE_LIST, pyatspi.ROLE_INTERNAL_FRAME, pyatspi.ROLE_TABLE, pyatspi.ROLE_TABLE_ROW] if role in lookInChild and obj.childCount and not self.treatAsDiv(obj, offset): msg = "WEB: First caret context for %s, %i will look in child %s" % (obj, offset, obj[0]) debug.println(debug.LEVEL_INFO, msg, True) return self.findFirstCaretContext(obj[0], 0) text = self.queryNonEmptyText(obj) if not text: if self._advanceCaretInEmptyObject(obj) \ and (self.isTextBlockElement(obj) or self.isEmptyAnchor(obj)): nextObj, nextOffset = self.nextContext(obj, offset) if nextObj: msg = "WEB: First caret context for non-text context %s, %i is next context %s, %i" % \ (obj, offset, nextObj, nextOffset) debug.println(debug.LEVEL_INFO, msg, True) return nextObj, nextOffset if self._canHaveCaretContext(obj): msg = "WEB: First caret context for non-text context %s, %i is %s, %i" % \ (obj, offset, obj, 0) debug.println(debug.LEVEL_INFO, msg, True) return obj, 0 if text and offset >= text.characterCount: if self.isContentEditableWithEmbeddedObjects(obj) and self.lastInputEventWasCharNav(): nextObj, nextOffset = self.nextContext(obj, text.characterCount) if not nextObj: msg = "WEB: No next object found at end of contenteditable %s" % obj debug.println(debug.LEVEL_INFO, msg, True) elif not self.isContentEditableWithEmbeddedObjects(nextObj): msg = "WEB: Next object found at end of contenteditable %s is not editable %s" % (obj, nextObj) debug.println(debug.LEVEL_INFO, msg, True) else: msg = "WEB: First caret context at end of contenteditable %s is next context %s, %i" % \ (obj, nextObj, nextOffset) debug.println(debug.LEVEL_INFO, msg, True) return nextObj, nextOffset msg = "WEB: First caret context at end of %s, %i is %s, %i" % (obj, offset, obj, text.characterCount) debug.println(debug.LEVEL_INFO, msg, True) return obj, text.characterCount offset = max (0, offset) if text: allText = text.getText(0, -1) if allText[offset] != self.EMBEDDED_OBJECT_CHARACTER or role == pyatspi.ROLE_ENTRY: msg = "WEB: First caret context for %s, %i is unchanged" % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return obj, offset child = self.getChildAtOffset(obj, offset) if not child: msg = "WEB: Child at offset is null. Returning %s, %i unchanged." % (obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return obj, offset if self.isListItemMarker(child): msg = "WEB: First caret context for %s, %i is %s, %i (skip list item marker child)" % \ (obj, offset, obj, offset + 1) debug.println(debug.LEVEL_INFO, msg, True) return obj, offset + 1 if not self._canHaveCaretContext(child): nextObj, nextOffset = self.nextContext(obj, offset) msg = "WEB: First caret context for %s, %i is %s, %i (child cannot be context)" % \ (obj, offset, nextObj, nextOffset) debug.println(debug.LEVEL_INFO, msg, True) return nextObj, nextOffset msg = "WEB: Looking in child %s for first caret context for %s, %i" % (child, obj, offset) debug.println(debug.LEVEL_INFO, msg, True) return self.findFirstCaretContext(child, 0) def findNextCaretInOrder(self, obj=None, offset=-1): if not obj: obj, offset = self.getCaretContext() if not obj or not self.inDocumentContent(obj): return None, -1 if self._canHaveCaretContext(obj): text = self.queryNonEmptyText(obj) if text: allText = text.getText(0, -1) for i in range(offset + 1, len(allText)): child = self.getChildAtOffset(obj, i) if child and self._treatObjectAsWhole(child): return child, 0 if self._canHaveCaretContext(child): return self.findNextCaretInOrder(child, -1) if allText[i] not in (self.EMBEDDED_OBJECT_CHARACTER, self.ZERO_WIDTH_NO_BREAK_SPACE): return obj, i elif obj.childCount and not self._treatObjectAsWhole(obj): return self.findNextCaretInOrder(obj[0], -1) elif offset < 0 and not self.isTextBlockElement(obj): return obj, 0 # If we're here, start looking up the the tree, up to the document. documentFrame = self.documentFrame() if self.isSameObject(obj, documentFrame): return None, -1 while obj and obj.parent: if self.isDetachedDocument(obj.parent): obj = self.iframeForDetachedDocument(obj.parent) continue parent = obj.parent if self.isZombie(parent): replicant = self.findReplicant(self.documentFrame(), parent) if replicant and not self.isZombie(replicant): parent = replicant elif parent.parent: obj = parent continue else: break start, end, length = self._rangeInParentWithLength(obj) if start + 1 == end and 0 <= start < end <= length: return self.findNextCaretInOrder(parent, start) index = obj.getIndexInParent() + 1 try: parentChildCount = parent.childCount except: msg = "WEB: Exception getting childCount for %s" % parent debug.println(debug.LEVEL_INFO, msg, True) else: if 0 < index < parentChildCount: return self.findNextCaretInOrder(parent[index], -1) obj = parent return None, -1 def findPreviousCaretInOrder(self, obj=None, offset=-1): if not obj: obj, offset = self.getCaretContext() if not obj or not self.inDocumentContent(obj): return None, -1 if self._canHaveCaretContext(obj): text = self.queryNonEmptyText(obj) if text: allText = text.getText(0, -1) if offset == -1 or offset > len(allText): offset = len(allText) for i in range(offset - 1, -1, -1): child = self.getChildAtOffset(obj, i) if child and self._treatObjectAsWhole(child): return child, 0 if self._canHaveCaretContext(child): return self.findPreviousCaretInOrder(child, -1) if allText[i] not in (self.EMBEDDED_OBJECT_CHARACTER, self.ZERO_WIDTH_NO_BREAK_SPACE): return obj, i elif obj.childCount and not self._treatObjectAsWhole(obj): return self.findPreviousCaretInOrder(obj[obj.childCount - 1], -1) elif offset < 0 and not self.isTextBlockElement(obj): return obj, 0 # If we're here, start looking up the the tree, up to the document. documentFrame = self.documentFrame() if self.isSameObject(obj, documentFrame): return None, -1 while obj and obj.parent: if self.isDetachedDocument(obj.parent): obj = self.iframeForDetachedDocument(obj.parent) continue parent = obj.parent if self.isZombie(parent): replicant = self.findReplicant(self.documentFrame(), parent) if replicant and not self.isZombie(replicant): parent = replicant elif parent.parent: obj = parent continue else: break start, end, length = self._rangeInParentWithLength(obj) if start + 1 == end and 0 <= start < end <= length: return self.findPreviousCaretInOrder(parent, start) index = obj.getIndexInParent() - 1 try: parentChildCount = parent.childCount except: msg = "WEB: Exception getting childCount for %s" % parent debug.println(debug.LEVEL_INFO, msg, True) else: if 0 <= index < parentChildCount: return self.findPreviousCaretInOrder(parent[index], -1) obj = parent return None, -1 def lastQueuedLiveRegion(self): if self._lastQueuedLiveRegionEvent is None: return None if self._lastQueuedLiveRegionEvent.type.startswith("object:text-changed:insert"): return self._lastQueuedLiveRegionEvent.source if self._lastQueuedLiveRegionEvent.type.startswith("object:children-changed:add"): return self._lastQueuedLiveRegionEvent.any_data return None def handleAsLiveRegion(self, event): if not _settingsManager.getSetting('inferLiveRegions'): return False if not self.isLiveRegion(event.source): return False if not _settingsManager.getSetting('presentLiveRegionFromInactiveTab') \ and self.getTopLevelDocumentForObject(event.source) != self.activeDocument(): msg = "WEB: Live region source is not in active tab." debug.println(debug.LEVEL_INFO, msg, True) return False if event.type.startswith("object:text-changed:insert"): isAlert = lambda x: x and x.getRole() == pyatspi.ROLE_ALERT alert = pyatspi.findAncestor(event.source, isAlert) if alert and self.focusedObject(alert) == event.source: msg = "WEB: Focused source will be presented as part of alert" debug.println(debug.LEVEL_INFO, msg, True) return False if self._lastQueuedLiveRegionEvent \ and self._lastQueuedLiveRegionEvent.type == event.type \ and self._lastQueuedLiveRegionEvent.any_data == event.any_data: msg = "WEB: Event is believed to be duplicate message" debug.println(debug.LEVEL_INFO, msg, True) return False if isinstance(event.any_data, pyatspi.Accessible): try: role = event.any_data.getRole() except: msg = "WEB: Exception getting role for %s" % event.any_data debug.println(debug.LEVEL_INFO, msg, True) return False if role in [pyatspi.ROLE_UNKNOWN, pyatspi.ROLE_REDUNDANT_OBJECT] \ and self._getTag(event.any_data) in ["", None, "br"]: msg = "WEB: Child has unknown role and no tag %s" % event.any_data debug.println(debug.LEVEL_INFO, msg, True) return False if self.lastQueuedLiveRegion() == event.any_data \ and self._lastQueuedLiveRegionEvent.type != event.type: msg = "WEB: Event is believed to be redundant live region notification" debug.println(debug.LEVEL_INFO, msg, True) return False self._lastQueuedLiveRegionEvent = event return True def getPageObjectCount(self, obj): result = {'landmarks': 0, 'headings': 0, 'forms': 0, 'tables': 0, 'visitedLinks': 0, 'unvisitedLinks': 0} docframe = self.documentFrame(obj) msg = "WEB: Document frame for %s is %s" % (obj, docframe) debug.println(debug.LEVEL_INFO, msg, True) col = docframe.queryCollection() stateset = pyatspi.StateSet() roles = [pyatspi.ROLE_HEADING, pyatspi.ROLE_LINK, pyatspi.ROLE_TABLE, pyatspi.ROLE_FORM, pyatspi.ROLE_LANDMARK] if not self.supportsLandmarkRole(): roles.append(pyatspi.ROLE_SECTION) rule = col.createMatchRule(stateset.raw(), col.MATCH_NONE, "", col.MATCH_NONE, roles, col.MATCH_ANY, "", col.MATCH_NONE, False) matches = col.getMatches(rule, col.SORT_ORDER_CANONICAL, 0, True) col.freeMatchRule(rule) for obj in matches: role = obj.getRole() if role == pyatspi.ROLE_HEADING: result['headings'] += 1 elif role == pyatspi.ROLE_FORM: result['forms'] += 1 elif role == pyatspi.ROLE_TABLE and not self.isLayoutOnly(obj): result['tables'] += 1 elif role == pyatspi.ROLE_LINK: if self.isLink(obj): if obj.getState().contains(pyatspi.STATE_VISITED): result['visitedLinks'] += 1 else: result['unvisitedLinks'] += 1 elif self.isLandmark(obj): result['landmarks'] += 1 return result def getPageSummary(self, obj, onlyIfFound=True): result = [] counts = self.getPageObjectCount(obj) result.append(messages.landmarkCount(counts.get('landmarks', 0), onlyIfFound)) result.append(messages.headingCount(counts.get('headings', 0), onlyIfFound)) result.append(messages.formCount(counts.get('forms', 0), onlyIfFound)) result.append(messages.tableCount(counts.get('tables', 0), onlyIfFound)) result.append(messages.visitedLinkCount(counts.get('visitedLinks', 0), onlyIfFound)) result.append(messages.unvisitedLinkCount(counts.get('unvisitedLinks', 0), onlyIfFound)) result = list(filter(lambda x: x, result)) if not result: return "" return messages.PAGE_SUMMARY_PREFIX % ", ".join(result) def preferDescriptionOverName(self, obj): if not self.inDocumentContent(obj): return super().preferDescriptionOverName(obj) rv = self._preferDescriptionOverName.get(hash(obj)) if rv is not None: return rv try: role = obj.getRole() name = obj.name description = obj.description except: msg = "WEB: Exception getting name, description, and role for %s" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = False else: if len(obj.name) == 1 and ord(obj.name) in range(0xe000, 0xf8ff): msg = "WEB: name of %s is in unicode private use area" % obj debug.println(debug.LEVEL_INFO, msg, True) rv = True else: roles = [pyatspi.ROLE_PUSH_BUTTON] rv = role in roles and len(name) == 1 and description self._preferDescriptionOverName[hash(obj)] = rv return rv def _getCtrlShiftSelectionsStrings(self): """Hacky and to-be-obsoleted method.""" return [messages.LINE_SELECTED_DOWN, messages.LINE_UNSELECTED_DOWN, messages.LINE_SELECTED_UP, messages.LINE_UNSELECTED_UP] def lastInputEventWasCopy(self): if super().lastInputEventWasCopy(): return True if not self.inDocumentContent(): return False if not self.topLevelObjectIsActiveAndCurrent(): return False if 'Action' in pyatspi.listInterfaces(orca_state.locusOfFocus): msg = "WEB: Treating %s as source of copy" % orca_state.locusOfFocus debug.println(debug.LEVEL_INFO, msg, True) return True return False
#!/usr/bin/env python ####################################################################################### ## Created by David Kirkby, University of California, Irvine <dkirkby@uci.edu> ####################################################################################### """ ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.07 -o lsst_i --pixel-scale 0.200 --width 4096 --height 4096 --exposure-time 6900 --sky-brightness 20.0 --zenith-fwhm 0.67 --zero-point 41.5 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.07 -o des_i --pixel-scale 0.263 --width 3115 --height 3115 --exposure-time 1000 --sky-brightness 20.1 --zenith-fwhm 0.79 --zero-point 12.5 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.07 -o cfht_i --pixel-scale 0.185 --width 4428 --height 4428 --exposure-time 4300 --sky-brightness 20.3 --zenith-fwhm 0.64 --zero-point 10.0 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.10 -o lsst_r --pixel-scale 0.200 --width 4096 --height 4096 --exposure-time 6900 --sky-brightness 21.3 --zenith-fwhm 0.70 --zero-point 55.8 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.10 -o des_r --pixel-scale 0.263 --width 3115 --height 3115 --exposure-time 800 --sky-brightness 21.1 --zenith-fwhm 0.79 --zero-point 16.8 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.10 -o cfht_r --pixel-scale 0.185 --width 4428 --height 4428 --exposure-time 2000 --sky-brightness 20.8 --zenith-fwhm 0.71 --zero-point 13.5 """ import sys import os import math import argparse import logging import galsim import pyfits import numpy twopi = 2*math.pi deg2rad = math.pi/180. deg2arcsec = 3600. deg2arcmin = 60. def createComponent(type,electrons,xc,yc,hlr,q,beta,g1,g2): # create a radial profile of the requested type and size comp = type(flux = electrons, half_light_radius = hlr) # set the intrinsic shape comp.applyShear(q = q, beta = beta*galsim.radians) # apply cosmic shear comp.applyShear(g1 = g1, g2 = g2) # shift to this component's centroid comp.applyShift(dx = xc, dy = yc) return comp """ Returns a (disk,bulge) tuple of source objects using the specified parameters. Note that f_d and f_b are fractions of the total flux and need not sum to one. """ def createSource( total_flux,f_d,f_b, x_d,y_d,hlr_d,q_d,beta_d, x_b,y_b,hlr_b,q_b,beta_b, dx,dy,relsize,dbeta, g1,g2): # Define the disk component, if any if f_d > 0: disk = createComponent(galsim.Exponential, total_flux*f_d,x_d+dx,y_d+dy,hlr_d*relsize,q_d,beta_d+dbeta,g1,g2) else: disk = None # Define the bulge component, if any if f_b > 0: bulge = createComponent(galsim.DeVaucouleurs, total_flux*f_b,x_b+dx,y_b+dy,hlr_b*relsize,q_b,beta_b+dbeta,g1,g2) else: bulge = None return (disk,bulge) """ Renders the convolution of [src,psf,pix] into the specified bounding box. If psf is None, only [src,pix] are convolved. If src is None, an empty stamp is returned (we use this below when either the bulge or disk is absent). """ def renderStamp(src,psf,pix,bbox): stamp = galsim.ImageD(bbox) stamp.setScale(pix.getXWidth()) if src: models = [src,pix] if psf is None else [src,psf,pix] gsp = galsim.GSParams(maximum_fft_size=32768) obj = galsim.Convolve(models,gsparams=gsp) obj.draw(image = stamp) return stamp """ Renders the specified source convolved with a psf (which might be None) and pixel response into a postage stamp with the specified bounding box. """ def createStamp(src,psf,pix,bbox): (disk,bulge) = src diskStamp = renderStamp(disk,psf,pix,bbox) bulgeStamp = renderStamp(bulge,psf,pix,bbox) return diskStamp + bulgeStamp """ Calculate the centroid, size, and shape of the convolution of [src,psf,pix] in the specified bounding box using a high-resolution image whose pixels are smaller by a factor of oversampling (in each direction), and whose stamp is larger by a factor of zoom (in each direction). The centroid and size are returned in arcsecs. The centroid is relative to the center of the input bounding box. """ def getStampMoments(src,psf,pix,bbox,oversampling=5,zoom=1): # Create a high-resolution pixel grid that covers the same area, and # preserves the even/oddness and mean (min+max)/2. of each dimension. (x1,x2,y1,y2) = (bbox.getXMin(),bbox.getXMax(),bbox.getYMin(),bbox.getYMax()) xmid = (x1+x2)/2. dx = oversampling*(x2-x1)/2. x1 = int(math.floor(xmid - zoom*dx)) x2 = int(math.ceil(xmid + zoom*dx)) assert (x1+x2)/2. == xmid ymid = (y1+y2)/2. dy = oversampling*(y2-y1)/2. y1 = int(math.floor(ymid - zoom*dy)) y2 = int(math.ceil(ymid + zoom*dy)) assert (y1+y2)/2. == ymid bigBbox = galsim.BoundsI(x1,x2,y1,y2) scale = pix.getXWidth()/oversampling smallPix = galsim.Pixel(scale) try: # Render a high-resolution stamp of this source (might fail # with an SB error, e.g., if a bigger FFT is required) stamp = createStamp(src,psf,smallPix,bigBbox) # Try to calculate this stamp's adaptive moments shape = stamp.FindAdaptiveMom() sig_minus = shape.moments_sigma*scale # in arcsecs (e1,e2) = (shape.observed_shape.getG1(),shape.observed_shape.getG2()) emagsq = e1*e1 + e2*e2 ratio = (1+emagsq)/(1-emagsq) sig_plus = sig_minus*math.sqrt(ratio) return (sig_minus,sig_plus,e1,e2) except RuntimeError,e: print 'getStampMoments: %s' % (str(e).strip()) return (-1.,-1.,0.,0.) """ Returns (dx,dy) for the bounding box of a surface brightness profile SB(x,y) whose isophotes are ellipses with the shape (q,beta) and which has an underlying normalized radial profile p(r). The inputs are: maxSB = totalFlux*p(0) = maximum surface brightness before shear thresholdSB = threshold surface brightness after shear q = ratio of minor to major axes of ellipse with 0 < q <= 1 beta = angle of ellipse's major axis in radians rFunction = returns R(b) such that p(R) = b*p(0) with 0 < b < 1 The returned (dx,dy) are in arcsecs, and defined such that SB(x,y) < f0 is guaranteed for |x| > dx or |y| > dy. The result only depends on the ratio thresholdSB/maxSB so they must be in the same (abitrary) units. """ def boundingBox(maxSB,thresholdSB,q,beta,rFunction): # Calculate shear affine transform parameters g = (1-q)/(1+q) gp = g*math.cos(2*beta) gx = g*math.sin(2*beta) detM = 1 - gp*gp - gx*gx # Calculate the dimensionless surface brightness ratio at threshold. b = thresholdSB/(maxSB*detM) if b <= 0: raise RuntimeError('boundingBox: invalid input parameters') if b >= 1: # The max surface brightness is below our threshold SB(0,0) <= f0 return (0,0) # Calculate the threshold radius of the radial profile. rcut = rFunction(b) # Shear this circle and return its bounding box dimensions dx = rcut*math.sqrt(((1+gp)*(1+gp)+gx*gx)/detM) # half width in arcsecs dy = rcut*math.sqrt(((1-gp)*(1-gp)+gx*gx)/detM) # half height in arcsecs return (dx,dy) """ Returns (dx,dy) for the bounding box of a Sersic profile with n = 1 or 4. The input flux should be in electrons, hlr in arscecs, beta in radians, f0 in elec/arcsec^2. 0 < q <= 1 is dimensionless. The returned (dx,dy) are in arcsecs. See boundingBox above for details. """ def sersicBounds(n,flux,hlr,q,beta,f0): # Convert the half-light radius to the appropriate scale radius r0 # and calculate the Sersic normalization constant if n == 1: r0 = hlr/1.67835 norm = twopi*r0*r0 elif n == 4: r0 = hlr/3459.49 norm = 20160*twopi*r0*r0 # 20160 = n*Gamma[2*n] else: raise RuntimeError('Sersic index n = %d is not supported.' % n) # Calculate and return the bounding box return boundingBox(flux/norm,f0,q,beta, lambda b: r0*math.pow(-math.log(b),n)) """ Returns (dx,dy) for the bounding box of a Moffat profile. The input flux should be in electrons, fwhm in arcsecs, beta in radians, f0 in elec/arcsec^2. 0 < q <= 1 and moffatBeta > 1 are dimensionless. The returned (dx,dy) are in arcsecs. See boundingBox above for details. """ def moffatBounds(moffatBeta,flux,fwhm,q,beta,f0): # Check that moffatBeta is valid if moffatBeta <= 1: raise RuntimeError('Moffat beta < 1 is not valid.') # Convert the fwhm to the corresponding scale radius r0 = 0.5*fwhm/math.sqrt(math.pow(2,1./moffatBeta)-1) # Calculate the normalization factor norm = 1/p(0) norm = math.pi*r0*r0/(moffatBeta-1) # Calculate and return the bounding box return boundingBox(flux/norm,f0,q,beta, lambda b: r0*math.sqrt(1-math.pow(b,(moffatBeta-1.)/moffatBeta))) """ Returns a mask image of values 0 or 1 depending on whether the corresponding input image pixel value is above or below the specified threshold in electrons. Note that if all pixels are below threshold, then the returned mask will contain only the central pixel with image.array.sum() == 0. """ def createMask(image,threshold,args): # create an empty mask image with the same dimensions as the input image box = image.bounds mask = galsim.ImageS(box) mask.setScale(image.getScale()) borderMax = 0. lastRow = box.ymax - box.ymin lastPixel = box.xmax - box.xmin # initialize our trimmed bounds to just the central pixel # (the numerator should always be even for odd width,height) xmin = (box.getXMin()+box.getXMax()) ymin = (box.getYMin()+box.getYMax()) assert xmin%2 == 0 and ymin%2 == 0 xmin = xmin/2 ymin = ymin/2 xmax = xmin ymax = ymin # loop over image pixels for (rowIndex,row) in enumerate(image.array): y = box.getYMin()+rowIndex for (pixelIndex,pixelValue) in enumerate(row): x = box.getXMin()+pixelIndex if rowIndex == 0 or rowIndex == lastRow or pixelIndex == 0 or pixelIndex == lastPixel: # update the largest pixel value on our 1-pixel wide border borderMax = max(borderMax,pixelValue) if pixelValue >= threshold: mask.array[rowIndex,pixelIndex] = 1 xmin = min(x,xmin) xmax = max(x,xmax) ymin = min(y,ymin) ymax = max(y,ymax) # is the stamp too small to contain the threshold contour? if borderMax > threshold: print '### stamp truncated at %.1f > %.1f electrons' % (borderMax,threshold) # build a new mask using the border max as the threshold return createMask(image,borderMax,args) trimmed = galsim.BoundsI(xmin,xmax,ymin,ymax) mask = mask[trimmed] return mask """ Performs any final processing on stamp, controlled by args, then appends it to stamps. Returns True if the stamp was saved, or otherwise False. """ def saveStamp(stamps,stamp,args): # Clip the stamp so that does not extend beyond the field image. This results # in potentially smaller files with sources that might not be centered. if not args.no_clip: overlap = stamp.bounds & galsim.BoundsI(1,args.width,1,args.height) if overlap.area() == 0: # skip this stamp if it falls completely outside our field (after trimming) return False stamp = stamp[overlap] # Convert normalization from elec/exposure to elec/second stamp = stamp/args.exposure_time # Remember this stamp. stamps.append(stamp) return True """ Performs initializations for the psf we will be using. """ def initializeForPsf(psf,pix,size): # Render a centered psf image bbox = galsim.BoundsI(1,2*size,1,2*size) stamp = galsim.ImageD(bbox) scale = pix.getXWidth() stamp.setScale(scale) obj = galsim.Convolve([psf,pix]) obj.draw(image=stamp) # Build the circularized psf profile profile = numpy.zeros(size,dtype=float) for x in range(2*size): for y in range(2*size): dx = x - size + 0.5 dy = y - size + 0.5 r = math.sqrt(dx*dx + dy*dy) ipix = int(math.floor(r)) if ipix < size: profile[ipix] = max(profile[ipix],stamp.array[x,y]) # Create a function that gives the size of bounding box necessary to contain # psf pixels down to the specified threshold assuming the specified total flux. # The return value is clipped at 2*size for large fluxes. def estimator(flux,threshold): index = 0 while index < size: if flux*profile[index] < threshold: return 2*index+1 index += 1 return 2*size # Calculate the psf size from a high-resolution rendering (psfSizeMinus,psfSizePlus,e1,e2) = getStampMoments((psf,None),None,pix,bbox) assert abs(e1) < 1e-6 and abs(e2) < 1e-6 return (estimator,psfSizeMinus,psfSizePlus) # Returns the combined size and ellipticity for the specified disk and bulge components, # assuming they have the same centroid. def combineEllipticities(hlr_d,q_d,pa_d,hlr_b,q_b,pa_b,f_b): # ensure that single-component models give correct results if f_b == 0: q_b = 1 elif f_b == 1: q_d = 1 # calculate the disk and bulge component ellipticities ed = (1-q_d)/(1+q_d) ed1 = ed*math.cos(2*pa_d) ed2 = ed*math.sin(2*pa_d) eb = (1-q_b)/(1+q_b) eb1 = eb*math.cos(2*pa_b) eb2 = eb*math.sin(2*pa_b) # calculate the corresponding second-moment tensors assuming unit total flux cd = 1.06502 nd = cd*(hlr_d/(1-ed*ed))**2 Qd11 = nd*(1+ed*ed+2*ed1) Qd12 = nd*2*ed2 Qd22 = nd*(1+ed*ed-2*ed1) detQd = Qd11*Qd22 - Qd12*Qd12 cb = 10.8396 nb = cb*(hlr_b/(1-eb*eb))**2 Qb11 = nb*(1+eb*eb+2*eb1) Qb12 = nb*2*eb2 Qb22 = nb*(1+eb*eb-2*eb1) detQb = Qb11*Qb22 - Qb12*Qb12 # add the component second-moment tensors Q11 = (1-f_b)*Qd11 + f_b*Qb11 Q12 = (1-f_b)*Qd12 + f_b*Qb12 Q22 = (1-f_b)*Qd22 + f_b*Qb22 detQ = Q11*Q22 - Q12*Q12 sizeMinus = math.pow(detQ,0.25) sizePlus = math.sqrt(0.5*(Q11+Q22)) #semiMajorAxis = math.sqrt(0.5*(Q11+Q22+math.sqrt((Q11-Q22)**2+4*Q12**2))) # calculate the corresponding combined ellipticity denom = Q11 + Q22 + 2*math.sqrt(detQ) e1 = (Q11 - Q22)/denom e2 = 2*Q12/denom """ # check direct calculation of emag when pa_d == pa_b emag = math.sqrt(e1*e1 + e2*e2) wd = (1-f_b)*cd*hlr_d**2*(1+q_d)**2/(8*q_d**2) if f_b < 1 else 0 wm = f_b*cb*hlr_b**2*(1+q_b)**2/(8*q_b**2) if f_b > 0 else 0 ep = wd*(1+q_d**2) + wm*(1+q_b**2) em = wd*(1-q_d**2) + wm*(1-q_b**2) emag2 = em/(ep+math.sqrt(ep*ep-em*em)) print 'emag:',emag-emag2 """ return (sizeMinus,sizePlus,e1,e2) def signalToNoiseRatio(stamp,pixelNoise): flat = stamp.array.reshape(-1) snr = math.sqrt(numpy.dot(flat,flat)/pixelNoise) return snr # Returns True if the stamps s1 and s2 have overlapping pixels with non-zero flux. def overlapping(s1,s2): # test for overlapping bounding boxes overlapBounds = s1.bounds & s2.bounds if overlapBounds.area() == 0: return False # test for overlapping flux within the overlapping pixels overlapFluxProduct = numpy.sum(s1[overlapBounds].array * s2[overlapBounds].array) return False if overlapFluxProduct == 0 else True # Assigns a group ID to each stamp in stamps based on its overlaps with other stamps. def analyzeOverlaps(stamps): groupID = range(len(stamps)) groupSize = [1]*len(stamps) for (i1,s1) in enumerate(stamps): for (i2,s2) in enumerate(stamps[:i1]): if overlapping(s1,s2): # get the current group IDs of these overlapping stamps gid1 = groupID[i1] gid2 = groupID[i2] if gid1 == gid2: continue # decide which group joins the other gnew = min(gid1,gid2) gold = max(gid1,gid2) # re-assign all stamps in gold to gnew for i in range(i1+1): if groupID[i] == gold: groupID[i] = gnew groupSize[gnew] += 1 groupSize[gold] -= 1 return (groupID,groupSize) # Builds the Fisher matrix from the specified array of npar*(npar+1)/2 Fisher images and # calculates the corresponding shape-measurment error, if possible. def shapeError(npar,fisherImages,fisherDenominator,mask): # calculate the Fisher matrix elements by summing pixels of the specified Fisher matrix images fisherMatrix = numpy.zeros((npar,npar)) index = 0 for i in range(npar): for j in range(i,npar): fisherMatrix[i,j] = numpy.sum(fisherImages[index]/fisherDenominator*mask) if i != j: fisherMatrix[j,i] = fisherMatrix[i,j] index += 1 # try to calculate corresponding shape measurement error, which will fail unless # the Fisher matrix is invertible try: fullCov = numpy.linalg.inv(fisherMatrix) # this is where we assume that the last 2 variations are g1,g2 varEps = 0.5*(fullCov[-2,-2]+fullCov[-1,-1]) # variance might be negative if inverse has large numerical errors sigmaEps = 0 if varEps <= 0 else math.sqrt(varEps) except numpy.linalg.LinAlgError: # assign a shape-measurement error of zero if the Fisher matrix is not invertible. sigmaEps = 0. return sigmaEps # Calculate shape measurment errors with the specified purity cuts. Returns a tuple of the # corresponding errors, in a list, and an integer-valued image that identifies the purity # regions by assigning each pixel the value of the largest index such that # nominal > purity[index]*field (or zero if this criteria is not met for any purity). def shapeErrorsAnalysis(npar,nominal,fisherImages,noiseVariance,field,purities,isolated=True): # find the overlap of this object in the full field overlap = nominal.bounds & field.bounds # get the pixel values for this object and all objects in the overlap subNominal = nominal[overlap].array subField = field[overlap].array # calculate the denominator array for our Fisher matrix elements, including # all objects unless we are pretending that this object is isolated fisherDenominator = (subNominal if isolated else subField) + noiseVariance # initialize our integer regions image regions = galsim.ImageI(nominal.bounds) regionsArray = regions.array errors = [ ] for (i,purity) in enumerate(purities): mask = (subNominal > purity*subField) regionsArray = numpy.maximum(regionsArray,i*mask) sigeps = shapeError(npar,fisherImages,fisherDenominator,mask) errors.append(sigeps) regions.array[:] = regionsArray[:] return (errors,regions) def main(): # Parse command-line args parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action = "store_true", help = "provide more verbose output") parser.add_argument("-i", "--input", default = 'gcat.dat', help = "name of input catalog to read") parser.add_argument("-o","--output", default = 'catout', help = "base name of output files to write") parser.add_argument("-x","--x-center", type = float, default = 0.5, help = "central RA of image (degrees)") parser.add_argument("-y","--y-center", type = float, default = 0.0, help = "central DEC of image (degrees)") parser.add_argument("--width", type = int, default = 512, help = "image width (pixels)") parser.add_argument("--height", type = int, default = 512, help = "image height (pixels)") parser.add_argument("--max-size", type = float, default = 20., help = "flux from any object is truncated beyond this size (arcsecs)") parser.add_argument("--no-margin", action = "store_true", help = "do not simulate the tails of objects just outside the field") parser.add_argument("--pixel-scale", type = float, default = 0.2, help = "pixel scale (arscecs/pixel)") parser.add_argument("--airmass", type = float, default = 1.2, help = "airmass value to use for atmospheric PSF and extinction") parser.add_argument("--extinction", type = float, default = 0.07, help = "atmospheric extinction coefficient") parser.add_argument("--zenith-fwhm", type = float, default = 0.67, help = "atmospheric psf full-width-half-max in arcsecs at zenith") parser.add_argument("--instrumental-fwhm", type = float, default = 0.4, help = "instrumental psf full-width-half-max in arcsecs") parser.add_argument("--psf-beta", type = float, default = 0.0, help = "psf Moffat parameter beta (uses Kolmogorov psf if beta <= 0)") parser.add_argument("--band", choices = ['u','g','r','i','z','y'], default = 'i', help = "LSST imaging band to use for source fluxes") parser.add_argument("--zero-point", type = float, default = 41.5, help = "zero point for converting magnitude to detected signal in elec/sec") parser.add_argument("--sky-brightness", type = float, default = 20.0, help = "sky brightness in mag/sq.arcsec.") parser.add_argument("--sn-cut", type = float, default = 0.5, help = "keep all pixels above this signal-to-noise ratio cut") parser.add_argument("--exposure-time", type = float, default = 6900., help = "full-depth exposure time in seconds") parser.add_argument("--g1", type = float, default = 0., help = "constant shear component g1 to apply") parser.add_argument("--g2", type = float, default = 0., help = "constant shear component g2 to apply") parser.add_argument("--save-field", action = "store_true", help = "save full field image without noise") parser.add_argument("--save-noise", action = "store_true", help = "save full field image with random noise added") parser.add_argument("--stamps", action = "store_true", help = "save postage stamps for each source (normalized to 1 exposure)") parser.add_argument("--no-clip", action = "store_true", help = "do not clip stamps to the image bounds") parser.add_argument("--no-disk", action = "store_true", help = "do not include any galactic disk (Sersic n=1) components") parser.add_argument("--no-bulge", action = "store_true", help = "do not include any galactic bulge (Sersic n=4) components") parser.add_argument("--shape", action = "store_true", help = "run HSM adaptive moments calculation on no-psf stamp") parser.add_argument("--partials", action = "store_true", help = "calculate and save partial derivatives wrt shape parameters (normalized to 1 exposure)") parser.add_argument("--partials-order", type = int, default = 1, help = "order of finite difference equation to use for evaluating partials") parser.add_argument("--only-line", type = int, default = 0, help = "only use the specified line number from the input catalog (when non-zero)") args = parser.parse_args() # Configure the GalSim logger logging.basicConfig(format="%(message)s", level=logging.INFO, stream=sys.stdout) logger = logging.getLogger("galsimcat") logger.info('Using output prefix %r' % args.output) # Define the pixel response pix = galsim.Pixel(args.pixel_scale) # Define the psf to use atmos_fwhm = args.zenith_fwhm*math.pow(args.airmass,0.6) fwhm = math.sqrt(atmos_fwhm**2 + args.instrumental_fwhm**2) logger.info('Using PSF fwhm = %.4f" (%.4f" zenith => %.4f" at X = %.3f, %.4f" instrumental)' % (fwhm,args.zenith_fwhm,atmos_fwhm,args.airmass,args.instrumental_fwhm)) if fwhm > 0: if args.psf_beta > 0: psf = galsim.Moffat(beta = args.psf_beta, fwhm = fwhm) else: psf = galsim.Kolmogorov(fwhm = fwhm) (psfBounds,psfSizeMinus,psfSizePlus) = initializeForPsf(psf,pix,int(math.ceil(0.5*args.max_size/args.pixel_scale))) logger.info('PSF sig(-) = %.6f arcsec, sig(+) = %.6f arcsec' % (psfSizeMinus,psfSizePlus)) else: psf = None # Create an empty image that represents the whole field field = galsim.ImageD(args.width,args.height) field.setScale(pix.getXWidth()) # Calculate the relative scaling of RA and angles relative to the image center RAscale = math.cos(args.y_center*deg2rad) # Calculate the corners of the image in degrees RAmin = args.x_center - 0.5*args.width*args.pixel_scale/deg2arcsec/RAscale RAmax = args.x_center + 0.5*args.width*args.pixel_scale/deg2arcsec/RAscale DECmin = args.y_center - 0.5*args.height*args.pixel_scale/deg2arcsec DECmax = args.y_center + 0.5*args.height*args.pixel_scale/deg2arcsec # Calculate margin size in degrees (sources outside of our image margins # are always skipped, for speed, even if their tails might overlap our image) if args.no_margin: margin = 0 else: margin = 0.5*args.max_size/deg2arcsec # Calculate the sky background rate in elec/sec/pixel skyRate = args.zero_point*math.pow(10,-0.4*(args.sky_brightness-24))*args.pixel_scale**2 # Calculate the mean sky noise level for the full exposure time in elec/pixel skyNoise = math.sqrt(args.exposure_time*skyRate) # Calculate the pixel threshold cut to use in detected electrons during the full exposure pixelCut = args.sn_cut*skyNoise # Calculate the corresponding surface brightness cut to use sbCut = pixelCut/(args.pixel_scale*args.pixel_scale) print 'Simulating %s-band observations with AB24 zero point %.3f elec/sec, sky rate = %.3f elec/sec/pixel' %( args.band,args.zero_point,skyRate) print 'Simulating %.1fs exposure with total sky noise level %.3f elec/pixel (%.3f mag/sq.arcsec.)' % ( args.exposure_time,skyNoise,args.sky_brightness) print 'Will keep all stacked pixels > %.3f elec (%.1f elec/arcsec^2)' % (pixelCut,sbCut) # Initialize finite difference calculations if necessary if args.partials: args.stamps = True if args.partials_order < 1 or args.partials_order > 4: logger.error('Bad parameter: partials-order must be an integer 1-4.') sys.exit(-1) # Initialize the finite difference coefficients to use if args.partials_order == 1: fdCoefs = (1./2.,) elif args.partials_order == 2: fdCoefs = (2./3.,-1./12.) elif args.partials_order == 3: fdCoefs = (3./4.,-3./20.,1./60.) else: fdCoefs = (4./5.,-1./5.,4./105.,-1./280.) # Open the source input catalog to use and initialize a keyword-based lookup for catalog entries cat = open(args.input) catFields = cat.readline().split() catDict = dict(zip(catFields,range(len(catFields)))) if args.verbose: logger.info('Reading input catalog %r with fields:\n%s' % (args.input,','.join(catFields))) # Initialize the output catalog in memory outputCatalog = [ ] # Initialize the list of per-object stamp HDUs we will fill hdu = pyfits.PrimaryHDU() hduList = pyfits.HDUList([hdu]) stampList = [ ] fisherImagesList = [ ] nvar = 0 # declared here so it stays in scope after loop over galaxies # Loop over catalog entries nkeep = lineno = 0 for line in cat: lineno += 1 if args.only_line > 0 and lineno != args.only_line: continue # prepare to read this catalog entry entryCols = line.split() def catalog(fieldName,type=float): return type(entryCols[catDict[fieldName]]) entryID = catalog('id',int) # position on the sky in degrees RA = catalog('ra') DEC = catalog('dec') # skip sources outside our margins if RA < RAmin-margin or RA > RAmax+margin or DEC < DECmin-margin or DEC > DECmax+margin: continue # Calculate the offsets of this source from our image's bottom left corner in pixels # (which might be negative or byeond our image bounds because of the margins) xoffset = (RA - RAmin)*deg2arcsec/args.pixel_scale*RAscale yoffset = (DEC - DECmin)*deg2arcsec/args.pixel_scale # Look up redshift z = catalog('redshift') # Look up source AB magnitude in the requested band abMag = catalog(args.band + '_ab') # Correct for extinction abMag += args.extinction*(args.airmass - 1) # Calculate total detected signal in electrons flux = args.exposure_time*args.zero_point*math.pow(10,-0.4*(abMag-24)) # Skip objects whose total flux is below our pixel threshold if flux < pixelCut: continue # Look up the component flux relative normalizations diskFluxNorm = catalog('fluxnorm_disk') bulgeFluxNorm = catalog('fluxnorm_bulge') agnFluxNorm = catalog('fluxnorm_agn') totalFluxNorm = diskFluxNorm + bulgeFluxNorm + agnFluxNorm # Calculate the disk and bulge fluxes to simulate if args.no_disk: diskFlux = 0 else: diskFlux = flux*diskFluxNorm/totalFluxNorm if args.no_bulge: bulgeFlux = 0 else: bulgeFlux = flux*bulgeFluxNorm/totalFluxNorm if diskFlux == 0 and bulgeFlux == 0: continue # Get disk component parameters if diskFlux > 0: hlr_d = catalog('DiskHalfLightRadius') # in arcsecs pa_d = catalog('pa_disk') # position angle in degrees a_d = catalog('a_d') # major axis length in arcsecs b_d = catalog('b_d') # minor axis length in arcsecs # Calculate sheared ellipse aspect ratio q_d = b_d/a_d # between 0.2 and 1 # Convert position angle from degrees to radians pa_d = pa_d*deg2rad # Calculate bounding box in arcsecs without psf or pixel convolution (w_d,h_d) = sersicBounds(1,diskFlux+bulgeFlux,hlr_d,q_d,pa_d,sbCut) else: (w_d,h_d) = (0,0) # Get bulge component parameters if bulgeFlux > 0: hlr_b = catalog('BulgeHalfLightRadius') # in arcsecs pa_b = catalog('pa_bulge') # position angle in degrees a_b = catalog('a_b') # major axis length in arcsecs b_b = catalog('b_b') # minor axis length in arcsecs # Calculate sheared ellipse aspect ratio q_b = b_b/a_b # between 0.2 and 1 # Convert position angle from degrees to radians pa_b = pa_b*deg2rad # Calculate bounding box in arcsecs without psf or pixel convolution (w_b,h_b) = sersicBounds(4,diskFlux+bulgeFlux,hlr_b,q_b,pa_b,sbCut) else: (w_b,h_b) = (0,0) # If a component is missing, set its nominal size and shape from the other component. if diskFlux == 0: (hlr_d,q_d,pa_d) = (hlr_b,q_b,pa_b) if bulgeFlux == 0: (hlr_b,q_b,pa_b) = (hlr_d,q_d,pa_d) # Combine the bulge and disk ellipticities (sizeMinus,sizePlus,e1,e2) = combineEllipticities(hlr_d,q_d,pa_d,hlr_b,q_b,pa_b,bulgeFlux/(bulgeFlux+diskFlux)) # Combine the bulge and disk bounding boxes width = max(w_d,w_b) height = max(h_d,h_b) # Estimate the (round) bounding box for the psf in arscecs given our total flux psfBoxSize = psfBounds(flux,pixelCut)*args.pixel_scale if psf else 0 # Add the psf size in quadrature width = math.sqrt(width*width + psfBoxSize*psfBoxSize) height = math.sqrt(height*height + psfBoxSize*psfBoxSize) # Truncate the bounding box, if necessary if width > args.max_size or height > args.max_size: logger.info('...truncating bbbox from (%.1f,%.1f)' % (width,height)) width = min(width,args.max_size) height = min(height,args.max_size) # Skip this source if its pixels would all be below pixelCut (can this ever happen?) if (width,height) == (0,0): continue # Calculate the integer coordinates of the image pixel that contains the source center # (using the convention that the bottom left corner pixel has coordinates 1,1) xpixels = int(math.ceil(xoffset)) ypixels = int(math.ceil(yoffset)) # Calculate the stamp size to use as width = 2*xhalf+1 and height = 2*yhalf+1. # We always round up to an odd integer so that flux is consistently centered # (see Issue #380). xhalf = int(math.ceil(width/args.pixel_scale)) yhalf = int(math.ceil(height/args.pixel_scale)) # Trim the stamp so that the source is still centered but we do not extend # beyond the final field image. This will only trim pixels above pixelCut # that lie outside the field. if xpixels-xhalf < 1 and xpixels+xhalf > args.width: xhalf = max(xpixels-1,args.width-xpixels) if ypixels-yhalf < 1 and ypixels+yhalf > args.height: yhalf = max(ypixels-1,args.height-ypixels) # Build this source's stamp bounding box bbox = galsim.BoundsI(xpixels-xhalf,xpixels+xhalf,ypixels-yhalf,ypixels+yhalf) # Skip objects that don't overlap our field if (bbox & field.bounds).area() == 0: continue # If we get this far, we are definitely rendering this source (but it might # still get trimmed out later) logger.info('Rendering input catalog line %d (entry id %d) with w x h = %d x %d' % (lineno,entryID,2*xhalf+1,2*yhalf+1)) # Calculate the pixel coordinates of the stamp center. xstamp = 0.5*(bbox.xmin + bbox.xmax) ystamp = 0.5*(bbox.ymin + bbox.ymax) # Calculate the subpixel shift in arcsecs (not pixels!) of the source center # relative to the stamp center. Note that the resulting shift may be more than # one pixel in either direction because of the clipping operation above. xshift = (xoffset - (xstamp-0.5))*args.pixel_scale yshift = (yoffset - (ystamp-0.5))*args.pixel_scale if args.verbose: logger.info(' flux: %.3g electrons (%s-band AB %.1f)' % (flux,args.band,abMag)) logger.info(' bounds: [%d:%d,%d:%d] pixels' % (bbox.xmin,bbox.xmax,bbox.ymin,bbox.ymax)) logger.info(' shift: (%f,%f) arcsecs = (%f,%f) pixels' % (xshift,yshift,xshift/args.pixel_scale,yshift/args.pixel_scale)) logger.info(' disk: frac = %f, hlr = %f arcsec, q = %f, beta = %f rad' % (diskFlux/flux,hlr_d,q_d,pa_d)) logger.info(' bulge: frac = %f, hlr = %f arcsec, q = %f, beta = %f rad' % (bulgeFlux/flux,hlr_b,q_b,pa_b)) logger.info(' agn: frac = %f' % (agnFluxNorm/flux)) logger.info(' bbox: disk (%.1f,%.1f) bulge (%.1f,%.1f) psf %.1f arcsec' % (w_d,h_d,w_b,h_b,psfBoxSize)) logger.info(' size: %.2f (-) %.2f (+) arcsec' % (sizeMinus,sizePlus)) logger.info(' shape: (e1,e2) = (%.6f,%.6f)' % (e1,e2)) # Define the nominal source parameters for rendering this object within its stamp params = { 'total_flux': diskFlux + bulgeFlux, 'f_d': diskFlux/(diskFlux+bulgeFlux), 'f_b': bulgeFlux/(diskFlux+bulgeFlux), 'x_d': xshift, 'y_d': yshift, 'hlr_d': hlr_d, 'q_d': q_d, 'beta_d': pa_d, 'x_b': xshift, 'y_b': yshift, 'hlr_b': hlr_b, 'q_b': q_b, 'beta_b': pa_b, 'dx': 0., 'dy': 0., 'relsize': 1., 'dbeta': 0., 'g1': args.g1, 'g2': args.g2 } # Render the nominal stamps for this galaxy gal = createSource(**params) nominal = createStamp(gal,psf,pix,bbox) # Calculate the adaptive moments shape of this galaxy w/o psf (sizeMinusHSM,sizePlusHSM,e1HSM,e2HSM) = getStampMoments(gal,None,pix,bbox) if args.verbose: logger.info('HSM size: %.2f (-) %.2f (+) arcsec' % (sizeMinusHSM,sizePlusHSM)) logger.info('HSMshape: (e1,e2) = (%.6f,%.6f)' % (e1HSM,e2HSM)) # Create a mask for pixels above threshold mask = createMask(nominal,pixelCut,args) if mask.array.sum() == 0: # this stamp has no pixels above threshold logger.info('*** line %d (id %d) is below threshold' % (lineno,entryID)) continue trimmed = mask.bounds if args.verbose: logger.info(' trimmed: [%d:%d,%d:%d] pixels' % (trimmed.xmin,trimmed.xmax,trimmed.ymin,trimmed.ymax)) # Add the nominal galaxy to the full field image after applying the threshold mask # (the mask must be the second term in the product so that the result is double precision) maskedNominal = nominal[trimmed]*mask fieldOverlap = trimmed & field.bounds if fieldOverlap.area() == 0: # this stamp's mask falls completely outside our field logger.info('*** line %d (id %d) does not overlap field' % (lineno,entryID)) continue field[fieldOverlap] += maskedNominal[fieldOverlap] # Remember the nominal stamp (clipped to the field) for overlap calculations. stampList.append(maskedNominal[fieldOverlap]) # Calculate this object's nominal flux S/N ratio at full depth using only masked pixels. # Note that this value cannot be reproduced from the saved stamp when a stamp is clipped # to the field boundary (use --no-clip to disable this). snr = signalToNoiseRatio(maskedNominal,args.exposure_time*skyRate) if args.verbose: logger.info(' S/N: %.6f' % snr) # Initialize the datacube of stamps that we will save for this object datacube = [ ] partialsArray = [ ] # Save the nominal (masked and trimmed) stamp assert saveStamp(datacube,maskedNominal,args) if args.partials: # Specify the amount to vary each parameter for partial derivatives # (we don't use a dictionary here since we want to control the order) variations = [ ('f_d',0.01), ('f_b',0.01), ('dx',args.pixel_scale/3.),('dy',args.pixel_scale/3.), ('relsize',0.05), ('g1',0.03), ('g2',0.03) ] # the shape measurement parameters must always be the last 2 variations # since we make this assumption when slicing the covariance matrix below assert variations[-2][0] == 'g1' assert variations[-1][0] == 'g2' # loop over source parameters to vary for (pname,delta) in variations: # create stamps for each variation of this parameter newparams = params.copy() partial = galsim.ImageD(bbox) partial.setScale(pix.getXWidth()) # delta might be zero, e.g., for hlr_b when bulge fraction = 0 if delta > 0: for step in range(args.partials_order): # create and save the positive variation stamp newparams[pname] = params[pname] + (step+1)*delta newsource = createSource(**newparams) plus = createStamp(newsource,psf,pix,bbox) # create and save the negative variation stamp newparams[pname] = params[pname] - (step+1)*delta newsource = createSource(**newparams) minus = createStamp(newsource,psf,pix,bbox) # update the finite difference calculation of this partial partial += (fdCoefs[step]/delta)*(plus - minus) # append this partial to our datacube after trimming and masking maskedPartial = partial[trimmed]*mask assert saveStamp(datacube,maskedPartial,args) # remember this partial's numpy image array partialsArray.append(maskedPartial[fieldOverlap].array) # calculate the Fisher matrix images for this object (note that we haven't # included the Fisher denominator here since that might include overlapping # objects that we have not seen yet) nvar = len(partialsArray) nfisher = ((nvar+1)*nvar)/2 (h,w) = partialsArray[0].shape fisherImage = numpy.zeros((nfisher,h,w)) index = 0 for i in range(nvar): for j in range(i,nvar): fisherImage[index] = partialsArray[i]*partialsArray[j] index += 1 fisherImagesList.append(fisherImage) # Add a new HDU with a datacube for this object's stamps # We don't use compression = 'gzip_tile' for now since it is lossy # and mathematica cannot Import it. galsim.fits.writeCube(datacube, hdu_list = hduList) # Add a catalog entry for this galaxy entry = [entryID,xoffset,yoffset,abMag,flux/args.exposure_time, sizeMinus,sizePlus,e1,e2,sizeMinusHSM,sizePlusHSM,e1HSM,e2HSM, bulgeFlux/(diskFlux+bulgeFlux),z,snr] outputCatalog.append(entry) nkeep += 1 logger.info("saved entry id %d as stamp %d" % (entryID,nkeep)) # Close the input catalog cat.close() # Loop over all saved objects to test for overlaps and build overlap groups (groupID,groupSize) = analyzeOverlaps(stampList) # Add group id to output catalog for (i,entry) in enumerate(outputCatalog): entry.append(groupID[i]) # Do shape measurement error analysis for each galaxy purities = (0,0.5,0.9,0.99) regionsList = [ ] for i in range(nkeep): # use all objects in Fisher denominator (isolated = False) (errors,regions) = shapeErrorsAnalysis( nvar,stampList[i],fisherImagesList[i],args.exposure_time*skyRate,field,purities,isolated=False) outputCatalog[i].extend(errors) # Save the regions for each object outname = args.output + '_regions.fits' logger.info('Saving regions to %r' % outname) galsim.fits.writeMulti(regionsList,outname) # Save group sizes to a file outname = args.output + '_groups.dat' out = open(outname,'w') ntot = 0 for (i,n) in enumerate(groupSize): if n > 0: print >>out,i,n ntot += n out.close() assert ntot == len(groupSize) # Write the full field image without noise if args.save_field: # First without noise outname = args.output + '_field.fits' logger.info('Saving full field to %r' % outname) galsim.fits.write(field,outname) # Write the full field image with random noise added if args.save_noise: rng = galsim.BaseDeviate(123) noise = galsim.PoissonNoise(rng,sky_level = args.exposure_time*skyRate) field.addNoise(noise) outname = args.output + '_noise.fits' logger.info('Saving full field with noise added to %r' % outname) galsim.fits.write(field,outname) # Write the object stamp datacubes if args.stamps: outname = args.output + '_stamps.fits' logger.info('Saving %d stamps to %r' % (nkeep,outname)) galsim.fits.writeFile(outname, hduList) # Write the output catalog from memory outname = args.output + '_catalog.dat' out = open(outname,'w') for entry in outputCatalog: print >>out, ' '.join(map(str,entry)) out.close() logger.info('Wrote %d of %d catalog entries to %r' % (nkeep,lineno,outname)) if __name__ == "__main__": main() Add —skip-line option and allow both —skip-line and —keep-line options to be repeated #!/usr/bin/env python ####################################################################################### ## Created by David Kirkby, University of California, Irvine <dkirkby@uci.edu> ####################################################################################### """ ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.07 -o lsst_i --pixel-scale 0.200 --width 4096 --height 4096 --exposure-time 6900 --sky-brightness 20.0 --zenith-fwhm 0.67 --zero-point 41.5 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.07 -o des_i --pixel-scale 0.263 --width 3115 --height 3115 --exposure-time 1000 --sky-brightness 20.1 --zenith-fwhm 0.79 --zero-point 12.5 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.07 -o cfht_i --pixel-scale 0.185 --width 4428 --height 4428 --exposure-time 4300 --sky-brightness 20.3 --zenith-fwhm 0.64 --zero-point 10.0 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.10 -o lsst_r --pixel-scale 0.200 --width 4096 --height 4096 --exposure-time 6900 --sky-brightness 21.3 --zenith-fwhm 0.70 --zero-point 55.8 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.10 -o des_r --pixel-scale 0.263 --width 3115 --height 3115 --exposure-time 800 --sky-brightness 21.1 --zenith-fwhm 0.79 --zero-point 16.8 ./galsimcat.py -i OneDegSq.dat -x 0.5 -y 0.0 --max-size 30 --stamps --partials --save-field --save-noise --airmass 1.2 --extinction 0.10 -o cfht_r --pixel-scale 0.185 --width 4428 --height 4428 --exposure-time 2000 --sky-brightness 20.8 --zenith-fwhm 0.71 --zero-point 13.5 """ import sys import os import math import argparse import logging import galsim import pyfits import numpy twopi = 2*math.pi deg2rad = math.pi/180. deg2arcsec = 3600. deg2arcmin = 60. def createComponent(type,electrons,xc,yc,hlr,q,beta,g1,g2): # create a radial profile of the requested type and size comp = type(flux = electrons, half_light_radius = hlr) # set the intrinsic shape comp.applyShear(q = q, beta = beta*galsim.radians) # apply cosmic shear comp.applyShear(g1 = g1, g2 = g2) # shift to this component's centroid comp.applyShift(dx = xc, dy = yc) return comp """ Returns a (disk,bulge) tuple of source objects using the specified parameters. Note that f_d and f_b are fractions of the total flux and need not sum to one. """ def createSource( total_flux,f_d,f_b, x_d,y_d,hlr_d,q_d,beta_d, x_b,y_b,hlr_b,q_b,beta_b, dx,dy,relsize,dbeta, g1,g2): # Define the disk component, if any if f_d > 0: disk = createComponent(galsim.Exponential, total_flux*f_d,x_d+dx,y_d+dy,hlr_d*relsize,q_d,beta_d+dbeta,g1,g2) else: disk = None # Define the bulge component, if any if f_b > 0: bulge = createComponent(galsim.DeVaucouleurs, total_flux*f_b,x_b+dx,y_b+dy,hlr_b*relsize,q_b,beta_b+dbeta,g1,g2) else: bulge = None return (disk,bulge) """ Renders the convolution of [src,psf,pix] into the specified bounding box. If psf is None, only [src,pix] are convolved. If src is None, an empty stamp is returned (we use this below when either the bulge or disk is absent). """ def renderStamp(src,psf,pix,bbox): stamp = galsim.ImageD(bbox) stamp.setScale(pix.getXWidth()) if src: models = [src,pix] if psf is None else [src,psf,pix] gsp = galsim.GSParams(maximum_fft_size=32768) obj = galsim.Convolve(models,gsparams=gsp) obj.draw(image = stamp) return stamp """ Renders the specified source convolved with a psf (which might be None) and pixel response into a postage stamp with the specified bounding box. """ def createStamp(src,psf,pix,bbox): (disk,bulge) = src diskStamp = renderStamp(disk,psf,pix,bbox) bulgeStamp = renderStamp(bulge,psf,pix,bbox) return diskStamp + bulgeStamp """ Calculate the centroid, size, and shape of the convolution of [src,psf,pix] in the specified bounding box using a high-resolution image whose pixels are smaller by a factor of oversampling (in each direction), and whose stamp is larger by a factor of zoom (in each direction). The centroid and size are returned in arcsecs. The centroid is relative to the center of the input bounding box. """ def getStampMoments(src,psf,pix,bbox,oversampling=5,zoom=1): # Create a high-resolution pixel grid that covers the same area, and # preserves the even/oddness and mean (min+max)/2. of each dimension. (x1,x2,y1,y2) = (bbox.getXMin(),bbox.getXMax(),bbox.getYMin(),bbox.getYMax()) xmid = (x1+x2)/2. dx = oversampling*(x2-x1)/2. x1 = int(math.floor(xmid - zoom*dx)) x2 = int(math.ceil(xmid + zoom*dx)) assert (x1+x2)/2. == xmid ymid = (y1+y2)/2. dy = oversampling*(y2-y1)/2. y1 = int(math.floor(ymid - zoom*dy)) y2 = int(math.ceil(ymid + zoom*dy)) assert (y1+y2)/2. == ymid bigBbox = galsim.BoundsI(x1,x2,y1,y2) scale = pix.getXWidth()/oversampling smallPix = galsim.Pixel(scale) try: # Render a high-resolution stamp of this source (might fail # with an SB error, e.g., if a bigger FFT is required) stamp = createStamp(src,psf,smallPix,bigBbox) # Try to calculate this stamp's adaptive moments shape = stamp.FindAdaptiveMom() sig_minus = shape.moments_sigma*scale # in arcsecs (e1,e2) = (shape.observed_shape.getG1(),shape.observed_shape.getG2()) emagsq = e1*e1 + e2*e2 ratio = (1+emagsq)/(1-emagsq) sig_plus = sig_minus*math.sqrt(ratio) return (sig_minus,sig_plus,e1,e2) except RuntimeError,e: print 'getStampMoments: %s' % (str(e).strip()) return (-1.,-1.,0.,0.) """ Returns (dx,dy) for the bounding box of a surface brightness profile SB(x,y) whose isophotes are ellipses with the shape (q,beta) and which has an underlying normalized radial profile p(r). The inputs are: maxSB = totalFlux*p(0) = maximum surface brightness before shear thresholdSB = threshold surface brightness after shear q = ratio of minor to major axes of ellipse with 0 < q <= 1 beta = angle of ellipse's major axis in radians rFunction = returns R(b) such that p(R) = b*p(0) with 0 < b < 1 The returned (dx,dy) are in arcsecs, and defined such that SB(x,y) < f0 is guaranteed for |x| > dx or |y| > dy. The result only depends on the ratio thresholdSB/maxSB so they must be in the same (abitrary) units. """ def boundingBox(maxSB,thresholdSB,q,beta,rFunction): # Calculate shear affine transform parameters g = (1-q)/(1+q) gp = g*math.cos(2*beta) gx = g*math.sin(2*beta) detM = 1 - gp*gp - gx*gx # Calculate the dimensionless surface brightness ratio at threshold. b = thresholdSB/(maxSB*detM) if b <= 0: raise RuntimeError('boundingBox: invalid input parameters') if b >= 1: # The max surface brightness is below our threshold SB(0,0) <= f0 return (0,0) # Calculate the threshold radius of the radial profile. rcut = rFunction(b) # Shear this circle and return its bounding box dimensions dx = rcut*math.sqrt(((1+gp)*(1+gp)+gx*gx)/detM) # half width in arcsecs dy = rcut*math.sqrt(((1-gp)*(1-gp)+gx*gx)/detM) # half height in arcsecs return (dx,dy) """ Returns (dx,dy) for the bounding box of a Sersic profile with n = 1 or 4. The input flux should be in electrons, hlr in arscecs, beta in radians, f0 in elec/arcsec^2. 0 < q <= 1 is dimensionless. The returned (dx,dy) are in arcsecs. See boundingBox above for details. """ def sersicBounds(n,flux,hlr,q,beta,f0): # Convert the half-light radius to the appropriate scale radius r0 # and calculate the Sersic normalization constant if n == 1: r0 = hlr/1.67835 norm = twopi*r0*r0 elif n == 4: r0 = hlr/3459.49 norm = 20160*twopi*r0*r0 # 20160 = n*Gamma[2*n] else: raise RuntimeError('Sersic index n = %d is not supported.' % n) # Calculate and return the bounding box return boundingBox(flux/norm,f0,q,beta, lambda b: r0*math.pow(-math.log(b),n)) """ Returns (dx,dy) for the bounding box of a Moffat profile. The input flux should be in electrons, fwhm in arcsecs, beta in radians, f0 in elec/arcsec^2. 0 < q <= 1 and moffatBeta > 1 are dimensionless. The returned (dx,dy) are in arcsecs. See boundingBox above for details. """ def moffatBounds(moffatBeta,flux,fwhm,q,beta,f0): # Check that moffatBeta is valid if moffatBeta <= 1: raise RuntimeError('Moffat beta < 1 is not valid.') # Convert the fwhm to the corresponding scale radius r0 = 0.5*fwhm/math.sqrt(math.pow(2,1./moffatBeta)-1) # Calculate the normalization factor norm = 1/p(0) norm = math.pi*r0*r0/(moffatBeta-1) # Calculate and return the bounding box return boundingBox(flux/norm,f0,q,beta, lambda b: r0*math.sqrt(1-math.pow(b,(moffatBeta-1.)/moffatBeta))) """ Returns a mask image of values 0 or 1 depending on whether the corresponding input image pixel value is above or below the specified threshold in electrons. Note that if all pixels are below threshold, then the returned mask will contain only the central pixel with image.array.sum() == 0. """ def createMask(image,threshold,args): # create an empty mask image with the same dimensions as the input image box = image.bounds mask = galsim.ImageS(box) mask.setScale(image.getScale()) borderMax = 0. lastRow = box.ymax - box.ymin lastPixel = box.xmax - box.xmin # initialize our trimmed bounds to just the central pixel # (the numerator should always be even for odd width,height) xmin = (box.getXMin()+box.getXMax()) ymin = (box.getYMin()+box.getYMax()) assert xmin%2 == 0 and ymin%2 == 0 xmin = xmin/2 ymin = ymin/2 xmax = xmin ymax = ymin # loop over image pixels for (rowIndex,row) in enumerate(image.array): y = box.getYMin()+rowIndex for (pixelIndex,pixelValue) in enumerate(row): x = box.getXMin()+pixelIndex if rowIndex == 0 or rowIndex == lastRow or pixelIndex == 0 or pixelIndex == lastPixel: # update the largest pixel value on our 1-pixel wide border borderMax = max(borderMax,pixelValue) if pixelValue >= threshold: mask.array[rowIndex,pixelIndex] = 1 xmin = min(x,xmin) xmax = max(x,xmax) ymin = min(y,ymin) ymax = max(y,ymax) # is the stamp too small to contain the threshold contour? if borderMax > threshold: print '### stamp truncated at %.1f > %.1f electrons' % (borderMax,threshold) # build a new mask using the border max as the threshold return createMask(image,borderMax,args) trimmed = galsim.BoundsI(xmin,xmax,ymin,ymax) mask = mask[trimmed] return mask """ Performs any final processing on stamp, controlled by args, then appends it to stamps. Returns True if the stamp was saved, or otherwise False. """ def saveStamp(stamps,stamp,args): # Clip the stamp so that does not extend beyond the field image. This results # in potentially smaller files with sources that might not be centered. if not args.no_clip: overlap = stamp.bounds & galsim.BoundsI(1,args.width,1,args.height) if overlap.area() == 0: # skip this stamp if it falls completely outside our field (after trimming) return False stamp = stamp[overlap] # Convert normalization from elec/exposure to elec/second stamp = stamp/args.exposure_time # Remember this stamp. stamps.append(stamp) return True """ Performs initializations for the psf we will be using. """ def initializeForPsf(psf,pix,size): # Render a centered psf image bbox = galsim.BoundsI(1,2*size,1,2*size) stamp = galsim.ImageD(bbox) scale = pix.getXWidth() stamp.setScale(scale) obj = galsim.Convolve([psf,pix]) obj.draw(image=stamp) # Build the circularized psf profile profile = numpy.zeros(size,dtype=float) for x in range(2*size): for y in range(2*size): dx = x - size + 0.5 dy = y - size + 0.5 r = math.sqrt(dx*dx + dy*dy) ipix = int(math.floor(r)) if ipix < size: profile[ipix] = max(profile[ipix],stamp.array[x,y]) # Create a function that gives the size of bounding box necessary to contain # psf pixels down to the specified threshold assuming the specified total flux. # The return value is clipped at 2*size for large fluxes. def estimator(flux,threshold): index = 0 while index < size: if flux*profile[index] < threshold: return 2*index+1 index += 1 return 2*size # Calculate the psf size from a high-resolution rendering (psfSizeMinus,psfSizePlus,e1,e2) = getStampMoments((psf,None),None,pix,bbox) assert abs(e1) < 1e-6 and abs(e2) < 1e-6 return (estimator,psfSizeMinus,psfSizePlus) # Returns the combined size and ellipticity for the specified disk and bulge components, # assuming they have the same centroid. def combineEllipticities(hlr_d,q_d,pa_d,hlr_b,q_b,pa_b,f_b): # ensure that single-component models give correct results if f_b == 0: q_b = 1 elif f_b == 1: q_d = 1 # calculate the disk and bulge component ellipticities ed = (1-q_d)/(1+q_d) ed1 = ed*math.cos(2*pa_d) ed2 = ed*math.sin(2*pa_d) eb = (1-q_b)/(1+q_b) eb1 = eb*math.cos(2*pa_b) eb2 = eb*math.sin(2*pa_b) # calculate the corresponding second-moment tensors assuming unit total flux cd = 1.06502 nd = cd*(hlr_d/(1-ed*ed))**2 Qd11 = nd*(1+ed*ed+2*ed1) Qd12 = nd*2*ed2 Qd22 = nd*(1+ed*ed-2*ed1) detQd = Qd11*Qd22 - Qd12*Qd12 cb = 10.8396 nb = cb*(hlr_b/(1-eb*eb))**2 Qb11 = nb*(1+eb*eb+2*eb1) Qb12 = nb*2*eb2 Qb22 = nb*(1+eb*eb-2*eb1) detQb = Qb11*Qb22 - Qb12*Qb12 # add the component second-moment tensors Q11 = (1-f_b)*Qd11 + f_b*Qb11 Q12 = (1-f_b)*Qd12 + f_b*Qb12 Q22 = (1-f_b)*Qd22 + f_b*Qb22 detQ = Q11*Q22 - Q12*Q12 sizeMinus = math.pow(detQ,0.25) sizePlus = math.sqrt(0.5*(Q11+Q22)) #semiMajorAxis = math.sqrt(0.5*(Q11+Q22+math.sqrt((Q11-Q22)**2+4*Q12**2))) # calculate the corresponding combined ellipticity denom = Q11 + Q22 + 2*math.sqrt(detQ) e1 = (Q11 - Q22)/denom e2 = 2*Q12/denom """ # check direct calculation of emag when pa_d == pa_b emag = math.sqrt(e1*e1 + e2*e2) wd = (1-f_b)*cd*hlr_d**2*(1+q_d)**2/(8*q_d**2) if f_b < 1 else 0 wm = f_b*cb*hlr_b**2*(1+q_b)**2/(8*q_b**2) if f_b > 0 else 0 ep = wd*(1+q_d**2) + wm*(1+q_b**2) em = wd*(1-q_d**2) + wm*(1-q_b**2) emag2 = em/(ep+math.sqrt(ep*ep-em*em)) print 'emag:',emag-emag2 """ return (sizeMinus,sizePlus,e1,e2) def signalToNoiseRatio(stamp,pixelNoise): flat = stamp.array.reshape(-1) snr = math.sqrt(numpy.dot(flat,flat)/pixelNoise) return snr # Returns True if the stamps s1 and s2 have overlapping pixels with non-zero flux. def overlapping(s1,s2): # test for overlapping bounding boxes overlapBounds = s1.bounds & s2.bounds if overlapBounds.area() == 0: return False # test for overlapping flux within the overlapping pixels overlapFluxProduct = numpy.sum(s1[overlapBounds].array * s2[overlapBounds].array) return False if overlapFluxProduct == 0 else True # Assigns a group ID to each stamp in stamps based on its overlaps with other stamps. def analyzeOverlaps(stamps): groupID = range(len(stamps)) groupSize = [1]*len(stamps) for (i1,s1) in enumerate(stamps): for (i2,s2) in enumerate(stamps[:i1]): if overlapping(s1,s2): # get the current group IDs of these overlapping stamps gid1 = groupID[i1] gid2 = groupID[i2] if gid1 == gid2: continue # decide which group joins the other gnew = min(gid1,gid2) gold = max(gid1,gid2) # re-assign all stamps in gold to gnew for i in range(i1+1): if groupID[i] == gold: groupID[i] = gnew groupSize[gnew] += 1 groupSize[gold] -= 1 return (groupID,groupSize) # Builds the Fisher matrix from the specified array of npar*(npar+1)/2 Fisher images and # calculates the corresponding shape-measurment error, if possible. def shapeError(npar,fisherImages,fisherDenominator,mask): # calculate the Fisher matrix elements by summing pixels of the specified Fisher matrix images fisherMatrix = numpy.zeros((npar,npar)) index = 0 for i in range(npar): for j in range(i,npar): fisherMatrix[i,j] = numpy.sum(fisherImages[index]/fisherDenominator*mask) if i != j: fisherMatrix[j,i] = fisherMatrix[i,j] index += 1 # try to calculate corresponding shape measurement error, which will fail unless # the Fisher matrix is invertible try: fullCov = numpy.linalg.inv(fisherMatrix) # this is where we assume that the last 2 variations are g1,g2 varEps = 0.5*(fullCov[-2,-2]+fullCov[-1,-1]) # variance might be negative if inverse has large numerical errors sigmaEps = 0 if varEps <= 0 else math.sqrt(varEps) except numpy.linalg.LinAlgError: # assign a shape-measurement error of zero if the Fisher matrix is not invertible. sigmaEps = 0. return sigmaEps # Calculate shape measurment errors with the specified purity cuts. Returns a tuple of the # corresponding errors, in a list, and an integer-valued image that identifies the purity # regions by assigning each pixel the value of the largest index such that # nominal > purity[index]*field (or zero if this criteria is not met for any purity). def shapeErrorsAnalysis(npar,nominal,fisherImages,noiseVariance,field,purities,isolated=True): # find the overlap of this object in the full field overlap = nominal.bounds & field.bounds # get the pixel values for this object and all objects in the overlap subNominal = nominal[overlap].array subField = field[overlap].array # calculate the denominator array for our Fisher matrix elements, including # all objects unless we are pretending that this object is isolated fisherDenominator = (subNominal if isolated else subField) + noiseVariance # initialize our integer regions image regions = galsim.ImageI(nominal.bounds) regionsArray = regions.array errors = [ ] for (i,purity) in enumerate(purities): mask = (subNominal > purity*subField) regionsArray = numpy.maximum(regionsArray,i*mask) sigeps = shapeError(npar,fisherImages,fisherDenominator,mask) errors.append(sigeps) regions.array[:] = regionsArray[:] return (errors,regions) def main(): # Parse command-line args parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action = "store_true", help = "provide more verbose output") parser.add_argument("-i", "--input", default = 'gcat.dat', help = "name of input catalog to read") parser.add_argument("-o","--output", default = 'catout', help = "base name of output files to write") parser.add_argument("-x","--x-center", type = float, default = 0.5, help = "central RA of image (degrees)") parser.add_argument("-y","--y-center", type = float, default = 0.0, help = "central DEC of image (degrees)") parser.add_argument("--width", type = int, default = 512, help = "image width (pixels)") parser.add_argument("--height", type = int, default = 512, help = "image height (pixels)") parser.add_argument("--max-size", type = float, default = 20., help = "flux from any object is truncated beyond this size (arcsecs)") parser.add_argument("--no-margin", action = "store_true", help = "do not simulate the tails of objects just outside the field") parser.add_argument("--pixel-scale", type = float, default = 0.2, help = "pixel scale (arscecs/pixel)") parser.add_argument("--airmass", type = float, default = 1.2, help = "airmass value to use for atmospheric PSF and extinction") parser.add_argument("--extinction", type = float, default = 0.07, help = "atmospheric extinction coefficient") parser.add_argument("--zenith-fwhm", type = float, default = 0.67, help = "atmospheric psf full-width-half-max in arcsecs at zenith") parser.add_argument("--instrumental-fwhm", type = float, default = 0.4, help = "instrumental psf full-width-half-max in arcsecs") parser.add_argument("--psf-beta", type = float, default = 0.0, help = "psf Moffat parameter beta (uses Kolmogorov psf if beta <= 0)") parser.add_argument("--band", choices = ['u','g','r','i','z','y'], default = 'i', help = "LSST imaging band to use for source fluxes") parser.add_argument("--zero-point", type = float, default = 41.5, help = "zero point for converting magnitude to detected signal in elec/sec") parser.add_argument("--sky-brightness", type = float, default = 20.0, help = "sky brightness in mag/sq.arcsec.") parser.add_argument("--sn-cut", type = float, default = 0.5, help = "keep all pixels above this signal-to-noise ratio cut") parser.add_argument("--exposure-time", type = float, default = 6900., help = "full-depth exposure time in seconds") parser.add_argument("--g1", type = float, default = 0., help = "constant shear component g1 to apply") parser.add_argument("--g2", type = float, default = 0., help = "constant shear component g2 to apply") parser.add_argument("--save-field", action = "store_true", help = "save full field image without noise") parser.add_argument("--save-noise", action = "store_true", help = "save full field image with random noise added") parser.add_argument("--stamps", action = "store_true", help = "save postage stamps for each source (normalized to 1 exposure)") parser.add_argument("--no-clip", action = "store_true", help = "do not clip stamps to the image bounds") parser.add_argument("--no-disk", action = "store_true", help = "do not include any galactic disk (Sersic n=1) components") parser.add_argument("--no-bulge", action = "store_true", help = "do not include any galactic bulge (Sersic n=4) components") parser.add_argument("--shape", action = "store_true", help = "run HSM adaptive moments calculation on no-psf stamp") parser.add_argument("--partials", action = "store_true", help = "calculate and save partial derivatives wrt shape parameters (normalized to 1 exposure)") parser.add_argument("--partials-order", type = int, default = 1, help = "order of finite difference equation to use for evaluating partials") parser.add_argument("--only-line", type = int, action = "append", help = "only use the specified line number from the input catalog (can be repeated)") parser.add_argument("--skip-line", type = int, action = "append", help = "skip the specified line number from the input catalog (can be repeated)") args = parser.parse_args() # Configure the GalSim logger logging.basicConfig(format="%(message)s", level=logging.INFO, stream=sys.stdout) logger = logging.getLogger("galsimcat") logger.info('Using output prefix %r' % args.output) # Define the pixel response pix = galsim.Pixel(args.pixel_scale) # Define the psf to use atmos_fwhm = args.zenith_fwhm*math.pow(args.airmass,0.6) fwhm = math.sqrt(atmos_fwhm**2 + args.instrumental_fwhm**2) logger.info('Using PSF fwhm = %.4f" (%.4f" zenith => %.4f" at X = %.3f, %.4f" instrumental)' % (fwhm,args.zenith_fwhm,atmos_fwhm,args.airmass,args.instrumental_fwhm)) if fwhm > 0: if args.psf_beta > 0: psf = galsim.Moffat(beta = args.psf_beta, fwhm = fwhm) else: psf = galsim.Kolmogorov(fwhm = fwhm) (psfBounds,psfSizeMinus,psfSizePlus) = initializeForPsf(psf,pix,int(math.ceil(0.5*args.max_size/args.pixel_scale))) logger.info('PSF sig(-) = %.6f arcsec, sig(+) = %.6f arcsec' % (psfSizeMinus,psfSizePlus)) else: psf = None # Create an empty image that represents the whole field field = galsim.ImageD(args.width,args.height) field.setScale(pix.getXWidth()) # Calculate the relative scaling of RA and angles relative to the image center RAscale = math.cos(args.y_center*deg2rad) # Calculate the corners of the image in degrees RAmin = args.x_center - 0.5*args.width*args.pixel_scale/deg2arcsec/RAscale RAmax = args.x_center + 0.5*args.width*args.pixel_scale/deg2arcsec/RAscale DECmin = args.y_center - 0.5*args.height*args.pixel_scale/deg2arcsec DECmax = args.y_center + 0.5*args.height*args.pixel_scale/deg2arcsec # Calculate margin size in degrees (sources outside of our image margins # are always skipped, for speed, even if their tails might overlap our image) if args.no_margin: margin = 0 else: margin = 0.5*args.max_size/deg2arcsec # Calculate the sky background rate in elec/sec/pixel skyRate = args.zero_point*math.pow(10,-0.4*(args.sky_brightness-24))*args.pixel_scale**2 # Calculate the mean sky noise level for the full exposure time in elec/pixel skyNoise = math.sqrt(args.exposure_time*skyRate) # Calculate the pixel threshold cut to use in detected electrons during the full exposure pixelCut = args.sn_cut*skyNoise # Calculate the corresponding surface brightness cut to use sbCut = pixelCut/(args.pixel_scale*args.pixel_scale) print 'Simulating %s-band observations with AB24 zero point %.3f elec/sec, sky rate = %.3f elec/sec/pixel' %( args.band,args.zero_point,skyRate) print 'Simulating %.1fs exposure with total sky noise level %.3f elec/pixel (%.3f mag/sq.arcsec.)' % ( args.exposure_time,skyNoise,args.sky_brightness) print 'Will keep all stacked pixels > %.3f elec (%.1f elec/arcsec^2)' % (pixelCut,sbCut) # Initialize finite difference calculations if necessary if args.partials: args.stamps = True if args.partials_order < 1 or args.partials_order > 4: logger.error('Bad parameter: partials-order must be an integer 1-4.') sys.exit(-1) # Initialize the finite difference coefficients to use if args.partials_order == 1: fdCoefs = (1./2.,) elif args.partials_order == 2: fdCoefs = (2./3.,-1./12.) elif args.partials_order == 3: fdCoefs = (3./4.,-3./20.,1./60.) else: fdCoefs = (4./5.,-1./5.,4./105.,-1./280.) # Open the source input catalog to use and initialize a keyword-based lookup for catalog entries cat = open(args.input) catFields = cat.readline().split() catDict = dict(zip(catFields,range(len(catFields)))) if args.verbose: logger.info('Reading input catalog %r with fields:\n%s' % (args.input,','.join(catFields))) # Initialize the output catalog in memory outputCatalog = [ ] # Initialize the list of per-object stamp HDUs we will fill hdu = pyfits.PrimaryHDU() hduList = pyfits.HDUList([hdu]) stampList = [ ] fisherImagesList = [ ] nvar = 0 # declared here so it stays in scope after loop over galaxies # Loop over catalog entries nkeep = lineno = 0 for line in cat: lineno += 1 if args.only_line and lineno not in args.only_line: continue if args.skip_line and lineno in args.skip_line: continue # prepare to read this catalog entry entryCols = line.split() def catalog(fieldName,type=float): return type(entryCols[catDict[fieldName]]) entryID = catalog('id',int) # position on the sky in degrees RA = catalog('ra') DEC = catalog('dec') # skip sources outside our margins if RA < RAmin-margin or RA > RAmax+margin or DEC < DECmin-margin or DEC > DECmax+margin: continue # Calculate the offsets of this source from our image's bottom left corner in pixels # (which might be negative or byeond our image bounds because of the margins) xoffset = (RA - RAmin)*deg2arcsec/args.pixel_scale*RAscale yoffset = (DEC - DECmin)*deg2arcsec/args.pixel_scale # Look up redshift z = catalog('redshift') # Look up source AB magnitude in the requested band abMag = catalog(args.band + '_ab') # Correct for extinction abMag += args.extinction*(args.airmass - 1) # Calculate total detected signal in electrons flux = args.exposure_time*args.zero_point*math.pow(10,-0.4*(abMag-24)) # Skip objects whose total flux is below our pixel threshold if flux < pixelCut: continue # Look up the component flux relative normalizations diskFluxNorm = catalog('fluxnorm_disk') bulgeFluxNorm = catalog('fluxnorm_bulge') agnFluxNorm = catalog('fluxnorm_agn') totalFluxNorm = diskFluxNorm + bulgeFluxNorm + agnFluxNorm # Calculate the disk and bulge fluxes to simulate if args.no_disk: diskFlux = 0 else: diskFlux = flux*diskFluxNorm/totalFluxNorm if args.no_bulge: bulgeFlux = 0 else: bulgeFlux = flux*bulgeFluxNorm/totalFluxNorm if diskFlux == 0 and bulgeFlux == 0: continue # Get disk component parameters if diskFlux > 0: hlr_d = catalog('DiskHalfLightRadius') # in arcsecs pa_d = catalog('pa_disk') # position angle in degrees a_d = catalog('a_d') # major axis length in arcsecs b_d = catalog('b_d') # minor axis length in arcsecs # Calculate sheared ellipse aspect ratio q_d = b_d/a_d # between 0.2 and 1 # Convert position angle from degrees to radians pa_d = pa_d*deg2rad # Calculate bounding box in arcsecs without psf or pixel convolution (w_d,h_d) = sersicBounds(1,diskFlux+bulgeFlux,hlr_d,q_d,pa_d,sbCut) else: (w_d,h_d) = (0,0) # Get bulge component parameters if bulgeFlux > 0: hlr_b = catalog('BulgeHalfLightRadius') # in arcsecs pa_b = catalog('pa_bulge') # position angle in degrees a_b = catalog('a_b') # major axis length in arcsecs b_b = catalog('b_b') # minor axis length in arcsecs # Calculate sheared ellipse aspect ratio q_b = b_b/a_b # between 0.2 and 1 # Convert position angle from degrees to radians pa_b = pa_b*deg2rad # Calculate bounding box in arcsecs without psf or pixel convolution (w_b,h_b) = sersicBounds(4,diskFlux+bulgeFlux,hlr_b,q_b,pa_b,sbCut) else: (w_b,h_b) = (0,0) # If a component is missing, set its nominal size and shape from the other component. if diskFlux == 0: (hlr_d,q_d,pa_d) = (hlr_b,q_b,pa_b) if bulgeFlux == 0: (hlr_b,q_b,pa_b) = (hlr_d,q_d,pa_d) # Combine the bulge and disk ellipticities (sizeMinus,sizePlus,e1,e2) = combineEllipticities(hlr_d,q_d,pa_d,hlr_b,q_b,pa_b,bulgeFlux/(bulgeFlux+diskFlux)) # Combine the bulge and disk bounding boxes width = max(w_d,w_b) height = max(h_d,h_b) # Estimate the (round) bounding box for the psf in arscecs given our total flux psfBoxSize = psfBounds(flux,pixelCut)*args.pixel_scale if psf else 0 # Add the psf size in quadrature width = math.sqrt(width*width + psfBoxSize*psfBoxSize) height = math.sqrt(height*height + psfBoxSize*psfBoxSize) # Truncate the bounding box, if necessary if width > args.max_size or height > args.max_size: logger.info('...truncating bbbox from (%.1f,%.1f)' % (width,height)) width = min(width,args.max_size) height = min(height,args.max_size) # Skip this source if its pixels would all be below pixelCut (can this ever happen?) if (width,height) == (0,0): continue # Calculate the integer coordinates of the image pixel that contains the source center # (using the convention that the bottom left corner pixel has coordinates 1,1) xpixels = int(math.ceil(xoffset)) ypixels = int(math.ceil(yoffset)) # Calculate the stamp size to use as width = 2*xhalf+1 and height = 2*yhalf+1. # We always round up to an odd integer so that flux is consistently centered # (see Issue #380). xhalf = int(math.ceil(width/args.pixel_scale)) yhalf = int(math.ceil(height/args.pixel_scale)) # Trim the stamp so that the source is still centered but we do not extend # beyond the final field image. This will only trim pixels above pixelCut # that lie outside the field. if xpixels-xhalf < 1 and xpixels+xhalf > args.width: xhalf = max(xpixels-1,args.width-xpixels) if ypixels-yhalf < 1 and ypixels+yhalf > args.height: yhalf = max(ypixels-1,args.height-ypixels) # Build this source's stamp bounding box bbox = galsim.BoundsI(xpixels-xhalf,xpixels+xhalf,ypixels-yhalf,ypixels+yhalf) # Skip objects that don't overlap our field if (bbox & field.bounds).area() == 0: continue # If we get this far, we are definitely rendering this source (but it might # still get trimmed out later) logger.info('Rendering input catalog line %d (entry id %d) with w x h = %d x %d' % (lineno,entryID,2*xhalf+1,2*yhalf+1)) # Calculate the pixel coordinates of the stamp center. xstamp = 0.5*(bbox.xmin + bbox.xmax) ystamp = 0.5*(bbox.ymin + bbox.ymax) # Calculate the subpixel shift in arcsecs (not pixels!) of the source center # relative to the stamp center. Note that the resulting shift may be more than # one pixel in either direction because of the clipping operation above. xshift = (xoffset - (xstamp-0.5))*args.pixel_scale yshift = (yoffset - (ystamp-0.5))*args.pixel_scale if args.verbose: logger.info(' flux: %.3g electrons (%s-band AB %.1f)' % (flux,args.band,abMag)) logger.info(' bounds: [%d:%d,%d:%d] pixels' % (bbox.xmin,bbox.xmax,bbox.ymin,bbox.ymax)) logger.info(' shift: (%f,%f) arcsecs = (%f,%f) pixels' % (xshift,yshift,xshift/args.pixel_scale,yshift/args.pixel_scale)) logger.info(' disk: frac = %f, hlr = %f arcsec, q = %f, beta = %f rad' % (diskFlux/flux,hlr_d,q_d,pa_d)) logger.info(' bulge: frac = %f, hlr = %f arcsec, q = %f, beta = %f rad' % (bulgeFlux/flux,hlr_b,q_b,pa_b)) logger.info(' agn: frac = %f' % (agnFluxNorm/flux)) logger.info(' bbox: disk (%.1f,%.1f) bulge (%.1f,%.1f) psf %.1f arcsec' % (w_d,h_d,w_b,h_b,psfBoxSize)) logger.info(' size: %.2f (-) %.2f (+) arcsec' % (sizeMinus,sizePlus)) logger.info(' shape: (e1,e2) = (%.6f,%.6f)' % (e1,e2)) # Define the nominal source parameters for rendering this object within its stamp params = { 'total_flux': diskFlux + bulgeFlux, 'f_d': diskFlux/(diskFlux+bulgeFlux), 'f_b': bulgeFlux/(diskFlux+bulgeFlux), 'x_d': xshift, 'y_d': yshift, 'hlr_d': hlr_d, 'q_d': q_d, 'beta_d': pa_d, 'x_b': xshift, 'y_b': yshift, 'hlr_b': hlr_b, 'q_b': q_b, 'beta_b': pa_b, 'dx': 0., 'dy': 0., 'relsize': 1., 'dbeta': 0., 'g1': args.g1, 'g2': args.g2 } # Render the nominal stamps for this galaxy gal = createSource(**params) nominal = createStamp(gal,psf,pix,bbox) # Calculate the adaptive moments shape of this galaxy w/o psf (sizeMinusHSM,sizePlusHSM,e1HSM,e2HSM) = getStampMoments(gal,None,pix,bbox) if args.verbose: logger.info('HSM size: %.2f (-) %.2f (+) arcsec' % (sizeMinusHSM,sizePlusHSM)) logger.info('HSMshape: (e1,e2) = (%.6f,%.6f)' % (e1HSM,e2HSM)) # Create a mask for pixels above threshold mask = createMask(nominal,pixelCut,args) if mask.array.sum() == 0: # this stamp has no pixels above threshold logger.info('*** line %d (id %d) is below threshold' % (lineno,entryID)) continue trimmed = mask.bounds if args.verbose: logger.info(' trimmed: [%d:%d,%d:%d] pixels' % (trimmed.xmin,trimmed.xmax,trimmed.ymin,trimmed.ymax)) # Add the nominal galaxy to the full field image after applying the threshold mask # (the mask must be the second term in the product so that the result is double precision) maskedNominal = nominal[trimmed]*mask fieldOverlap = trimmed & field.bounds if fieldOverlap.area() == 0: # this stamp's mask falls completely outside our field logger.info('*** line %d (id %d) does not overlap field' % (lineno,entryID)) continue field[fieldOverlap] += maskedNominal[fieldOverlap] # Remember the nominal stamp (clipped to the field) for overlap calculations. stampList.append(maskedNominal[fieldOverlap]) # Calculate this object's nominal flux S/N ratio at full depth using only masked pixels. # Note that this value cannot be reproduced from the saved stamp when a stamp is clipped # to the field boundary (use --no-clip to disable this). snr = signalToNoiseRatio(maskedNominal,args.exposure_time*skyRate) if args.verbose: logger.info(' S/N: %.6f' % snr) # Initialize the datacube of stamps that we will save for this object datacube = [ ] partialsArray = [ ] # Save the nominal (masked and trimmed) stamp assert saveStamp(datacube,maskedNominal,args) if args.partials: # Specify the amount to vary each parameter for partial derivatives # (we don't use a dictionary here since we want to control the order) variations = [ ('f_d',0.01), ('f_b',0.01), ('dx',args.pixel_scale/3.),('dy',args.pixel_scale/3.), ('relsize',0.05), ('g1',0.03), ('g2',0.03) ] # the shape measurement parameters must always be the last 2 variations # since we make this assumption when slicing the covariance matrix below assert variations[-2][0] == 'g1' assert variations[-1][0] == 'g2' # loop over source parameters to vary for (pname,delta) in variations: # create stamps for each variation of this parameter newparams = params.copy() partial = galsim.ImageD(bbox) partial.setScale(pix.getXWidth()) # delta might be zero, e.g., for hlr_b when bulge fraction = 0 if delta > 0: for step in range(args.partials_order): # create and save the positive variation stamp newparams[pname] = params[pname] + (step+1)*delta newsource = createSource(**newparams) plus = createStamp(newsource,psf,pix,bbox) # create and save the negative variation stamp newparams[pname] = params[pname] - (step+1)*delta newsource = createSource(**newparams) minus = createStamp(newsource,psf,pix,bbox) # update the finite difference calculation of this partial partial += (fdCoefs[step]/delta)*(plus - minus) # append this partial to our datacube after trimming and masking maskedPartial = partial[trimmed]*mask assert saveStamp(datacube,maskedPartial,args) # remember this partial's numpy image array partialsArray.append(maskedPartial[fieldOverlap].array) # calculate the Fisher matrix images for this object (note that we haven't # included the Fisher denominator here since that might include overlapping # objects that we have not seen yet) nvar = len(partialsArray) nfisher = ((nvar+1)*nvar)/2 (h,w) = partialsArray[0].shape fisherImage = numpy.zeros((nfisher,h,w)) index = 0 for i in range(nvar): for j in range(i,nvar): fisherImage[index] = partialsArray[i]*partialsArray[j] index += 1 fisherImagesList.append(fisherImage) # Add a new HDU with a datacube for this object's stamps # We don't use compression = 'gzip_tile' for now since it is lossy # and mathematica cannot Import it. galsim.fits.writeCube(datacube, hdu_list = hduList) # Add a catalog entry for this galaxy entry = [entryID,xoffset,yoffset,abMag,flux/args.exposure_time, sizeMinus,sizePlus,e1,e2,sizeMinusHSM,sizePlusHSM,e1HSM,e2HSM, bulgeFlux/(diskFlux+bulgeFlux),z,snr] outputCatalog.append(entry) nkeep += 1 logger.info("saved entry id %d as stamp %d" % (entryID,nkeep)) # Close the input catalog cat.close() # Loop over all saved objects to test for overlaps and build overlap groups (groupID,groupSize) = analyzeOverlaps(stampList) # Add group id to output catalog for (i,entry) in enumerate(outputCatalog): entry.append(groupID[i]) # Do shape measurement error analysis for each galaxy purities = (0,0.5,0.9,0.99) regionsList = [ ] for i in range(nkeep): # use all objects in Fisher denominator (isolated = False) (errors,regions) = shapeErrorsAnalysis( nvar,stampList[i],fisherImagesList[i],args.exposure_time*skyRate,field,purities,isolated=False) outputCatalog[i].extend(errors) # Save the regions for each object outname = args.output + '_regions.fits' logger.info('Saving regions to %r' % outname) galsim.fits.writeMulti(regionsList,outname) # Save group sizes to a file outname = args.output + '_groups.dat' out = open(outname,'w') ntot = 0 for (i,n) in enumerate(groupSize): if n > 0: print >>out,i,n ntot += n out.close() assert ntot == len(groupSize) # Write the full field image without noise if args.save_field: # First without noise outname = args.output + '_field.fits' logger.info('Saving full field to %r' % outname) galsim.fits.write(field,outname) # Write the full field image with random noise added if args.save_noise: rng = galsim.BaseDeviate(123) noise = galsim.PoissonNoise(rng,sky_level = args.exposure_time*skyRate) field.addNoise(noise) outname = args.output + '_noise.fits' logger.info('Saving full field with noise added to %r' % outname) galsim.fits.write(field,outname) # Write the object stamp datacubes if args.stamps: outname = args.output + '_stamps.fits' logger.info('Saving %d stamps to %r' % (nkeep,outname)) galsim.fits.writeFile(outname, hduList) # Write the output catalog from memory outname = args.output + '_catalog.dat' out = open(outname,'w') for entry in outputCatalog: print >>out, ' '.join(map(str,entry)) out.close() logger.info('Wrote %d of %d catalog entries to %r' % (nkeep,lineno,outname)) if __name__ == "__main__": main()
""" sender - SimplE Neuron DEleteR Deletes the least significant neurons. Outgoing value of neuron is defined as sum of absolute values of weights outgoing from neuron divided by sum of absolute values of weights outgoing from entire layer. Ingoing value of neuron is defined as sum of absolute values of weights ingoing from neuron divided by sum of absolute values of weights ingoing from entire layer. Neuron value is defined as multiplication of its ingoing and outgoing values. """ import numpy as np from athenet.layers import FullyConnectedLayer, ConvolutionalLayer, MaxPool from athenet.algorithm.utils import list_of_percentage_columns, \ list_of_percentage_rows, delete_column, delete_row def simple_neuron_deleter2(network, config): """ :network: - an instance of athenet.Network. :config: - tuple of 2 foats, p and layer_limit :p, layer_limit: - floats between 0 and 1. Modifies [network]. Deletes [p] neurons from layers connected direclty to fully connected layer's. Do not delete more than [layer_limit] neurons from single layer. If [layer_limit] < [p] then at most [layer_limit] neurons will be deleted. Deletion of neuron is simulated by setting all weights outgoing form to it and ingoing to it to 0. In athenet.network they are reprezented as rows of next layer's weights matrix. The algorithm supposes that there is no ConvolutionalLayer or MaxPool layer between any FullyConnectedLayers """ p, layer_limit = config assert p >= 0. and p <= 1. assert layer_limit >= 0. and layer_limit <= 1. if layer_limit < p: p = layer_limit # counter of neurons neurons_for_layer = np.zeros((len(network.layers))) neurons_in_general = 0 # counter of deleted neurons deleted_for_layer = np.zeros((len(network.layers))) deleted_in_general = 0 # weights is list of tuples (outgoing values of provious layer (rows), # ingoing values of this layer (columns)) # ingoing / outgoing value = (value, number of row / column, layer_id) weights = [] was_fully_connected_layer = False for i in xrange(len(network.layers)): layer = network.layers[i] if isinstance(layer, FullyConnectedLayer): was_fully_connected_layer = True weights.append((list_of_percentage_rows(i, layer), list_of_percentage_columns(i, layer))) neurons_for_layer[i] = layer.W.shape[1] neurons_in_general += neurons_for_layer[i] elif was_fully_connected_layer: assert not isinstance(layer, ConvolutionalLayer) assert not isinstance(layer, MaxPool) considered_neurons = [] for i in xrange(len(weights) - 1): for j in xrange(len(weights[i][1])): # neuron is reprezented as tuple #(value, number of column (and row), column_layer_id, row_layer_id) assert weights[i][1][j][1] == weights[i + 1][0][j][1] considered_neurons.append( (weights[i][1][j][0] * weights[i + 1][0][j][1], weights[i][1][j][1], weights[i][1][j][2], weights[i + 1][0][j][2]) ) considered_neurons = sorted(considered_neurons) for val, neuron_id, column_layer_id, row_layer_id in considered_neurons: if deleted_in_general >= p * neurons_in_general: break if deleted_for_layer[row_layer_id] + 1 > \ layer_limit * neurons_for_layer[row_layer_id]: continue delete_column(network.layers[column_layer_id], neuron_id) delete_row(network.layers[row_layer_id], neuron_id) deleted_for_layer[row_layer_id] += 1 deleted_in_general += 1 Remove bug from sender2 algorithm """ sender - SimplE Neuron DEleteR Deletes the least significant neurons. Outgoing value of neuron is defined as sum of absolute values of weights outgoing from neuron divided by sum of absolute values of weights outgoing from entire layer. Ingoing value of neuron is defined as sum of absolute values of weights ingoing from neuron divided by sum of absolute values of weights ingoing from entire layer. Neuron value is defined as multiplication of its ingoing and outgoing values. """ import numpy as np from athenet.layers import FullyConnectedLayer, ConvolutionalLayer, MaxPool from athenet.algorithm.utils import list_of_percentage_columns, \ list_of_percentage_rows, delete_column, delete_row def simple_neuron_deleter2(network, config): """ :network: - an instance of athenet.Network. :config: - tuple of 2 foats, p and layer_limit :p, layer_limit: - floats between 0 and 1. Modifies [network]. Deletes [p] neurons from layers connected direclty to fully connected layer's. Do not delete more than [layer_limit] neurons from single layer. If [layer_limit] < [p] then at most [layer_limit] neurons will be deleted. Deletion of neuron is simulated by setting all weights outgoing form to it and ingoing to it to 0. In athenet.network they are reprezented as rows of next layer's weights matrix. The algorithm supposes that there is no ConvolutionalLayer or MaxPool layer between any FullyConnectedLayers """ p, layer_limit = config assert p >= 0. and p <= 1. assert layer_limit >= 0. and layer_limit <= 1. if layer_limit < p: p = layer_limit # counter of neurons neurons_for_layer = np.zeros((len(network.layers))) neurons_in_general = 0 # counter of deleted neurons deleted_for_layer = np.zeros((len(network.layers))) deleted_in_general = 0 # weights is list of tuples (outgoing values of provious layer (rows), # ingoing values of this layer (columns)) # ingoing / outgoing value = (value, number of row / column, layer_id) weights = [] was_fully_connected_layer = False for i in xrange(len(network.layers)): layer = network.layers[i] if isinstance(layer, FullyConnectedLayer): was_fully_connected_layer = True weights.append((list_of_percentage_rows(i, layer), list_of_percentage_columns(i, layer))) neurons_for_layer[i] = layer.W.shape[1] neurons_in_general += neurons_for_layer[i] elif was_fully_connected_layer: assert not isinstance(layer, ConvolutionalLayer) assert not isinstance(layer, MaxPool) considered_neurons = [] for i in xrange(len(weights) - 1): for j in xrange(len(weights[i][1])): # neuron is reprezented as tuple #(value, number of column (and row), column_layer_id, row_layer_id) assert weights[i][1][j][1] == weights[i + 1][0][j][1] considered_neurons.append( (weights[i][1][j][0] * weights[i + 1][0][j][0], weights[i][1][j][1], weights[i][1][j][2], weights[i + 1][0][j][2]) ) considered_neurons = sorted(considered_neurons) for val, neuron_id, column_layer_id, row_layer_id in considered_neurons: if deleted_in_general >= p * neurons_in_general: break if deleted_for_layer[row_layer_id] + 1 > \ layer_limit * neurons_for_layer[row_layer_id]: continue delete_column(network.layers[column_layer_id], neuron_id) delete_row(network.layers[row_layer_id], neuron_id) deleted_for_layer[row_layer_id] += 1 deleted_in_general += 1
# # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import itertools import logging import pickle import numpy as np import ray from zoo.orca.data.shard import RayXShards from zoo.orca.learn.tf2.tf_runner import TFRunner from zoo.orca.learn.ray_estimator import Estimator as OrcaRayEstimator from zoo.orca.learn.utils import maybe_dataframe_to_xshards, dataframe_to_xshards, \ convert_predict_rdd_to_dataframe, convert_predict_xshards_to_dataframe, update_predict_xshards from zoo.ray import RayContext logger = logging.getLogger(__name__) class Estimator(object): @staticmethod def from_keras(*, model_creator, config=None, verbose=False, workers_per_node=1, compile_args_creator=None, backend="tf2" ): return TensorFlow2Estimator(model_creator=model_creator, config=config, verbose=verbose, workers_per_node=workers_per_node, backend=backend, compile_args_creator=compile_args_creator) def shards_ref_to_creator(shards_ref): def data_creator(config): return shards_ref return data_creator def data_length(data): x = data["x"] if isinstance(x, np.ndarray): return x.shape[0] else: return x[0].shape[0] def process_spark_xshards(spark_xshards, num_workers): data = spark_xshards if data.num_partitions() != num_workers: data = data.repartition(num_workers) # todo currently we need this information to pad the short partitions # so that every model run exactly the same number of steps in one epoch max_length = data.rdd.map(data_length) \ .mapPartitions(lambda iterator: [sum(iterator)]).max() ray_xshards = RayXShards.from_spark_xshards(data) return max_length, ray_xshards class TensorFlow2Estimator(OrcaRayEstimator): def __init__(self, model_creator, compile_args_creator=None, config=None, verbose=False, backend="tf2", workers_per_node=1): """Sets up the TensorFlow trainer. Args: model_creator (dict -> Model): This function takes in the `config` dict and returns a compiled TF model. data_creator (dict -> tf.Dataset, tf.Dataset): Creates the training and validation data sets using the config. `config` dict is passed into the function. config (dict): configuration passed to 'model_creator', 'data_creator'. Also contains `fit_config`, which is passed into `model.fit(data, **fit_config)` and `evaluate_config` which is passed into `model.evaluate`. num_replicas (int): Sets number of workers used in distributed training. Workers will be placed arbitrarily across the cluster. use_gpu (bool): Enables all workers to use GPU. verbose (bool): Prints output of one model if true. """ self.model_creator = model_creator self.compile_args_creator = compile_args_creator self.config = {} if config is None else config self.verbose = verbose ray_ctx = RayContext.get() if "inter_op_parallelism" not in self.config: self.config["inter_op_parallelism"] = 1 if "intra_op_parallelism" not in self.config: self.config["intra_op_parallelism"] = ray_ctx.ray_node_cpu_cores // workers_per_node if backend == "horovod": assert compile_args_creator is not None, "compile_args_creator should not be None," \ " when backend is set to horovod" params = { "model_creator": model_creator, "compile_args_creator": compile_args_creator, "config": self.config, "verbose": self.verbose, } if backend == "tf2": cores_per_node = ray_ctx.ray_node_cpu_cores // workers_per_node num_nodes = ray_ctx.num_ray_nodes * workers_per_node worker_class = ray.remote(num_cpus=cores_per_node)(TFRunner) self.remote_workers = [worker_class.remote(**params) for i in range(0, num_nodes)] ips = ray.get( [worker.get_node_ip.remote() for worker in self.remote_workers]) ports = ray.get( [worker.find_free_port.remote() for worker in self.remote_workers]) urls = ["{ip}:{port}".format(ip=ips[i], port=ports[i]) for i in range(len(self.remote_workers))] # Get setup tasks in order to throw errors on failure ray.get([ worker.setup_distributed.remote(urls, i, len(self.remote_workers)) for i, worker in enumerate(self.remote_workers)]) elif backend == "horovod": # it is necessary to call self.run first to set horovod environment from zoo.orca.learn.horovod.horovod_ray_runner import HorovodRayRunner horovod_runner = HorovodRayRunner(ray_ctx, worker_cls=TFRunner, worker_param=params, workers_per_node=workers_per_node) horovod_runner.run(lambda: print("worker initialized")) self.remote_workers = horovod_runner.remote_workers ray.get([ worker.setup_horovod.remote() for i, worker in enumerate(self.remote_workers)]) else: raise Exception("Only \"tf2\" and \"horovod\" are legal " "values of backend, but got {}".format(backend)) self.num_workers = len(self.remote_workers) def fit(self, data, epochs=1, batch_size=32, verbose=1, callbacks=None, validation_data=None, class_weight=None, steps_per_epoch=None, validation_steps=None, validation_freq=1, data_config=None, feature_cols=None, label_cols=None): """Runs a training epoch.""" params = dict( epochs=epochs, batch_size=batch_size, verbose=verbose, callbacks=callbacks, class_weight=class_weight, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps, validation_freq=validation_freq, data_config=data_config ) from zoo.orca.data import SparkXShards data, validation_data = maybe_dataframe_to_xshards(data, validation_data, feature_cols, label_cols, mode="fit") if isinstance(data, SparkXShards): max_length, ray_xshards = process_spark_xshards(data, self.num_workers) if validation_data is None: def transform_func(worker, shards_ref): params["data_creator"] = shards_ref_to_creator(shards_ref) return worker.step.remote(**params) stats_shards = ray_xshards.transform_shards_with_actors(self.remote_workers, transform_func, gang_scheduling=True) else: val_max_length, val_ray_xshards = process_spark_xshards(validation_data, self.num_workers) def zip_func(worker, this_shards_ref, that_shards_ref): params["data_creator"] = shards_ref_to_creator(this_shards_ref) params["validation_data_creator"] =\ shards_ref_to_creator(that_shards_ref) return worker.step.remote(**params) stats_shards = ray_xshards.zip_shards_with_actors(val_ray_xshards, self.remote_workers, zip_func, gang_scheduling=True) worker_stats = stats_shards.collect() else: params["data_creator"] = data params["validation_data_creator"] = validation_data params_list = [params] * self.num_workers worker_stats = ray.get([self.remote_workers[i].step.remote(**params_list[i]) for i in range(self.num_workers)]) worker_stats = list(itertools.chain.from_iterable(worker_stats)) stats = worker_stats[0].copy() return stats def evaluate(self, data, batch_size=32, num_steps=None, verbose=1, sample_weight=None, callbacks=None, data_config=None, feature_cols=None, label_cols=None): """Evaluates the model on the validation data set.""" logger.info("Starting validation step.") params = dict( batch_size=batch_size, verbose=verbose, sample_weight=sample_weight, steps=num_steps, callbacks=callbacks, data_config=data_config, ) from zoo.orca.data import SparkXShards data, _ = maybe_dataframe_to_xshards(data, validation_data=None, feature_cols=feature_cols, label_cols=label_cols, mode="evaluate") if isinstance(data, SparkXShards): data = data if data.num_partitions() != self.num_workers: data = data.repartition(self.num_workers) ray_xshards = RayXShards.from_spark_xshards(data) def transform_func(worker, shards_ref): params["data_creator"] = shards_ref_to_creator(shards_ref) return worker.validate.remote(**params) stats_shards = ray_xshards.transform_shards_with_actors(self.remote_workers, transform_func, gang_scheduling=True) worker_stats = stats_shards.collect() else: # data_creator functions; should return Iter or DataLoader params["data_creator"] = data params_list = [params] * self.num_workers worker_stats = ray.get([w.validate.remote(**params_list[i]) for i, w in enumerate(self.remote_workers)]) worker_stats = list(itertools.chain.from_iterable(worker_stats)) stats = worker_stats[0].copy() return stats def _predict_spark_xshards(self, xshards, params): ray_xshards = RayXShards.from_spark_xshards(xshards) def transform_func(worker, shards_ref): params["data_creator"] = shards_ref_to_creator(shards_ref) return worker.predict.remote(**params) pred_shards = ray_xshards.transform_shards_with_actors(self.remote_workers, transform_func, gang_scheduling=False) spark_xshards = pred_shards.to_spark_xshards() return spark_xshards def predict(self, data, batch_size=None, verbose=1, steps=None, callbacks=None, data_config=None, feature_cols=None): """Evaluates the model on the validation data set.""" logger.info("Starting predict step.") params = dict( verbose=verbose, batch_size=batch_size, steps=steps, callbacks=callbacks, data_config=data_config, ) from zoo.orca.data import SparkXShards from pyspark.sql import DataFrame if isinstance(data, DataFrame): xshards, _ = dataframe_to_xshards(data, validation_data=None, feature_cols=feature_cols, label_cols=None, mode="predict") pred_shards = self._predict_spark_xshards(xshards, params) result = convert_predict_xshards_to_dataframe(data, pred_shards) elif isinstance(data, SparkXShards): pred_shards = self._predict_spark_xshards(data, params) result = update_predict_xshards(data, pred_shards) else: raise ValueError("Only xshards or Spark DataFrame is supported for predict") return result def get_model(self): """Returns the learned model.""" state = ray.get(self.remote_workers[0].get_state.remote()) return self._get_model_from_state(state) def save(self, checkpoint): """Saves the model at the provided checkpoint. Args: checkpoint (str): Path to target checkpoint file. """ # Some model might need to aggregate variables during checkpointing # which requires both the chief and workers to participate in the # allreduce communication protocol. # So we need to call get_state on every remote workers, otherwise # it might get stuck state_refs = [w.get_state.remote() for w in self.remote_workers] state = ray.get(state_refs[0]) with open(checkpoint, "wb") as f: pickle.dump(state, f) return checkpoint def load(self, checkpoint, **kwargs): """Restores the model from the provided checkpoint. Args: checkpoint (str): Path to target checkpoint file. """ with open(checkpoint, "rb") as f: state = pickle.load(f) state_id = ray.put(state) ray.get([worker.set_state.remote(state_id) for worker in self.remote_workers]) def shutdown(self): """Shuts down workers and releases resources.""" for worker in self.remote_workers: worker.shutdown.remote() worker.__ray_terminate__.remote() def _get_model_from_state(self, state): """Creates model and load weights from state""" model = self.model_creator(self.config) model.set_weights(state["weights"]) # This part is due to ray.get() changing scalar np.int64 object to int state["optimizer_weights"][0] = np.array( state["optimizer_weights"][0], dtype=np.int64) if model.optimizer.weights == []: model._make_train_function() model.optimizer.set_weights(state["optimizer_weights"]) return model Avoid workers' waiting and fix _get_model_from_state (#3418) * fix docs * fix * fix * get_model * rm optimizer weight * typo # # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import itertools import logging import pickle import numpy as np import ray from zoo.orca.data.shard import RayXShards from zoo.orca.learn.tf2.tf_runner import TFRunner from zoo.orca.learn.ray_estimator import Estimator as OrcaRayEstimator from zoo.orca.learn.utils import maybe_dataframe_to_xshards, dataframe_to_xshards, \ convert_predict_rdd_to_dataframe, convert_predict_xshards_to_dataframe, update_predict_xshards from zoo.ray import RayContext logger = logging.getLogger(__name__) class Estimator(object): @staticmethod def from_keras(*, model_creator, config=None, verbose=False, workers_per_node=1, compile_args_creator=None, backend="tf2" ): return TensorFlow2Estimator(model_creator=model_creator, config=config, verbose=verbose, workers_per_node=workers_per_node, backend=backend, compile_args_creator=compile_args_creator) def shards_ref_to_creator(shards_ref): def data_creator(config): return shards_ref return data_creator def data_length(data): x = data["x"] if isinstance(x, np.ndarray): return x.shape[0] else: return x[0].shape[0] def process_spark_xshards(spark_xshards, num_workers): data = spark_xshards if data.num_partitions() != num_workers: data = data.repartition(num_workers) # todo currently we need this information to pad the short partitions # so that every model run exactly the same number of steps in one epoch max_length = data.rdd.map(data_length) \ .mapPartitions(lambda iterator: [sum(iterator)]).max() ray_xshards = RayXShards.from_spark_xshards(data) return max_length, ray_xshards class TensorFlow2Estimator(OrcaRayEstimator): def __init__(self, model_creator, compile_args_creator=None, config=None, verbose=False, backend="tf2", workers_per_node=1): """Sets up the TensorFlow trainer. Args: model_creator (dict -> Model): This function takes in the `config` dict and returns a compiled TF model. data_creator (dict -> tf.Dataset, tf.Dataset): Creates the training and validation data sets using the config. `config` dict is passed into the function. config (dict): configuration passed to 'model_creator', 'data_creator'. Also contains `fit_config`, which is passed into `model.fit(data, **fit_config)` and `evaluate_config` which is passed into `model.evaluate`. num_replicas (int): Sets number of workers used in distributed training. Workers will be placed arbitrarily across the cluster. use_gpu (bool): Enables all workers to use GPU. verbose (bool): Prints output of one model if true. """ self.model_creator = model_creator self.compile_args_creator = compile_args_creator self.config = {} if config is None else config self.verbose = verbose ray_ctx = RayContext.get() if "inter_op_parallelism" not in self.config: self.config["inter_op_parallelism"] = 1 if "intra_op_parallelism" not in self.config: self.config["intra_op_parallelism"] = ray_ctx.ray_node_cpu_cores // workers_per_node if backend == "horovod": assert compile_args_creator is not None, "compile_args_creator should not be None," \ " when backend is set to horovod" params = { "model_creator": model_creator, "compile_args_creator": compile_args_creator, "config": self.config, "verbose": self.verbose, } if backend == "tf2": cores_per_node = ray_ctx.ray_node_cpu_cores // workers_per_node num_nodes = ray_ctx.num_ray_nodes * workers_per_node worker_class = ray.remote(num_cpus=cores_per_node)(TFRunner) self.remote_workers = [worker_class.remote(**params) for i in range(0, num_nodes)] ips = ray.get( [worker.get_node_ip.remote() for worker in self.remote_workers]) ports = ray.get( [worker.find_free_port.remote() for worker in self.remote_workers]) urls = ["{ip}:{port}".format(ip=ips[i], port=ports[i]) for i in range(len(self.remote_workers))] # Get setup tasks in order to throw errors on failure ray.get([ worker.setup_distributed.remote(urls, i, len(self.remote_workers)) for i, worker in enumerate(self.remote_workers)]) elif backend == "horovod": # it is necessary to call self.run first to set horovod environment from zoo.orca.learn.horovod.horovod_ray_runner import HorovodRayRunner horovod_runner = HorovodRayRunner(ray_ctx, worker_cls=TFRunner, worker_param=params, workers_per_node=workers_per_node) horovod_runner.run(lambda: print("worker initialized")) self.remote_workers = horovod_runner.remote_workers ray.get([ worker.setup_horovod.remote() for i, worker in enumerate(self.remote_workers)]) else: raise Exception("Only \"tf2\" and \"horovod\" are legal " "values of backend, but got {}".format(backend)) self.num_workers = len(self.remote_workers) def fit(self, data, epochs=1, batch_size=32, verbose=1, callbacks=None, validation_data=None, class_weight=None, steps_per_epoch=None, validation_steps=None, validation_freq=1, data_config=None, feature_cols=None, label_cols=None): """Runs a training epoch.""" params = dict( epochs=epochs, batch_size=batch_size, verbose=verbose, callbacks=callbacks, class_weight=class_weight, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps, validation_freq=validation_freq, data_config=data_config ) from zoo.orca.data import SparkXShards data, validation_data = maybe_dataframe_to_xshards(data, validation_data, feature_cols, label_cols, mode="fit") if isinstance(data, SparkXShards): max_length, ray_xshards = process_spark_xshards(data, self.num_workers) if validation_data is None: def transform_func(worker, shards_ref): params["data_creator"] = shards_ref_to_creator(shards_ref) return worker.step.remote(**params) stats_shards = ray_xshards.transform_shards_with_actors(self.remote_workers, transform_func, gang_scheduling=True) else: val_max_length, val_ray_xshards = process_spark_xshards(validation_data, self.num_workers) def zip_func(worker, this_shards_ref, that_shards_ref): params["data_creator"] = shards_ref_to_creator(this_shards_ref) params["validation_data_creator"] = \ shards_ref_to_creator(that_shards_ref) return worker.step.remote(**params) stats_shards = ray_xshards.zip_shards_with_actors(val_ray_xshards, self.remote_workers, zip_func, gang_scheduling=True) worker_stats = stats_shards.collect() else: params["data_creator"] = data params["validation_data_creator"] = validation_data params_list = [params] * self.num_workers worker_stats = ray.get([self.remote_workers[i].step.remote(**params_list[i]) for i in range(self.num_workers)]) worker_stats = list(itertools.chain.from_iterable(worker_stats)) stats = worker_stats[0].copy() return stats def evaluate(self, data, batch_size=32, num_steps=None, verbose=1, sample_weight=None, callbacks=None, data_config=None, feature_cols=None, label_cols=None): """Evaluates the model on the validation data set.""" logger.info("Starting validation step.") params = dict( batch_size=batch_size, verbose=verbose, sample_weight=sample_weight, steps=num_steps, callbacks=callbacks, data_config=data_config, ) from zoo.orca.data import SparkXShards data, _ = maybe_dataframe_to_xshards(data, validation_data=None, feature_cols=feature_cols, label_cols=label_cols, mode="evaluate") if isinstance(data, SparkXShards): data = data if data.num_partitions() != self.num_workers: data = data.repartition(self.num_workers) ray_xshards = RayXShards.from_spark_xshards(data) def transform_func(worker, shards_ref): params["data_creator"] = shards_ref_to_creator(shards_ref) return worker.validate.remote(**params) stats_shards = ray_xshards.transform_shards_with_actors(self.remote_workers, transform_func, gang_scheduling=True) worker_stats = stats_shards.collect() else: # data_creator functions; should return Iter or DataLoader params["data_creator"] = data params_list = [params] * self.num_workers worker_stats = ray.get([w.validate.remote(**params_list[i]) for i, w in enumerate(self.remote_workers)]) worker_stats = list(itertools.chain.from_iterable(worker_stats)) stats = worker_stats[0].copy() return stats def _predict_spark_xshards(self, xshards, params): ray_xshards = RayXShards.from_spark_xshards(xshards) def transform_func(worker, shards_ref): params["data_creator"] = shards_ref_to_creator(shards_ref) return worker.predict.remote(**params) pred_shards = ray_xshards.transform_shards_with_actors(self.remote_workers, transform_func, gang_scheduling=False) spark_xshards = pred_shards.to_spark_xshards() return spark_xshards def predict(self, data, batch_size=None, verbose=1, steps=None, callbacks=None, data_config=None, feature_cols=None): """Evaluates the model on the validation data set.""" logger.info("Starting predict step.") params = dict( verbose=verbose, batch_size=batch_size, steps=steps, callbacks=callbacks, data_config=data_config, ) from zoo.orca.data import SparkXShards from pyspark.sql import DataFrame if isinstance(data, DataFrame): xshards, _ = dataframe_to_xshards(data, validation_data=None, feature_cols=feature_cols, label_cols=None, mode="predict") pred_shards = self._predict_spark_xshards(xshards, params) result = convert_predict_xshards_to_dataframe(data, pred_shards) elif isinstance(data, SparkXShards): pred_shards = self._predict_spark_xshards(data, params) result = update_predict_xshards(data, pred_shards) else: raise ValueError("Only xshards or Spark DataFrame is supported for predict") return result def get_model(self): """Returns the learned model.""" state_refs = [w.get_state.remote() for w in self.remote_workers] state = ray.get(state_refs[0]) return self._get_model_from_state(state) def save(self, checkpoint): """Saves the model at the provided checkpoint. Args: checkpoint (str): Path to target checkpoint file. """ # Some model might need to aggregate variables during checkpointing # which requires both the chief and workers to participate in the # allreduce communication protocol. # So we need to call get_state on every remote workers, otherwise # it might get stuck state_refs = [w.get_state.remote() for w in self.remote_workers] state = ray.get(state_refs[0]) with open(checkpoint, "wb") as f: pickle.dump(state, f) return checkpoint def load(self, checkpoint, **kwargs): """Restores the model from the provided checkpoint. Args: checkpoint (str): Path to target checkpoint file. """ with open(checkpoint, "rb") as f: state = pickle.load(f) state_id = ray.put(state) ray.get([worker.set_state.remote(state_id) for worker in self.remote_workers]) def shutdown(self): """Shuts down workers and releases resources.""" for worker in self.remote_workers: worker.shutdown.remote() worker.__ray_terminate__.remote() def _get_model_from_state(self, state): """Creates model and load weights from state""" # keep the same behavior as `set_state` in `load` do model = self.model_creator(self.config) model.set_weights(state["weights"]) return model
#!/usr/bin/env python import os import pprint import json import time import logging import atexit from libsubmit.providers.provider_base import ExecutionProvider from libsubmit.error import * try : import boto3 from botocore.exceptions import ClientError except ImportError: _boto_enabled = False else: _boto_enabled = True AWS_REGIONS = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2'] DEFAULT_REGION = 'us-east-2' translate_table = {'PD': 'PENDING', 'R': 'RUNNING', 'CA': 'CANCELLED', 'CF': 'PENDING', # (configuring), 'CG': 'RUNNING', # (completing), 'CD': 'COMPLETED', 'F': 'FAILED', # (failed), 'TO': 'TIMEOUT', # (timeout), 'NF': 'FAILED', # (node failure), 'RV': 'FAILED', # (revoked) and 'SE': 'FAILED'} # (special exit state template_string = """ cd ~ sudo apt-get update -y sudo apt-get update -y sudo apt-get install -y python3 sudo apt-get install -y python3-pip sudo apt-get install -y ipython sudo pip3 install ipyparallel sudo pip3 install parsl pip3 install numpy pip3 install scipy """ class EC2Provider(ExecutionProvider): def __init__(self, config): if not _boto_enabled : raise OptionalModuleMissing(['boto3'], "AWS Provider requires boto3 module.") """Initialize provider""" self.config = self.read_configs(config) self.set_instance_vars() self.config_logger() try: self.read_state_file() except Exception as e: self.create_vpc().id self.logger.info( "No State File. Cannot load previous options. Creating new infrastructure\n") self.write_state_file() @property def channels_required(self): return False def set_instance_vars(self): """Initialize instance variables""" self.current_blocksize = 0 self.sitename = self.config['site'] self.session = self.create_session(self.config) self.client = self.session.client('ec2') self.ec2 = self.session.resource('ec2') self.instances = [] self.instance_states = {} self.vpc_id = 0 self.sg_id = 0 self.sn_ids = [] def config_logger(self): """Configure Logger""" logger = logging.getLogger("EC2Provider") logger.setLevel(logging.INFO) if not os.path.isfile('awsprovider.log'): with open('awsprovider.log', 'w') as temp_log: temp_log.write("Creating new log file.\n") fh = logging.FileHandler('awsprovider.log') fh.setLevel(logging.INFO) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.CRITICAL) # create formatter and add it to the handlers formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) fh.setFormatter(formatter) # add the handlers to logger logger.addHandler(ch) logger.addHandler(fh) self.logger = logger def read_state_file(self): """If this script has been run previously, it will be persisitent by writing resource ids to state file. On run, the script looks for a state file before creating new infrastructure""" try: fh = open('awsproviderstate.json', 'r') state = json.load(fh) self.vpc_id = state['vpcID'] self.sg_id = state['sgID'] self.sn_ids = state['snIDs'] self.instances = state['instances'] except Exception as e: raise e def write_state_file(self): fh = open('awsproviderstate.json', 'w') state = {} state['vpcID'] = self.vpc_id state['sgID'] = self.sg_id state['snIDs'] = self.sn_ids state['instances'] = self.instances state["instanceState"] = self.instance_states fh.write(json.dumps(state, indent=4)) def _read_conf(self, config_file): """read config file""" config = json.load(open(config_file, 'r')) return config def pretty_configs(self, configs): """prettyprint config""" printer = pprint.PrettyPrinter(indent=4) printer.pprint(configs) def read_configs(self, config_file): """Read config file""" config = self._read_conf(config_file) return config def create_session(self, config={}): """Create boto3 session. If config contains ec2credentialsfile, it will use that file, if not, it will check for a ~/.aws/credentials file and use that. If not found, it will look for environment variables containing aws auth information. If none of those options work, it will let boto attempt to figure out who you are. if that fails, we cannot proceed""" if 'ec2credentialsfile' in config: config['ec2credentialsfile'] = os.path.expanduser( config['ec2credentialsfile']) config['ec2credentialsfile'] = os.path.expandvars( config['ec2credentialsfile']) cred_lines = open(config['ec2credentialsfile']).readlines() cred_details = cred_lines[1].split(',') credentials = {'AWS_Username': cred_lines[0], 'AWSAccessKeyId': cred_lines[1].split(' = ')[1], 'AWSSecretKey': cred_lines[2].split(' = ')[1]} config.update(credentials) session = boto3.session.Session(aws_access_key_id=credentials['AWSAccessKeyId'], aws_secret_access_key=credentials['AWSSecretKey'],) return session elif os.path.isfile(os.path.expanduser('~/.aws/credentials')): cred_lines = open(os.path.expanduser( '~/.aws/credentials')).readlines() credentials = {'AWS_Username': cred_lines[0], 'AWSAccessKeyId': cred_lines[1].split(' = ')[1], 'AWSSecretKey': cred_lines[2].split(' = ')[1]} config.update(credentials) session = boto3.session.Session() return session elif (os.getenv("AWS_ACCESS_KEY_ID") is not None and os.getenv("AWS_SECRET_ACCESS_KEY") is not None): session = boto3.session.Session(aws_access_key_id=credentials['AWSAccessKeyId'], aws_secret_access_key=credentials['AWSSecretKey'],) return session else: try: session = boto3.session.Session() return session except Exception as e: self.logger.error("Credentials not found. Cannot Continue") exit(-1) def create_vpc(self): """Create and configure VPC""" try: vpc = self.ec2.create_vpc( CidrBlock='10.0.0.0/16', AmazonProvidedIpv6CidrBlock=False, ) except Exception as e: self.logger.error("{}\n".format(e)) internet_gateway = self.ec2.create_internet_gateway() internet_gateway.attach_to_vpc(VpcId=vpc.vpc_id) # Returns None self.internet_gateway = internet_gateway.id route_table = self.config_route_table(vpc, internet_gateway) self.route_table = route_table.id availability_zones = self.client.describe_availability_zones() for num, zone in enumerate(availability_zones['AvailabilityZones']): if zone['State'] == "available": subnet = vpc.create_subnet( CidrBlock='10.0.{}.0/20'.format(16 * num), AvailabilityZone=zone['ZoneName']) subnet.meta.client.modify_subnet_attribute( SubnetId=subnet.id, MapPublicIpOnLaunch={"Value": True}) route_table.associate_with_subnet(SubnetId=subnet.id) self.sn_ids.append(subnet.id) else: print("{} unavailable".format(zone['ZoneName'])) # Security groups sg = self.security_group(vpc) self.vpc_id = vpc.id return vpc def security_group(self, vpc): """Create and configure security group. Allows all ICMP in, all tcp and udp in within vpc """ sg = vpc.create_security_group( GroupName="private-subnet", Description="security group for remote executors") ip_ranges = [{ 'CidrIp': '172.32.0.0/16' }] # Allows all ICMP in, all tcp and udp in within vpc inPerms = [{ 'IpProtocol': 'TCP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': ip_ranges, }, { 'IpProtocol': 'UDP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': ip_ranges, }, { 'IpProtocol': 'ICMP', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], }] # Allows all TCP out, all tcp and udp out within vpc outPerms = [{ 'IpProtocol': 'TCP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], }, { 'IpProtocol': 'TCP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': ip_ranges, }, { 'IpProtocol': 'UDP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': ip_ranges, }, ] sg.authorize_ingress(IpPermissions=inPerms) sg.authorize_egress(IpPermissions=outPerms) self.sg_id = sg.id return sg def config_route_table(self, vpc, internet_gateway): """Configure route table for vpc""" route_table = vpc.create_route_table() route_ig_ipv4 = route_table.create_route( DestinationCidrBlock='0.0.0.0/0', GatewayId=internet_gateway.internet_gateway_id) return route_table def scale_out(self, size, cmd_string=None): """Scale cluster out (larger)""" instances = [] for i in range(size * self.config['nodeGranularity']): instances.append(self.spin_up_instance(cmd_string=cmd_string)) self.current_blocksize += size * self.config['nodeGranularity'] self.logger.info( "started {} instances".format( size * self.config['nodeGranularity'])) return instances def scale_in(self, size): """Scale cluster in (smaller)""" for i in range(size * self.config['nodeGranularity']): self.shut_down_instance() self.current_blocksize -= size * self.config['nodeGranularity'] def xstr(self, s): return '' if s is None else s def spin_up_instance(self, cmd_string): """Starts an instance in the vpc in first available subnet. Starts up n instances at a time where n is node granularity from config""" escaped_command = self.xstr(cmd_string) command = "#!/bin/bash\nsed -i 's/us-east-2\.ec2\.//g' /etc/apt/sources.list\n" + \ template_string + \ "\n{}\n{}".format( self.ipyparallel_configuration(), escaped_command) instance_type = self.config['instancetype'] subnet = self.sn_ids[0] ami_id = self.config['AMIID'] total_instances = len(self.instances) + self.config['nodeGranularity'] if total_instances > self.config['maxNodes']: warning = "You have requested more instances ({}) than your maxNodes ({}). Cannot Continue\n".format( total_instances, self.config['maxNodes']) self.logger.warn(warning) return -1 instance = self.ec2.create_instances( InstanceType=instance_type, ImageId=ami_id, MinCount=1, MaxCount=self.config['nodeGranularity'], KeyName=self.config['AWSKeyName'], SubnetId=subnet, SecurityGroupIds=[self.sg_id], UserData=command) self.instances.append(instance[0].id) self.logger.info( "Started up 1 instance. Instance type:{}".format(instance_type)) return instance def shut_down_instance(self, instances=None): """Shuts down a list of instances if provided or the last instance started up if none provided""" if instances and len(self.instances > 0): term = self.client.terminate_instances(InstanceIds=instances) self.logger.info( "Shut down {} instances (ids:{}".format( len(instances), str(instances))) elif len(self.instances) > 0: instance = self.instances.pop() term = self.client.terminate_instances(InstanceIds=[instance]) self.logger.info("Shut down 1 instance (id:{})".format(instance)) else: self.logger.warn("No Instances to shut down.\n") return -1 self.get_instance_state() return term def get_instance_state(self, instances=None): """Get stateus of all instances on EC2 which were started by this file""" if instances: desc = self.client.describe_instances(InstanceIds=instances) else: desc = self.client.describe_instances(InstanceIds=self.instances) # pprint.pprint(desc['Reservations'],indent=4) for i in range(len(desc['Reservations'])): instance = desc['Reservations'][i]['Instances'][0] self.instance_states[instance['InstanceId'] ] = instance['State']['Name'] return self.instance_states def ipyparallel_configuration(self): config = '' try: with open(os.path.expanduser(self.config['iPyParallelConfigFile'])) as f: config = f.read().strip() except Exception as e: self.logger.error(e) self.logger.info( "Couldn't find user ipyparallel config file. Trying default location.") with open(os.path.expanduser("~/.ipython/profile_default/security/ipcontroller-engine.json")) as f: config = f.read().strip() else: self.logger.error( "Cannot find iPyParallel config file. Cannot proceed.") return -1 ipptemplate = """ cat <<EOF > ipengine.json {} EOF mkdir -p '.ipengine_logs' sleep 5 ipengine --file=ipengine.json &> ipengine.log & ipengine --file=ipengine.json &> ipengine.log &""".format(config) return ipptemplate ####################################################### # Status ####################################################### def status(self, job_ids): ''' Get the status of a list of jobs identified by their ids. Args: - job_ids (List of ids) : List of identifiers for the jobs Returns: - List of status codes. ''' return self.get_instance_state() ######################################################## # Submit ######################################################## def submit(self, cmd_string='sleep 1', blocksize=1, job_name="parsl.auto"): """Submit an ipyparalel pilot job which will connect to an ipp controller specified by your ipp config file and run cmd_string on the instance being started up.""" return self.scale_out(cmd_string=cmd_string, size=blocksize) ######################################################## # Cancel ######################################################## def cancel(self, job_ids): ''' Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. ''' return self.shut_down_instance(instances=job_ids) def show_summary(self): """Print human readable summary of current AWS state to log and to console""" self.get_instance_state() status_string = "EC2 Summary:\n\tVPC IDs: {}\n\tSubnet IDs: \ {}\n\tSecurity Group ID: {}\n\tRunning Instance IDs: {}\n".format( self.vpc_id, self.sn_ids, self.sg_id, self.instances) status_string += "\tInstance States:\n\t\t" self.get_instance_state() for state in self.instance_states.keys(): status_string += "Instance ID: {} State: {}\n\t\t".format( state, self.instance_states[state]) status_string += "\n" self.logger.info(status_string) return status_string def teardown(self): """Terminate all EC2 instances, delete all subnets, delete security group, delete vpc and reset all instance variables """ self.shut_down_instance(self.instances) self.instances = [] try: self.client.delete_internet_gateway( InternetGatewayId=self.internet_gateway) self.internet_gateway = None self.client.delete_route_table(RouteTableId=self.route_table) self.route_table = None for subnet in list(self.sn_ids): # Cast to list ensures that this is a copy # Which is important because it means that # the length of the list won't change during iteration self.client.delete_subnet(SubnetId=subnet) self.sn_ids.remove(subnet) self.client.delete_security_group(GroupId=self.sg_id) self.sg_id = None self.client.delete_vpc(VpcId=self.vpc_id) self.vpc_id = None except Exception as e: self.logger.error( "{}".format(e)) raise e self.show_summary() os.remove(self.config['stateFilePath']) def scaling_enabled(): return True # @atexit.register # def goodbye(): # self.teardown() if __name__ == '__main__': conf = "providerconf.json" provider = EC2Provider(conf) provider.submit("sleep 5") print(provider.show_summary()) # provider.scale_in(1) print(provider.show_summary()) Several fixes and interface cleanups import os import pprint import math import json import time import logging import atexit from string import Template from libsubmit.providers.provider_base import ExecutionProvider from libsubmit.launchers import Launchers from libsubmit.error import * from libsubmit.providers.aws.template import template_string logger = logging.getLogger(__name__) try : import boto3 from botocore.exceptions import ClientError except ImportError: _boto_enabled = False else: _boto_enabled = True AWS_REGIONS = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2'] DEFAULT_REGION = 'us-east-2' translate_table = {'PD': 'PENDING', 'R': 'RUNNING', 'CA': 'CANCELLED', 'CF': 'PENDING', # (configuring), 'CG': 'RUNNING', # (completing), 'CD': 'COMPLETED', 'F': 'FAILED', # (failed), 'TO': 'TIMEOUT', # (timeout), 'NF': 'FAILED', # (node failure), 'RV': 'FAILED', # (revoked) and 'SE': 'FAILED'} # (special exit state class EC2Provider(ExecutionProvider): ''' Here's a sample config for the EC2 provider: .. code-block:: python { "execution" : { # Definition of all execution aspects of a site "executor" : #{Description: Define the executor used as task executor, # Type : String, # Expected : "ipp", # Required : True}, "provider" : #{Description : The provider name, in this case ec2 # Type : String, # Expected : "slurm", # Required : True }, "script_dir" : #{Description : Relative or absolute path to a # directory in which intermediate scripts are placed # Type : String, # Default : "./.scripts"}, "block" : { # Definition of a block "nodes" : #{Description : # of nodes to provision per block # Type : Integer, # Default: 1}, "taskBlocks" : #{Description : # of workers to launch per block # as either an number or as a bash expression. # for eg, "1" , "$(($CORES / 2))" # Type : String, # Default: "1" }, "walltime" : #{Description : Walltime requested per block in HH:MM:SS # Type : String, # Default : "00:20:00" }, "initBlocks" : #{Description : # of blocks to provision at the start of # the DFK # Type : Integer # Default : ? # Required : }, "minBlocks" : #{Description : Minimum # of blocks outstanding at any time # WARNING :: Not Implemented # Type : Integer # Default : 0 }, "maxBlocks" : #{Description : Maximum # Of blocks outstanding at any time # WARNING :: Not Implemented # Type : Integer # Default : ? }, "options" : { # Scheduler specific options "instanceType" : #{Description : Instance type t2.small|t2... # Type : String, # Required : False # Default : t2.small }, "imageId" : #{"Description : String to append to the #SBATCH blocks # in the submit script to the scheduler # Type : String, # Required : False }, } } } } ''' def __repr__ (self): return "<EC2 Execution Provider for site:{0}>".format(self.sitename) def __init__(self, config, channel=None): ''' Initialize the EC2Provider class Args: - Config (dict): Dictionary with all the config options. KWargs: - Channel (None): A channel is not required for EC2. ''' self.channel = channel if not _boto_enabled : raise OptionalModuleMissing(['boto3'], "AWS Provider requires boto3 module.") self.config = config self.sitename = config['site'] self.current_blocksize = 0 self.resources = {} self.config = config options = self.config["execution"]["block"]["options"] logger.warn("Options %s", options) self.instance_type = options.get("instanceType", "t2.small") self.image_id = options["imageId"] self.key_name = options["keyName"] self.max_nodes = (self.config["execution"]["block"].get("maxBlocks",1)* self.config["execution"]["block"].get("nodes", 1)) try: self.initialize_boto_client() except Exception as e: logger.error("Site:[{0}] Failed to initialize".format(self)) raise e try: self.statefile = self.config["execution"]["block"]["options"].get("stateFile", '.ec2site_{0}.json'.format(self.sitename)) self.read_state_file(self.statefile) except Exception as e: self.create_vpc().id logger.info("No State File. Cannot load previous options. Creating new infrastructure") self.write_state_file() @property def channels_required(self): return False def initialize_boto_client(self): ''' Use auth configs to initialize the boto client ''' self.sitename = self.config['site'] self.session = self.create_session() self.client = self.session.client('ec2') self.ec2 = self.session.resource('ec2') self.instances = [] self.instance_states = {} self.vpc_id = 0 self.sg_id = 0 self.sn_ids = [] def read_state_file(self, statefile): """If this script has been run previously, it will be persisitent by writing resource ids to state file. On run, the script looks for a state file before creating new infrastructure""" try: fh = open(statefile, 'r') state = json.load(fh) self.vpc_id = state['vpcID'] self.sg_id = state['sgID'] self.sn_ids = state['snIDs'] self.instances = state['instances'] except Exception as e: logger.debug("Caught exception while reading state file: {0}".format(e)) raise e logger.debug("Done reading state from the local state file") def write_state_file(self): fh = open('awsproviderstate.json', 'w') state = {} state['vpcID'] = self.vpc_id state['sgID'] = self.sg_id state['snIDs'] = self.sn_ids state['instances'] = self.instances state["instanceState"] = self.instance_states fh.write(json.dumps(state, indent=4)) def _read_conf(self, config_file): """read config file""" config = json.load(open(config_file, 'r')) return config def pretty_configs(self, configs): """prettyprint config""" printer = pprint.PrettyPrinter(indent=4) printer.pprint(configs) def read_configs(self, config_file): """Read config file""" config = self._read_conf(config_file) return config def create_session(self): ''' Here we will first look in the ~/.aws/config file. First we look in config["auth"]["keyfile"] for a path to a json file with the credentials. the keyfile should have 'AWSAccessKeyId' and 'AWSSecretKey' Next we look for config["auth"]["profile"] for a profile name and try to use the Session call to auto pick up the keys for the profile from the user default keys file ~/.aws/config. Lastly boto3 will look for the keys in env variables: AWS_ACCESS_KEY_ID : The access key for your AWS account. AWS_SECRET_ACCESS_KEY : The secret key for your AWS account. AWS_SESSION_TOKEN : The session key for your AWS account. This is only needed when you are using temporary credentials. The AWS_SECURITY_TOKEN environment variable can also be used, but is only supported for backwards compatibility purposes. AWS_SESSION_TOKEN is supported by multiple AWS SDKs besides python. ''' session = None region = self.config["execution"]["block"]["options"].get("region", DEFAULT_REGION) if "keyfile" in self.config["auth"]: c = self.config["auth"]["keyfile"] credfile = os.path.expandvars(os.path.expanduser(c)) try: with open(credfile, 'r') as f: creds = json.load(credfile) except json.JSONDecodeError as e: logger.error("Site[{0}]: Json decode error in credential file {1}".format( self, credfile)) raise e except Exception as e: logger.debug("Caught exception: {0} while reading credential file: {1}".format(self, credfile)) raise e logger.debug("Site[{0}]: Using credential file to create session".format(self)) session = boto3.session.Session(**creds, region_name=region) elif "profile" in self.config["auth"]: logger.debug("Site[{0}]: Using profile name to create session".format(self)) session = boto3.session.Session(profile_name=self.config["auth"]["profile"], region_name=region) elif (os.getenv("AWS_ACCESS_KEY_ID") is not None and os.getenv("AWS_SECRET_ACCESS_KEY") is not None): logger.debug("Site[{0}]: Using env variables to create session".format(self)) session = boto3.session.Session(region_name=region) else: logger.error("Site[{0}]: Credentials not available to create session".format(self)) session = boto3.session.Session(region_name=region) print(session) return session def create_vpc(self): """Create and configure VPC""" try: vpc = self.ec2.create_vpc( CidrBlock='10.0.0.0/16', AmazonProvidedIpv6CidrBlock=False, ) except Exception as e: logger.error("{}\n".format(e)) raise e internet_gateway = self.ec2.create_internet_gateway() internet_gateway.attach_to_vpc(VpcId=vpc.vpc_id) # Returns None self.internet_gateway = internet_gateway.id route_table = self.config_route_table(vpc, internet_gateway) self.route_table = route_table.id availability_zones = self.client.describe_availability_zones() for num, zone in enumerate(availability_zones['AvailabilityZones']): if zone['State'] == "available": subnet = vpc.create_subnet( CidrBlock='10.0.{}.0/20'.format(16 * num), AvailabilityZone=zone['ZoneName']) subnet.meta.client.modify_subnet_attribute( SubnetId=subnet.id, MapPublicIpOnLaunch={"Value": True}) route_table.associate_with_subnet(SubnetId=subnet.id) self.sn_ids.append(subnet.id) else: print("{} unavailable".format(zone['ZoneName'])) # Security groups sg = self.security_group(vpc) self.vpc_id = vpc.id return vpc def security_group(self, vpc): """Create and configure security group. Allows all ICMP in, all tcp and udp in within vpc """ sg = vpc.create_security_group( GroupName="private-subnet", Description="security group for remote executors") ip_ranges = [{ 'CidrIp': '172.32.0.0/16' }] # Allows all ICMP in, all tcp and udp in within vpc inPerms = [{ 'IpProtocol': 'TCP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': ip_ranges, }, { 'IpProtocol': 'UDP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': ip_ranges, }, { 'IpProtocol': 'ICMP', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], }] # Allows all TCP out, all tcp and udp out within vpc outPerms = [{ 'IpProtocol': 'TCP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], }, { 'IpProtocol': 'TCP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': ip_ranges, }, { 'IpProtocol': 'UDP', 'FromPort': 0, 'ToPort': 65535, 'IpRanges': ip_ranges, }, ] sg.authorize_ingress(IpPermissions=inPerms) sg.authorize_egress(IpPermissions=outPerms) self.sg_id = sg.id return sg def config_route_table(self, vpc, internet_gateway): """Configure route table for vpc""" route_table = vpc.create_route_table() route_ig_ipv4 = route_table.create_route( DestinationCidrBlock='0.0.0.0/0', GatewayId=internet_gateway.internet_gateway_id) return route_table def scale_out(self, size, cmd_string=None): """Scale cluster out (larger)""" job_name = "parsl.auto.{0}".format(time.time()) instances = [] for i in range(size): instances.append(self.spin_up_instance(cmd_string=cmd_string, job_name=job_name)) self.current_blocksize += size logger.info("started {} instances".format(size)) return instances def scale_in(self, size): """Scale cluster in (smaller)""" for i in range(size): self.shut_down_instance() self.current_blocksize -= size def xstr(self, s): return '' if s is None else s def spin_up_instance(self, cmd_string, job_name): ''' Starts an instance in the vpc in first available subnet. Starts up n instances if nodes per block > 1 Not supported. We only do 1 node per block Args: - cmd_string (str) : Command string to execute on the node - job_name (str) : Name associated with the instances ''' escaped_command = self.xstr(cmd_string) command = Template(template_string).substitute(jobname=job_name, user_script=cmd_string) instance_type = self.instance_type subnet = self.sn_ids[0] ami_id = self.image_id total_instances = len(self.instances) if total_instances > self.max_nodes: logger.warn("You have requested more instances ({}) than your max_nodes ({}). Cannot Continue\n".format(total_instances, self.max_nodes)) return -1 instance = self.ec2.create_instances( InstanceType=instance_type, ImageId=ami_id, MinCount=1, MaxCount=1, KeyName=self.key_name, SubnetId=subnet, SecurityGroupIds=[self.sg_id], TagSpecifications = [{"ResourceType" : "instance", "Tags" : [{'Key' : 'Name', 'Value' : job_name }]} ], UserData=command) self.instances.append(instance[0].id) logger.info( "Started up 1 instance. Instance type:{}".format(instance_type)) return instance def shut_down_instance(self, instances=None): """Shuts down a list of instances if provided or the last instance started up if none provided""" if instances and len(self.instances) > 0: term = self.client.terminate_instances(InstanceIds=instances) logger.info( "Shut down {} instances (ids:{}".format( len(instances), str(instances))) elif len(self.instances) > 0: instance = self.instances.pop() term = self.client.terminate_instances(InstanceIds=[instance]) logger.info("Shut down 1 instance (id:{})".format(instance)) else: logger.warn("No Instances to shut down.\n") return -1 self.get_instance_state() return term def get_instance_state(self, instances=None): """Get stateus of all instances on EC2 which were started by this file""" if instances: desc = self.client.describe_instances(InstanceIds=instances) else: desc = self.client.describe_instances(InstanceIds=self.instances) # pprint.pprint(desc['Reservations'],indent=4) for i in range(len(desc['Reservations'])): instance = desc['Reservations'][i]['Instances'][0] self.instance_states[instance['InstanceId'] ] = instance['State']['Name'] return self.instance_states def ipyparallel_configuration(self): config = '' try: with open(os.path.expanduser(self.config['iPyParallelConfigFile'])) as f: config = f.read().strip() except Exception as e: logger.error(e) logger.info( "Couldn't find user ipyparallel config file. Trying default location.") with open(os.path.expanduser("~/.ipython/profile_default/security/ipcontroller-engine.json")) as f: config = f.read().strip() else: logger.error( "Cannot find iPyParallel config file. Cannot proceed.") return -1 ipptemplate = """ cat <<EOF > ipengine.json {} EOF mkdir -p '.ipengine_logs' sleep 5 ipengine --file=ipengine.json &> ipengine.log & ipengine --file=ipengine.json &> ipengine.log &""".format(config) return ipptemplate ####################################################### # Status ####################################################### def status(self, job_ids): ''' Get the status of a list of jobs identified by their ids. Args: - job_ids (List of ids) : List of identifiers for the jobs Returns: - List of status codes. ''' return self.get_instance_state() ######################################################## # Submit ######################################################## def submit(self, cmd_string='sleep 1', blocksize=1, job_name="parsl.auto"): """Submit an ipyparalel pilot job which will connect to an ipp controller specified by your ipp config file and run cmd_string on the instance being started up.""" return self.scale_out(cmd_string=cmd_string, size=blocksize) ######################################################## # Cancel ######################################################## def cancel(self, job_ids): ''' Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. ''' return self.shut_down_instance(instances=job_ids) def show_summary(self): """Print human readable summary of current AWS state to log and to console""" self.get_instance_state() status_string = "EC2 Summary:\n\tVPC IDs: {}\n\tSubnet IDs: \ {}\n\tSecurity Group ID: {}\n\tRunning Instance IDs: {}\n".format( self.vpc_id, self.sn_ids, self.sg_id, self.instances) status_string += "\tInstance States:\n\t\t" self.get_instance_state() for state in self.instance_states.keys(): status_string += "Instance ID: {} State: {}\n\t\t".format( state, self.instance_states[state]) status_string += "\n" logger.info(status_string) return status_string def teardown(self): """Terminate all EC2 instances, delete all subnets, delete security group, delete vpc and reset all instance variables """ self.shut_down_instance(self.instances) self.instances = [] try: self.client.delete_internet_gateway( InternetGatewayId=self.internet_gateway) self.internet_gateway = None self.client.delete_route_table(RouteTableId=self.route_table) self.route_table = None for subnet in list(self.sn_ids): # Cast to list ensures that this is a copy # Which is important because it means that # the length of the list won't change during iteration self.client.delete_subnet(SubnetId=subnet) self.sn_ids.remove(subnet) self.client.delete_security_group(GroupId=self.sg_id) self.sg_id = None self.client.delete_vpc(VpcId=self.vpc_id) self.vpc_id = None except Exception as e: logger.error("{}".format(e)) raise e self.show_summary() os.remove(self.config['stateFilePath']) def scaling_enabled(): return True # @atexit.register # def goodbye(): # self.teardown() if __name__ == '__main__': conf = "providerconf.json" provider = EC2Provider(conf) provider.submit("sleep 5") print(provider.show_summary()) # provider.scale_in(1) print(provider.show_summary())
from .. import syntax from . import util from schemata import validators as val class Schema(dict): """ Makes a Schema object from a schema dict. Still acts like a dict. #NeverGrowUp """ def __init__(self, schema_dict, name=''): schema = util.flatten(schema_dict) dict.__init__(self, schema) self._process_schema(self) self.dict = schema_dict self.name = name self.includes = {} def add_include(self, type_dict): for include_name, custom_type in type_dict.items(): t = Schema(custom_type, name=include_name) self.includes[include_name] = t def _process_schema(self, schema): ''' Warning: this method mutates input. Go through a schema and construct validators. ''' for key, expression in schema.items(): try: schema[key] = syntax.parse(expression) except SyntaxError, e: # Tack on some more context and rethrow. raise SyntaxError(e.message + ' at node \'%s\'' % key) def validate(self, data): errors = [] for key, validator in self.items(): errors += self._validate(validator, data, key=key, includes=self.includes) if errors: header = '\nError validating data %s with schema %s' % (data.name, self.name) error_str = '\n\t' + '\n\t'.join(errors) raise ValueError(header + error_str) def _validate(self, validator, data, key, position=None, includes=None): ''' Run through a schema and a data structure, validating along the way. Ignores fields that are in the data structure, but not in the schema. Returns an array of errors. ''' errors = [] if position: position = '%s.%s' % (position, key) else: position = key try: # Pull value out of data. Data can be a map or a list/sequence data_item = data[key] except KeyError: # Oops, that field didn't exist. if validator.is_optional: # Optional? Who cares. return errors # SHUT DOWN EVERTYHING errors.append('%s: Required field missing' % position) return errors errors += self._validate_primitive(validator, data_item, position) if errors: return errors if isinstance(validator, val.Include): errors += self._validate_include(validator, data_item, includes, position) elif isinstance(validator, val.List): errors += self._validate_list(validator, data_item, includes, position) return errors def _validate_list(self, validator, data, includes, pos): errors = [] if not validator.validators: return errors # No validators, user just wanted a list. for key in range(len(data)): sub_errors = [] for v in validator.validators: err = self._validate(v, data, key, pos, includes) if err: sub_errors.append(err) if len(sub_errors) == len(validator.validators): # All validators failed, add to errors for err in sub_errors: errors += err return errors def _validate_include(self, validator, data, includes, pos): errors = [] include_schema = includes.get(validator.include_name) if not include_schema: errors.append('Include \'%s\' has not been defined.' % validator.include_name) return errors for key, validator in include_schema.items(): errors += include_schema._validate(validator, data, includes=includes, key=key, position=pos) return errors def _validate_primitive(self, validator, data, pos): errors = validator.validate(data) for i, error in enumerate(errors): errors[i] = '%s: ' % pos + error return errors Update schema.py from .. import syntax from . import util from schemata import validators as val class Schema(dict): """ Makes a Schema object from a schema dict. Still acts like a dict. """ def __init__(self, schema_dict, name=''): schema = util.flatten(schema_dict) dict.__init__(self, schema) self._process_schema(self) self.dict = schema_dict self.name = name self.includes = {} def add_include(self, type_dict): for include_name, custom_type in type_dict.items(): t = Schema(custom_type, name=include_name) self.includes[include_name] = t def _process_schema(self, schema): ''' Warning: this method mutates input. Go through a schema and construct validators. ''' for key, expression in schema.items(): try: schema[key] = syntax.parse(expression) except SyntaxError, e: # Tack on some more context and rethrow. raise SyntaxError(e.message + ' at node \'%s\'' % key) def validate(self, data): errors = [] for key, validator in self.items(): errors += self._validate(validator, data, key=key, includes=self.includes) if errors: header = '\nError validating data %s with schema %s' % (data.name, self.name) error_str = '\n\t' + '\n\t'.join(errors) raise ValueError(header + error_str) def _validate(self, validator, data, key, position=None, includes=None): ''' Run through a schema and a data structure, validating along the way. Ignores fields that are in the data structure, but not in the schema. Returns an array of errors. ''' errors = [] if position: position = '%s.%s' % (position, key) else: position = key try: # Pull value out of data. Data can be a map or a list/sequence data_item = data[key] except KeyError: # Oops, that field didn't exist. if validator.is_optional: # Optional? Who cares. return errors # SHUT DOWN EVERTYHING errors.append('%s: Required field missing' % position) return errors errors += self._validate_primitive(validator, data_item, position) if errors: return errors if isinstance(validator, val.Include): errors += self._validate_include(validator, data_item, includes, position) elif isinstance(validator, val.List): errors += self._validate_list(validator, data_item, includes, position) return errors def _validate_list(self, validator, data, includes, pos): errors = [] if not validator.validators: return errors # No validators, user just wanted a list. for key in range(len(data)): sub_errors = [] for v in validator.validators: err = self._validate(v, data, key, pos, includes) if err: sub_errors.append(err) if len(sub_errors) == len(validator.validators): # All validators failed, add to errors for err in sub_errors: errors += err return errors def _validate_include(self, validator, data, includes, pos): errors = [] include_schema = includes.get(validator.include_name) if not include_schema: errors.append('Include \'%s\' has not been defined.' % validator.include_name) return errors for key, validator in include_schema.items(): errors += include_schema._validate(validator, data, includes=includes, key=key, position=pos) return errors def _validate_primitive(self, validator, data, pos): errors = validator.validate(data) for i, error in enumerate(errors): errors[i] = '%s: ' % pos + error return errors
#!/usr/bin/python #============================================================================================= # MODULE DOCSTRING #============================================================================================= """ Test examples. """ #============================================================================================= # GLOBAL IMPORTS #============================================================================================= import os, os.path import subprocess from openmmtools import testsystems from nose.plugins.skip import Skip, SkipTest #============================================================================================= # UNIT TESTS #============================================================================================= def run_example(path, example): # Change to example directory. cwd = os.getcwd() os.chdir(os.path.join(path, example)) # Execute one iteration of the example. import subprocess returncode = subprocess.call('NITERATIONS=5 ./run.sh', shell=True, executable='/bin/bash') # Restore working directory. os.chdir(cwd) if returncode: raise Exception('Example %s returned exit code %d' % (example, returncode)) return def get_immediate_subdirectories(path): return [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name)) and os.path.exists(os.path.join(path, name, 'run.sh'))] def test_examples(): # Get example path. from pkg_resources import resource_filename path = resource_filename('yank', '../examples') # Get list of examples. directories = get_immediate_subdirectories(path) # Test examples for directory in directories: run_example(path, directory) Reduced number of iterations used in tests of examples. #!/usr/bin/python #============================================================================================= # MODULE DOCSTRING #============================================================================================= """ Test examples. """ #============================================================================================= # GLOBAL IMPORTS #============================================================================================= import os, os.path import subprocess from openmmtools import testsystems from nose.plugins.skip import Skip, SkipTest #============================================================================================= # UNIT TESTS #============================================================================================= def run_example(path, example): # Change to example directory. cwd = os.getcwd() os.chdir(os.path.join(path, example)) # Execute one iteration of the example. import subprocess returncode = subprocess.call('NITERATIONS=1 ./run.sh', shell=True, executable='/bin/bash') # Restore working directory. os.chdir(cwd) if returncode: raise Exception('Example %s returned exit code %d' % (example, returncode)) return def get_immediate_subdirectories(path): return [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name)) and os.path.exists(os.path.join(path, name, 'run.sh'))] def test_examples(): # Get example path. from pkg_resources import resource_filename path = resource_filename('yank', '../examples') # Get list of examples. directories = get_immediate_subdirectories(path) # Test examples for directory in directories: run_example(path, directory)
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3.0 from sqlalchemy import * from iatidq import db from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash ## TEST RUNTIME-SPECIFIC DATA class PackageStatus(db.Model): __tablename__ = 'packagestatus' id = Column(Integer, primary_key=True) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) status = Column(Integer, nullable=False) runtime_datetime = Column(DateTime) def __init__(self): self.runtime_datetime = datetime.utcnow() def __repr__(self): return unicode(self.runtime_datetime)+u' '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class Runtime(db.Model): __tablename__ = 'runtime' id = Column(Integer, primary_key=True) runtime_datetime = Column(DateTime, nullable=False) def __init__(self): self.runtime_datetime = datetime.utcnow() def __repr__(self): return unicode(self.runtime_datetime)+u' '+unicode(self.id) ## IATI REGISTRY PACKAGEGROUPS AND PACKAGES class PackageGroup(db.Model): __tablename__ = 'packagegroup' id = Column(Integer, primary_key=True) man_auto = Column(UnicodeText) name = Column(UnicodeText, nullable=False) ckan_id = Column(UnicodeText) revision_id = Column(UnicodeText) title = Column(UnicodeText) created_date = Column(UnicodeText) state = Column(UnicodeText) publisher_iati_id = Column(UnicodeText) publisher_segmentation = Column(UnicodeText) publisher_type = Column(UnicodeText) publisher_ui = Column(UnicodeText) publisher_organization_type = Column(UnicodeText) publisher_frequency = Column(UnicodeText) publisher_thresholds = Column(UnicodeText) publisher_units = Column(UnicodeText) publisher_contact = Column(UnicodeText) publisher_agencies = Column(UnicodeText) publisher_field_exclusions = Column(UnicodeText) publisher_description = Column(UnicodeText) publisher_record_exclusions = Column(UnicodeText) publisher_timeliness = Column(UnicodeText) license_id = Column(UnicodeText) publisher_country = Column(UnicodeText) publisher_refs = Column(UnicodeText) publisher_constraints = Column(UnicodeText) publisher_data_quality = Column(UnicodeText) __table_args__ = (UniqueConstraint('name',),) def __init__(self, man_auto=None, name=None): if man_auto is not None: self.man_auto = man_auto if name is not None: self.name = name def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class Package(db.Model): __tablename__ = 'package' id = Column(Integer, primary_key=True) man_auto = Column(UnicodeText) source_url = Column(UnicodeText) package_ckan_id = Column(UnicodeText) package_name = Column(UnicodeText, nullable=False) package_title = Column(UnicodeText) package_license_id = Column(UnicodeText) package_license = Column(UnicodeText) package_metadata_created = Column(UnicodeText) package_metadata_modified = Column(UnicodeText) package_group = Column(Integer, ForeignKey('packagegroup.id')) package_activity_from = Column(UnicodeText) package_activity_to = Column(UnicodeText) package_activity_count = Column(UnicodeText) package_country = Column(UnicodeText) package_archive_file = Column(UnicodeText) package_verified = Column(UnicodeText) package_filetype = Column(UnicodeText) package_revision_id = Column(UnicodeText) active = Column(Boolean) hash = Column(UnicodeText) deleted = Column(Boolean, default=False) __table_args__ = (UniqueConstraint('package_name'),) def __init__(self, man_auto=None, source_url=None): if man_auto is not None: self.man_auto = man_auto if source_url is not None: self.source_url = source_url def __repr__(self): source_url = self.source_url or "None" return source_url+u", "+str(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## RESULTS class Result(db.Model): __tablename__ = 'result' id = Column(Integer, primary_key=True) runtime_id = Column(Integer, ForeignKey('runtime.id'), nullable=False) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) organisation_id = Column(Integer, ForeignKey('organisation.id')) test_id = Column(Integer, ForeignKey('test.id'), nullable=False) result_data = Column(Integer, nullable=False) result_identifier = Column(UnicodeText) result_hierarchy = Column(Integer) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} db.Index('result_runpack', Result.runtime_id, Result.package_id, Result.result_identifier) db.Index('result_test', Result.test_id) # there should be a uniqueness constraint, roughly: # # alter table aggregateresult add unique ( # package_id, test_id, result_hierarchy, aggregateresulttype_id, # organisation_id # ); # # but after normalisation the package/organisation thing should go away class AggregateResult(db.Model): __tablename__='aggregateresult' id = Column(Integer,primary_key=True) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) organisation_id = Column(Integer, ForeignKey('organisation.id')) aggregateresulttype_id = Column(Integer, ForeignKey('aggregationtype.id'), nullable=False) test_id = Column(Integer, ForeignKey('test.id'), nullable=False) result_hierarchy = Column(Integer) results_data = Column(Float) results_num = Column(Integer) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} # AggregationType allows for different aggregations # Particularly used for looking only at current data class AggregationType(db.Model): __tablename__ = 'aggregationtype' id = Column(Integer,primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) test_id = Column(Integer, ForeignKey('test.id')) test_result = Column(Integer, nullable=False) active = Column(Integer) def setup(self, name, description, test_id, test_result, active, id=None): self.name = name self.description = description self.test_id = test_id self.test_result = test_result self.active = active if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## TESTS class Test(db.Model): __tablename__ = 'test' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText, nullable=False) test_group = Column(UnicodeText) file = Column(UnicodeText) line = Column(Integer) test_level = Column(Integer, nullable=False) active = Column(Boolean) def setup(self, name, description, test_group, test_level, active, id=None): self.name = name self.description = description self.test_group = test_group self.test_level = test_level self.active = active if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## CODELISTS class Codelist(db.Model): __tablename__ = 'codelist' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) source = Column(UnicodeText) def setup(self, name, description, id=None): self.name = name self.description = description if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class CodelistCode(db.Model): __tablename__ = 'codelistcode' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) code = Column(UnicodeText, nullable=False) codelist_id = Column(Integer, ForeignKey('codelist.id'), nullable=False) source = Column(UnicodeText) def setup(self, name, code, codelist_id, id=None): self.name = name self.code = code self.codelist_id = codelist_id if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## INDICATORS class IndicatorGroup(db.Model): __tablename__ = 'indicatorgroup' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) def setup(self, name, description, id=None): self.name = name self.description = description if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class Indicator(db.Model): __tablename__ = 'indicator' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) longdescription = Column(UnicodeText) indicatorgroup_id = Column(Integer, ForeignKey('indicatorgroup.id'), nullable=False) indicator_type = Column(UnicodeText) indicator_category_name = Column(UnicodeText) indicator_subcategory_name = Column(UnicodeText) indicator_ordinal = Column(Boolean) indicator_noformat = Column(Boolean) indicator_order = Column(Integer, nullable=False) indicator_weight = Column(Float(precision=4)) def setup(self, name, description, longdescription, indicatorgroup_id, indicator_type, indicator_category_name, indicator_subcategory_name, indicator_ordinal=None, indicator_noformat=None, indicator_order=None, indicator_weight=None, id=None): self.name = name self.description = description self.longdescription = longdescription self.indicatorgroup_id = indicatorgroup_id self.indicator_type = indicator_type self.indicator_category_name = indicator_category_name self.indicator_subcategory_name = indicator_subcategory_name self.indicator_ordinal = indicator_ordinal self.indicator_noformat = indicator_noformat self.indicator_order = indicator_order self.indicator_weight = indicator_weight if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class IndicatorTest(db.Model): __tablename__ = 'indicatortest' id = Column(Integer, primary_key=True) indicator_id = Column(Integer, ForeignKey('indicator.id'), nullable=False) test_id = Column(Integer, ForeignKey('test.id'), nullable=False) __table_args__ = (UniqueConstraint('indicator_id', 'test_id'), ) def setup(self, indicator_id, test_id, id=None): self.indicator_id = indicator_id self.test_id = test_id if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class IndicatorInfoType(db.Model): __tablename__ = 'indicatorinfotype' id = Column(Integer, primary_key=True) indicator_id = Column(Integer, ForeignKey('indicator.id'), nullable=False) infotype_id = Column(Integer, ForeignKey('info_type.id'), nullable=False) def setup(self, indicator_id, infotype_id, id=None): self.indicator_id = indicator_id self.infotype_id = infotype_id if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class OrganisationCondition(db.Model): __tablename__ = 'organisationcondition' id = Column(Integer, primary_key=True) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) test_id = Column(Integer, ForeignKey('test.id'), nullable=False) operation = Column(Integer) # show (1) or don't show (0) result condition = Column(UnicodeText) # activity level, hierarchy 2 condition_value = Column(UnicodeText) # True, 2, etc. description = Column(UnicodeText) file = Column(UnicodeText) line = Column(Integer) active = Column(Boolean) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class OrganisationConditionFeedback(db.Model): __tablename__ ='organisationconditionfeedback' id = Column(Integer, primary_key=True) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) uses = Column(UnicodeText) element = Column(UnicodeText) where = Column(UnicodeText) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} # Migration """ alter table organisationconditionfeedback alter column organisation_id type integer USING (organisation_id::integer); alter table organisationconditionfeedback add constraint ofbkorg FOREIGN KEY (organisation_id) REFERENCES organisation (id) MATCH FULL; """ ## ORGANISATIONS; RELATIONS WITH PACKAGES class Organisation(db.Model): __tablename__ = 'organisation' id = Column(Integer, primary_key=True) organisation_name = Column(UnicodeText, nullable=False) organisation_code = Column(UnicodeText, nullable=False) organisation_total_spend = Column(Float(precision=2)) organisation_total_spend_source = Column(UnicodeText) organisation_currency = Column(UnicodeText) organisation_currency_conversion = Column(Float(precision=4)) organisation_currency_conversion_source = Column(UnicodeText) organisation_largest_recipient = Column(UnicodeText) organisation_largest_recipient_source = Column(UnicodeText) frequency = Column(UnicodeText) frequency_comment = Column(UnicodeText) no_independent_reviewer=Column(Boolean) organisation_responded=Column(Integer) __table_args__ = (UniqueConstraint('organisation_name'), UniqueConstraint('organisation_code')) # organisation_code is also used to communicate # with implementation schedules def setup(self, organisation_name, organisation_code, organisation_total_spend=None, organisation_total_spend_source=None, organisation_currency=None, organisation_currency_conversion=None, organisation_currency_conversion_source=None, organisation_largest_recipient=None, organisation_largest_recipient_source=None, id=None): self.organisation_name = organisation_name self.organisation_code = organisation_code self.organisation_total_spend = organisation_total_spend, self.organisation_currency = organisation_currency, self.organisation_currency_conversion = organisation_currency_conversion, self.organisation_currency_conversion_source = organisation_currency_conversion_source, self.organisation_largest_recipient = organisation_largest_recipient if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class OrganisationPackage(db.Model): __tablename__ = 'organisationpackage' id = Column(Integer, primary_key=True) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) condition = Column(UnicodeText) __table_args__ = (UniqueConstraint('organisation_id', 'package_id', name='_organisation_package_uc'), ) def setup(self, organisation_id, package_id, condition=None, id=None): self.organisation_id = organisation_id self.package_id = package_id self.condition = condition if id is not None: self.id = id class OrganisationPackageGroup(db.Model): __tablename__ = 'organisationpackagegroup' id = Column(Integer, primary_key=True) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) packagegroup_id = Column(Integer, ForeignKey('packagegroup.id'), nullable=False) condition = Column(UnicodeText) __table_args__ = (UniqueConstraint('organisation_id', 'packagegroup_id'),) def setup(self, organisation_id, packagegroup_id, condition=None, id=None): self.organisation_id = organisation_id self.packagegroup_id = packagegroup_id self.condition = condition if id is not None: self.id = id ## INFORESULTS # TODO: IMPLEMENT # ==> total amount of disbursements in this package # e.g. 1 = total disbursements class InfoResult(db.Model): __tablename__ = 'info_result' id = Column(Integer, primary_key=True) runtime_id = Column(Integer, ForeignKey('runtime.id'), nullable=False) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) info_id = Column(Integer, ForeignKey('info_type.id'), nullable=False) organisation_id = Column(Integer, ForeignKey('organisation.id')) result_data = Column(Float) class InfoType(db.Model): __tablename__ = 'info_type' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) level = Column(Integer, nullable=False) def setup(self, name, level, description=None, id=None): self.name = name self.level = level self.description = description if id is not None: self.id = id ## USERS class User(db.Model): __tablename__ = 'dquser' id = Column(Integer, primary_key=True) username = Column(UnicodeText, nullable=False) name = Column(UnicodeText) email_address = Column(UnicodeText) reset_password_key = Column(UnicodeText) pw_hash = db.Column(String(255)) organisation = Column(UnicodeText) children = db.relationship("UserPermission", cascade="all, delete-orphan", passive_deletes=True) __table_args__ = (UniqueConstraint('username',),) def setup(self, username, password, name, email_address=None, organisation=None, id=None): self.username = username self.pw_hash = generate_password_hash(password) self.name = name self.email_address = email_address self.organisation = organisation if id is not None: self.id = id def check_password(self, password): return check_password_hash(self.pw_hash, password) def is_active(self): return True def get_id(self): return self.id def is_anonymous(self): return False def is_authenticated(self): return True class UserPermission(db.Model): __tablename__ = 'userpermission' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('dquser.id', ondelete='CASCADE')) permission_name = Column(UnicodeText) # survey_donorreview permission_method = Column(UnicodeText) # edit permission_value = Column(UnicodeText) # 1 def setup(self, user_id, permission_name, permission_method=None, permission_value=None, id=None): self.user_id = user_id self.permission_name = permission_name self.permission_method = permission_method self.permission_value = permission_value if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## ORGANISATION SURVEYS class OrganisationSurvey(db.Model): __tablename__ = 'organisationsurvey' id = Column(Integer,primary_key=True) currentworkflow_id = Column(Integer, ForeignKey('workflow.id'), nullable=False) currentworkflow_deadline = Column(DateTime) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) __table_args__ = (UniqueConstraint('organisation_id',),) def setup(self, organisation_id, currentworkflow_id, currentworkflow_deadline=None, id=None): self.organisation_id = organisation_id self.currentworkflow_id = currentworkflow_id self.currentworkflow_deadline = currentworkflow_deadline if id is not None: self.id = id class OrganisationSurveyData(db.Model): __tablename__ = 'organisationsurveydata' id = Column(Integer,primary_key=True) organisationsurvey_id = Column(Integer, ForeignKey('organisationsurvey.id'), nullable=False) indicator_id = Column(Integer, ForeignKey('indicator.id'), nullable=False) workflow_id = Column(Integer, ForeignKey('workflow.id'), nullable=False) published_status = Column(Integer, ForeignKey('publishedstatus.id')) published_source = Column(UnicodeText) published_comment = Column(UnicodeText) published_format = Column(Integer, ForeignKey('publishedformat.id')) published_accepted = Column(Integer) ordinal_value = Column(Float(precision=2)) __table_args__ = (UniqueConstraint('organisationsurvey_id', 'indicator_id', 'workflow_id'),) def setup(self, organisationsurvey_id, indicator_id, workflow_id=None, published_status=None, published_source=None, published_comment=None, published_format=None, published_accepted=None, ordinal_value=None, id=None): self.organisationsurvey_id = organisationsurvey_id self.workflow_id = workflow_id self.indicator_id = indicator_id self.published_status = published_status self.published_source = published_source self.published_comment = published_comment self.published_format = published_format self.published_accepted = published_accepted self.ordinal_value = ordinal_value if id is not None: self.id = id class PublishedFormat(db.Model): __tablename__ = 'publishedformat' id = Column(Integer, primary_key=True) name = Column(UnicodeText) title = Column(UnicodeText) format_class = Column(UnicodeText) format_value = Column(Float) def setup(self, name, title, format_class, format_value, id=None): self.name = name self.title = title self.format_class = format_class self.format_value = format_value if id is not None: self.id = id class PublishedStatus(db.Model): __tablename__ = 'publishedstatus' id = Column(Integer, primary_key=True) name = Column(UnicodeText) title = Column(UnicodeText) publishedstatus_class = Column(UnicodeText) publishedstatus_value = Column(Float) def setup(self, name, title, publishedstatus_class, publishedstatus_value, id=None): self.name = name self.title = title self.publishedstatus_class = publishedstatus_class self.publishedstatus_value = publishedstatus_value if id is not None: self.id = id class Workflow(db.Model): __tablename__='workflow' id = Column(Integer,primary_key=True) name = Column(UnicodeText) title = Column(UnicodeText) leadsto = Column(Integer, ForeignKey('workflow.id')) workflow_type = Column(Integer, ForeignKey('workflowtype.id')) duration = Column(Integer) def setup(self, name, title, leadsto, workflow_type=None, duration=None, id=None): self.name = name self.title = title self.leadsto = leadsto self.workflow_type = workflow_type self.duration = duration if id is not None: self.id = id # WorkflowType: define what sort of workflow this should be. # Will initially be hardcoded but this should make it easier # to expand and define later. class WorkflowType(db.Model): __tablename__='workflowtype' id = Column(Integer,primary_key=True) name = Column(UnicodeText) def setup(self, name, id=None): self.name = name if id is not None: self.id = id class WorkflowNotification(db.Model): __tablename__='workflownotifications' id = Column(Integer, primary_key=True) workflow_from = Column(Integer, ForeignKey('workflow.id')) workflow_to = Column(Integer, ForeignKey('workflow.id')) workflow_notice = Column(UnicodeText) class PackageTested(db.Model): __tablename__ = 'package_tested' package_id = Column(Integer, ForeignKey('package.id'), primary_key=True) runtime = Column(Integer, ForeignKey('package.id'), nullable=False) class UserActivity(db.Model): __tablename__='useractivity' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('dquser.id')) activity_type = Column(Integer) activity_data = Column(UnicodeText) ip_address = Column(UnicodeText) activity_date = Column(DateTime) add uniqueness constraint # IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3.0 from sqlalchemy import * from iatidq import db from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash ## TEST RUNTIME-SPECIFIC DATA class PackageStatus(db.Model): __tablename__ = 'packagestatus' id = Column(Integer, primary_key=True) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) status = Column(Integer, nullable=False) runtime_datetime = Column(DateTime) def __init__(self): self.runtime_datetime = datetime.utcnow() def __repr__(self): return unicode(self.runtime_datetime)+u' '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class Runtime(db.Model): __tablename__ = 'runtime' id = Column(Integer, primary_key=True) runtime_datetime = Column(DateTime, nullable=False) def __init__(self): self.runtime_datetime = datetime.utcnow() def __repr__(self): return unicode(self.runtime_datetime)+u' '+unicode(self.id) ## IATI REGISTRY PACKAGEGROUPS AND PACKAGES class PackageGroup(db.Model): __tablename__ = 'packagegroup' id = Column(Integer, primary_key=True) man_auto = Column(UnicodeText) name = Column(UnicodeText, nullable=False) ckan_id = Column(UnicodeText) revision_id = Column(UnicodeText) title = Column(UnicodeText) created_date = Column(UnicodeText) state = Column(UnicodeText) publisher_iati_id = Column(UnicodeText) publisher_segmentation = Column(UnicodeText) publisher_type = Column(UnicodeText) publisher_ui = Column(UnicodeText) publisher_organization_type = Column(UnicodeText) publisher_frequency = Column(UnicodeText) publisher_thresholds = Column(UnicodeText) publisher_units = Column(UnicodeText) publisher_contact = Column(UnicodeText) publisher_agencies = Column(UnicodeText) publisher_field_exclusions = Column(UnicodeText) publisher_description = Column(UnicodeText) publisher_record_exclusions = Column(UnicodeText) publisher_timeliness = Column(UnicodeText) license_id = Column(UnicodeText) publisher_country = Column(UnicodeText) publisher_refs = Column(UnicodeText) publisher_constraints = Column(UnicodeText) publisher_data_quality = Column(UnicodeText) __table_args__ = (UniqueConstraint('name',),) def __init__(self, man_auto=None, name=None): if man_auto is not None: self.man_auto = man_auto if name is not None: self.name = name def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class Package(db.Model): __tablename__ = 'package' id = Column(Integer, primary_key=True) man_auto = Column(UnicodeText) source_url = Column(UnicodeText) package_ckan_id = Column(UnicodeText) package_name = Column(UnicodeText, nullable=False) package_title = Column(UnicodeText) package_license_id = Column(UnicodeText) package_license = Column(UnicodeText) package_metadata_created = Column(UnicodeText) package_metadata_modified = Column(UnicodeText) package_group = Column(Integer, ForeignKey('packagegroup.id')) package_activity_from = Column(UnicodeText) package_activity_to = Column(UnicodeText) package_activity_count = Column(UnicodeText) package_country = Column(UnicodeText) package_archive_file = Column(UnicodeText) package_verified = Column(UnicodeText) package_filetype = Column(UnicodeText) package_revision_id = Column(UnicodeText) active = Column(Boolean) hash = Column(UnicodeText) deleted = Column(Boolean, default=False) __table_args__ = (UniqueConstraint('package_name'),) def __init__(self, man_auto=None, source_url=None): if man_auto is not None: self.man_auto = man_auto if source_url is not None: self.source_url = source_url def __repr__(self): source_url = self.source_url or "None" return source_url+u", "+str(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## RESULTS class Result(db.Model): __tablename__ = 'result' id = Column(Integer, primary_key=True) runtime_id = Column(Integer, ForeignKey('runtime.id'), nullable=False) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) organisation_id = Column(Integer, ForeignKey('organisation.id')) test_id = Column(Integer, ForeignKey('test.id'), nullable=False) result_data = Column(Integer, nullable=False) result_identifier = Column(UnicodeText) result_hierarchy = Column(Integer) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} db.Index('result_runpack', Result.runtime_id, Result.package_id, Result.result_identifier) db.Index('result_test', Result.test_id) # there should be a uniqueness constraint, roughly: # # alter table aggregateresult add unique ( # package_id, test_id, result_hierarchy, aggregateresulttype_id, # organisation_id # ); # # but after normalisation the package/organisation thing should go away class AggregateResult(db.Model): __tablename__='aggregateresult' id = Column(Integer,primary_key=True) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) organisation_id = Column(Integer, ForeignKey('organisation.id')) aggregateresulttype_id = Column(Integer, ForeignKey('aggregationtype.id'), nullable=False) test_id = Column(Integer, ForeignKey('test.id'), nullable=False) result_hierarchy = Column(Integer) results_data = Column(Float) results_num = Column(Integer) __table_args__ = (UniqueConstraint('package_id', 'test_id', 'result_hierarchy', 'aggregateresulttype_id', 'organisation_id'),) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} # AggregationType allows for different aggregations # Particularly used for looking only at current data class AggregationType(db.Model): __tablename__ = 'aggregationtype' id = Column(Integer,primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) test_id = Column(Integer, ForeignKey('test.id')) test_result = Column(Integer, nullable=False) active = Column(Integer) def setup(self, name, description, test_id, test_result, active, id=None): self.name = name self.description = description self.test_id = test_id self.test_result = test_result self.active = active if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## TESTS class Test(db.Model): __tablename__ = 'test' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText, nullable=False) test_group = Column(UnicodeText) file = Column(UnicodeText) line = Column(Integer) test_level = Column(Integer, nullable=False) active = Column(Boolean) def setup(self, name, description, test_group, test_level, active, id=None): self.name = name self.description = description self.test_group = test_group self.test_level = test_level self.active = active if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## CODELISTS class Codelist(db.Model): __tablename__ = 'codelist' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) source = Column(UnicodeText) def setup(self, name, description, id=None): self.name = name self.description = description if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class CodelistCode(db.Model): __tablename__ = 'codelistcode' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) code = Column(UnicodeText, nullable=False) codelist_id = Column(Integer, ForeignKey('codelist.id'), nullable=False) source = Column(UnicodeText) def setup(self, name, code, codelist_id, id=None): self.name = name self.code = code self.codelist_id = codelist_id if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## INDICATORS class IndicatorGroup(db.Model): __tablename__ = 'indicatorgroup' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) def setup(self, name, description, id=None): self.name = name self.description = description if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class Indicator(db.Model): __tablename__ = 'indicator' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) longdescription = Column(UnicodeText) indicatorgroup_id = Column(Integer, ForeignKey('indicatorgroup.id'), nullable=False) indicator_type = Column(UnicodeText) indicator_category_name = Column(UnicodeText) indicator_subcategory_name = Column(UnicodeText) indicator_ordinal = Column(Boolean) indicator_noformat = Column(Boolean) indicator_order = Column(Integer, nullable=False) indicator_weight = Column(Float(precision=4)) def setup(self, name, description, longdescription, indicatorgroup_id, indicator_type, indicator_category_name, indicator_subcategory_name, indicator_ordinal=None, indicator_noformat=None, indicator_order=None, indicator_weight=None, id=None): self.name = name self.description = description self.longdescription = longdescription self.indicatorgroup_id = indicatorgroup_id self.indicator_type = indicator_type self.indicator_category_name = indicator_category_name self.indicator_subcategory_name = indicator_subcategory_name self.indicator_ordinal = indicator_ordinal self.indicator_noformat = indicator_noformat self.indicator_order = indicator_order self.indicator_weight = indicator_weight if id is not None: self.id = id def __repr__(self): return self.name+u', '+unicode(self.id) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class IndicatorTest(db.Model): __tablename__ = 'indicatortest' id = Column(Integer, primary_key=True) indicator_id = Column(Integer, ForeignKey('indicator.id'), nullable=False) test_id = Column(Integer, ForeignKey('test.id'), nullable=False) __table_args__ = (UniqueConstraint('indicator_id', 'test_id'), ) def setup(self, indicator_id, test_id, id=None): self.indicator_id = indicator_id self.test_id = test_id if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class IndicatorInfoType(db.Model): __tablename__ = 'indicatorinfotype' id = Column(Integer, primary_key=True) indicator_id = Column(Integer, ForeignKey('indicator.id'), nullable=False) infotype_id = Column(Integer, ForeignKey('info_type.id'), nullable=False) def setup(self, indicator_id, infotype_id, id=None): self.indicator_id = indicator_id self.infotype_id = infotype_id if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class OrganisationCondition(db.Model): __tablename__ = 'organisationcondition' id = Column(Integer, primary_key=True) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) test_id = Column(Integer, ForeignKey('test.id'), nullable=False) operation = Column(Integer) # show (1) or don't show (0) result condition = Column(UnicodeText) # activity level, hierarchy 2 condition_value = Column(UnicodeText) # True, 2, etc. description = Column(UnicodeText) file = Column(UnicodeText) line = Column(Integer) active = Column(Boolean) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class OrganisationConditionFeedback(db.Model): __tablename__ ='organisationconditionfeedback' id = Column(Integer, primary_key=True) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) uses = Column(UnicodeText) element = Column(UnicodeText) where = Column(UnicodeText) def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} # Migration """ alter table organisationconditionfeedback alter column organisation_id type integer USING (organisation_id::integer); alter table organisationconditionfeedback add constraint ofbkorg FOREIGN KEY (organisation_id) REFERENCES organisation (id) MATCH FULL; """ ## ORGANISATIONS; RELATIONS WITH PACKAGES class Organisation(db.Model): __tablename__ = 'organisation' id = Column(Integer, primary_key=True) organisation_name = Column(UnicodeText, nullable=False) organisation_code = Column(UnicodeText, nullable=False) organisation_total_spend = Column(Float(precision=2)) organisation_total_spend_source = Column(UnicodeText) organisation_currency = Column(UnicodeText) organisation_currency_conversion = Column(Float(precision=4)) organisation_currency_conversion_source = Column(UnicodeText) organisation_largest_recipient = Column(UnicodeText) organisation_largest_recipient_source = Column(UnicodeText) frequency = Column(UnicodeText) frequency_comment = Column(UnicodeText) no_independent_reviewer=Column(Boolean) organisation_responded=Column(Integer) __table_args__ = (UniqueConstraint('organisation_name'), UniqueConstraint('organisation_code')) # organisation_code is also used to communicate # with implementation schedules def setup(self, organisation_name, organisation_code, organisation_total_spend=None, organisation_total_spend_source=None, organisation_currency=None, organisation_currency_conversion=None, organisation_currency_conversion_source=None, organisation_largest_recipient=None, organisation_largest_recipient_source=None, id=None): self.organisation_name = organisation_name self.organisation_code = organisation_code self.organisation_total_spend = organisation_total_spend, self.organisation_currency = organisation_currency, self.organisation_currency_conversion = organisation_currency_conversion, self.organisation_currency_conversion_source = organisation_currency_conversion_source, self.organisation_largest_recipient = organisation_largest_recipient if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class OrganisationPackage(db.Model): __tablename__ = 'organisationpackage' id = Column(Integer, primary_key=True) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) condition = Column(UnicodeText) __table_args__ = (UniqueConstraint('organisation_id', 'package_id', name='_organisation_package_uc'), ) def setup(self, organisation_id, package_id, condition=None, id=None): self.organisation_id = organisation_id self.package_id = package_id self.condition = condition if id is not None: self.id = id class OrganisationPackageGroup(db.Model): __tablename__ = 'organisationpackagegroup' id = Column(Integer, primary_key=True) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) packagegroup_id = Column(Integer, ForeignKey('packagegroup.id'), nullable=False) condition = Column(UnicodeText) __table_args__ = (UniqueConstraint('organisation_id', 'packagegroup_id'),) def setup(self, organisation_id, packagegroup_id, condition=None, id=None): self.organisation_id = organisation_id self.packagegroup_id = packagegroup_id self.condition = condition if id is not None: self.id = id ## INFORESULTS # TODO: IMPLEMENT # ==> total amount of disbursements in this package # e.g. 1 = total disbursements class InfoResult(db.Model): __tablename__ = 'info_result' id = Column(Integer, primary_key=True) runtime_id = Column(Integer, ForeignKey('runtime.id'), nullable=False) package_id = Column(Integer, ForeignKey('package.id'), nullable=False) info_id = Column(Integer, ForeignKey('info_type.id'), nullable=False) organisation_id = Column(Integer, ForeignKey('organisation.id')) result_data = Column(Float) class InfoType(db.Model): __tablename__ = 'info_type' id = Column(Integer, primary_key=True) name = Column(UnicodeText, nullable=False) description = Column(UnicodeText) level = Column(Integer, nullable=False) def setup(self, name, level, description=None, id=None): self.name = name self.level = level self.description = description if id is not None: self.id = id ## USERS class User(db.Model): __tablename__ = 'dquser' id = Column(Integer, primary_key=True) username = Column(UnicodeText, nullable=False) name = Column(UnicodeText) email_address = Column(UnicodeText) reset_password_key = Column(UnicodeText) pw_hash = db.Column(String(255)) organisation = Column(UnicodeText) children = db.relationship("UserPermission", cascade="all, delete-orphan", passive_deletes=True) __table_args__ = (UniqueConstraint('username',),) def setup(self, username, password, name, email_address=None, organisation=None, id=None): self.username = username self.pw_hash = generate_password_hash(password) self.name = name self.email_address = email_address self.organisation = organisation if id is not None: self.id = id def check_password(self, password): return check_password_hash(self.pw_hash, password) def is_active(self): return True def get_id(self): return self.id def is_anonymous(self): return False def is_authenticated(self): return True class UserPermission(db.Model): __tablename__ = 'userpermission' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('dquser.id', ondelete='CASCADE')) permission_name = Column(UnicodeText) # survey_donorreview permission_method = Column(UnicodeText) # edit permission_value = Column(UnicodeText) # 1 def setup(self, user_id, permission_name, permission_method=None, permission_value=None, id=None): self.user_id = user_id self.permission_name = permission_name self.permission_method = permission_method self.permission_value = permission_value if id is not None: self.id = id def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} ## ORGANISATION SURVEYS class OrganisationSurvey(db.Model): __tablename__ = 'organisationsurvey' id = Column(Integer,primary_key=True) currentworkflow_id = Column(Integer, ForeignKey('workflow.id'), nullable=False) currentworkflow_deadline = Column(DateTime) organisation_id = Column(Integer, ForeignKey('organisation.id'), nullable=False) __table_args__ = (UniqueConstraint('organisation_id',),) def setup(self, organisation_id, currentworkflow_id, currentworkflow_deadline=None, id=None): self.organisation_id = organisation_id self.currentworkflow_id = currentworkflow_id self.currentworkflow_deadline = currentworkflow_deadline if id is not None: self.id = id class OrganisationSurveyData(db.Model): __tablename__ = 'organisationsurveydata' id = Column(Integer,primary_key=True) organisationsurvey_id = Column(Integer, ForeignKey('organisationsurvey.id'), nullable=False) indicator_id = Column(Integer, ForeignKey('indicator.id'), nullable=False) workflow_id = Column(Integer, ForeignKey('workflow.id'), nullable=False) published_status = Column(Integer, ForeignKey('publishedstatus.id')) published_source = Column(UnicodeText) published_comment = Column(UnicodeText) published_format = Column(Integer, ForeignKey('publishedformat.id')) published_accepted = Column(Integer) ordinal_value = Column(Float(precision=2)) __table_args__ = (UniqueConstraint('organisationsurvey_id', 'indicator_id', 'workflow_id'),) def setup(self, organisationsurvey_id, indicator_id, workflow_id=None, published_status=None, published_source=None, published_comment=None, published_format=None, published_accepted=None, ordinal_value=None, id=None): self.organisationsurvey_id = organisationsurvey_id self.workflow_id = workflow_id self.indicator_id = indicator_id self.published_status = published_status self.published_source = published_source self.published_comment = published_comment self.published_format = published_format self.published_accepted = published_accepted self.ordinal_value = ordinal_value if id is not None: self.id = id class PublishedFormat(db.Model): __tablename__ = 'publishedformat' id = Column(Integer, primary_key=True) name = Column(UnicodeText) title = Column(UnicodeText) format_class = Column(UnicodeText) format_value = Column(Float) def setup(self, name, title, format_class, format_value, id=None): self.name = name self.title = title self.format_class = format_class self.format_value = format_value if id is not None: self.id = id class PublishedStatus(db.Model): __tablename__ = 'publishedstatus' id = Column(Integer, primary_key=True) name = Column(UnicodeText) title = Column(UnicodeText) publishedstatus_class = Column(UnicodeText) publishedstatus_value = Column(Float) def setup(self, name, title, publishedstatus_class, publishedstatus_value, id=None): self.name = name self.title = title self.publishedstatus_class = publishedstatus_class self.publishedstatus_value = publishedstatus_value if id is not None: self.id = id class Workflow(db.Model): __tablename__='workflow' id = Column(Integer,primary_key=True) name = Column(UnicodeText) title = Column(UnicodeText) leadsto = Column(Integer, ForeignKey('workflow.id')) workflow_type = Column(Integer, ForeignKey('workflowtype.id')) duration = Column(Integer) def setup(self, name, title, leadsto, workflow_type=None, duration=None, id=None): self.name = name self.title = title self.leadsto = leadsto self.workflow_type = workflow_type self.duration = duration if id is not None: self.id = id # WorkflowType: define what sort of workflow this should be. # Will initially be hardcoded but this should make it easier # to expand and define later. class WorkflowType(db.Model): __tablename__='workflowtype' id = Column(Integer,primary_key=True) name = Column(UnicodeText) def setup(self, name, id=None): self.name = name if id is not None: self.id = id class WorkflowNotification(db.Model): __tablename__='workflownotifications' id = Column(Integer, primary_key=True) workflow_from = Column(Integer, ForeignKey('workflow.id')) workflow_to = Column(Integer, ForeignKey('workflow.id')) workflow_notice = Column(UnicodeText) class PackageTested(db.Model): __tablename__ = 'package_tested' package_id = Column(Integer, ForeignKey('package.id'), primary_key=True) runtime = Column(Integer, ForeignKey('package.id'), nullable=False) class UserActivity(db.Model): __tablename__='useractivity' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('dquser.id')) activity_type = Column(Integer) activity_data = Column(UnicodeText) ip_address = Column(UnicodeText) activity_date = Column(DateTime)
#!/usr/bin/env python try: from pyspark import SparkContext, SparkFiles except: print "### NO PYSPARK" import sys import os import platform import socket from hybridJaccard import HybridJaccard import argparse import json import cgi from htmltoken import tokenize import crf_features from base64 import b64encode, b64decode # import snakebite for doing hdfs file manipulations from snakebite.client import Client from snakebite.errors import FileNotFoundException def extract_body(main_json): try: return main_json["hasBodyPart"]["text"] except: pass def extract_title(main_json): try: return main_json["hasTitlePart"]["text"] except: pass def textTokens(texts): # Turn None into empty text texts = texts or "" # Allow for multiple texts texts = texts if isinstance(texts, list) else [texts] v = [] for text in texts: try: for tok in genescaped(text): v.append([tok]) except TypeError as e: print >> sys.stderr, "Error %s" % e print >> sys.stderr, type(text) print >> sys.stderr, "Computing textTokens of %s: %s" % (text, e) v.append("") return v def genescaped(text, maxTokenLength=40): """All tokens in TEXT with any odd characters (such as <>&) encoded using HTML escaping""" for tok in tokenize(text, interpret=cgi.escape, keepTags=False): # Some ads have odd tokens like 1000 As in a row if len(tok) <= maxTokenLength: # yield tok yield tok.replace('\t', ' ') ### The URI + index mechanism isn't good enough to recover data when there are multiple sentences per URI ### which can occur from (a) title + body as separate documents (b) sentence breaking of body ### The intra-sentence space rows won't be maintained by reconstructTuple + groupBy ### Proposed future workarounds: ### (a) sentence-specific temporary URIs ending /processed/title or /processed/1 ### (b) and/or sentence-specific indexing 1.1, 1.2, ... 1.N, 2.1, etc. could work def reconstructTuple(tabsep): """Works only for old multi-line invocation of crf_test, not crf_test_b64""" fields = tabsep.split('\t') try: uri = fields[-3] idx = fields[-2] except: uri = "endOfDocument" idx = "0" return (uri, [idx] + fields) def fakeFindBestMatch(words): if 'blue' in words: return 'blue' else: return 'NONE' def alignToControlledVocab(harvested, vocabs): """harvested is a dict matching category 'eyeColor', 'hairType' to a function""" try: category = harvested['category'] # f = vocabs[category] f = fakeFindBestMatch words = harvested['words'] try: harvested['bestMatch'] = f(words) except Exception as e: return "sm.findBestMatch error:" + str(e) + ":" + str(words) return harvested except Exception as e: return str(e) return None def vectorToUTF8(v, debug=False): "unicode only" def rowToUnicode(r): try: if isinstance(r, list): return u"\t".join([unicode(x) for x in r]) else: return unicode(r) except: print >> sys.stderr, "error in rowToUnicode" return u"" rows = [] if v[-1] == u"": pass else: # print "appending1" v.append(u"") for r in v: rows.append(rowToUnicode(r)) result = u"\n".join(rows) # result now a unicode object # here is the only place where we convert to UTF8 return result.encode('utf-8') ### HISTORICAL def computeSpans(v, verbose=False, indexed=False): # extract the data and write the result as vector currentLabel = None currentTokens = [] spans = [] def addSpan(u, l, words): spans.append( {"uri": u, "category": l, "words": " ".join(words) } ) if verbose: print >> sys.stderr, " Added %s" % (spans[-1],) uri = 'bogus' currentUri = None for row in v: if (len(row) <= 1): # blank/empty line: expecting "" but might be [] if currentLabel and currentTokens: addSpan(currentUri, currentLabel, currentTokens) currentUri = None continue if (len(row) >= 4): # a typical row token = row[0] uri = row[-3] if indexed else row[-2] label = row[-1] if verbose: print >> sys.stderr, "Typical row: token %r uri %r: crflabel %r" % (token, uri, label) # now process this row if label == "O": # unlabeled row if currentLabel: # so this concludes span in progress addSpan(uri, currentLabel, currentTokens) currentLabel = None currentTokens = [] else: pass else: # Labeled row if label == currentLabel: # continue span in progress currentTokens.append(token) elif currentLabel and label != currentLabel: # span/span boundary # first conclude old one addSpan(uri, currentLabel, currentTokens) currentLabel = None currentTokens = [] # then begin new one currentLabel = label currentTokens = [token] elif not currentLabel: # begin novel span currentLabel = label currentTokens = [token] else: raise Exception("Unexpected file structure") currentUri = uri if currentLabel and currentTokens: # Input ended without blank line after last marked span, so hallucinate one addSpan(uri, currentLabel, currentTokens) # Publish results return spans def crfsmall(sc, input, output, limit=None, location='hdfs', outputFormat="text", numPartitions=None): crfConfigDir = os.path.join(os.path.dirname(__file__), "data/config") featureListFilename = os.path.join(crfConfigDir, "features.hair-eye") crfExecutable = os.path.join(os.path.dirname(__file__), "bin/crf_test_filter.sh") crfModelFilename = os.path.join(crfConfigDir, "dig-hair-eye-train.model") sc.addFile(crfExecutable) sc.addFile(crfModelFilename) # crfConfigDir = os.path.join(os.path.dirname(__file__), "data/config") # def cpath(n): # return os.path.join(crfConfigDir, n) # smEyeColor = HybridJaccard(ref_path=cpath("eyeColor_reference_wiki.txt"), # config_path=cpath("eyeColor_config.txt")) # smHairColor = HybridJaccard(ref_path=cpath("hairColor_reference_wiki.txt"), # config_path=cpath("hairColor_config.txt")) # print smEyeColor, smHairColor # hypothesis1: data fetched this way prompts the lzo compression error # hypothesis2: but it doesn't matter, error is just a warning rdd_crfl = sc.sequenceFile(input) rdd_crfl.setName('rdd_crfl') if limit: rdd_crfl = sc.parallelize(rdd_crfl.take(limit)) if numPartitions: rdd_crfl = rdd_crfl.repartition(numPartitions) rdd_json = rdd_crfl.mapValues(lambda x: json.loads(x)) rdd_json.setName('rdd_json') # rdd_json.persist() rdd_texts = rdd_json.mapValues(lambda x: (textTokens(extract_body(x)), textTokens(extract_title(x)))) rdd_texts.setName('rdd_texts') c = crf_features.CrfFeatures(featureListFilename) SEPARATOR = '&amp;nbsp;', def makeMatrix(c, uri, bodyTokens, titleTokens): b = c.computeFeatMatrix(bodyTokens, False, addLabels=False, addIndex=False) s = c.computeFeatMatrix([SEPARATOR, ""], False, addLabels=False, addIndex=False) t = c.computeFeatMatrix(titleTokens, False, addLabels=False, addIndex=False) idx = 1 for row in b: if row == u"": pass else: label = uri + "/%05d/%05d" % (0, idx) row.append(label) idx += 1 idx = 1 for row in s: if row == u"": pass else: label = uri + "/%05d/%05d" % (1, idx) row.append(label) idx += 1 idx = 1 for row in t: if row == u"": pass else: label = uri + "/%05d/%05d" % (2, idx) row.append(label) idx += 1 # might be b[0:-1] + s[0:-1] + t? return b[0:-1] + s[0:-1] + t rdd_features = rdd_texts.map(lambda x: makeMatrix(c, x[0], x[1][0], x[1][1])) rdd_features.setName('rdd_features') # rdd_features.persist() # unicode/string representation of the feature matrix rdd_vector = rdd_features.map(lambda x: vectorToUTF8(x)) rdd_vector.setName('rdd_vector') # all strings concatenated together, then base64 encoded into one input for crf_test rdd_pipeinput = sc.parallelize([b64encode(rdd_vector.reduce(lambda a,b: a+b))]) rdd_pipeinput.setName('rdd_pipeinput') executable = SparkFiles.get(os.path.basename(crfExecutable)) model = SparkFiles.get(os.path.basename(crfModelFilename)) cmd = "%s %s" % (executable, model) # this result is base64 encoded rdd_crfoutput = rdd_pipeinput.pipe(cmd) rdd_crfoutput.setName('rdd_crfoutput') rdd_base64decode = rdd_crfoutput.map(lambda x: b64decode(x)) ### There may be a need to utf8 decode this data ### ### There are values like \xed\xa0\xbd which might be a broken emoji # 1. break into physical lines # 2. turn each line into its own spark row # 3. drop any inter-document empty string markers rdd_lines = rdd_base64decode.map(lambda x: x.split("\n")).flatMap(lambda l: l).filter(lambda x: len(x)>1) def processOneLine(l): return l.split("\t") rdd_triples = rdd_lines.map(lambda l: processOneLine(l)) rdd_triples.saveAsTextFile('out_rdd_triples') def organizeByOrigDoc(triple): try: (word, uri, label) = triple (parentUri, docId, wordId) = uri.rsplit('/', 2) return ( (parentUri, docId), (wordId, word, label) ) except Exception as e: print "Can't destructure %r" % [triple] return () rdd_reorg = rdd_triples.map(lambda l: organizeByOrigDoc(l)) rdd_reorg.saveAsTextFile('out_rdd_reorg') rdd_sorted = rdd_reorg.sortByKey() rdd_sorted.saveAsTextFile('out_rdd_sorted') # each (parentUri, docId) has a sequence of (wordId, word, label) # we want to consider them in order (by wordId) rdd_grouped = rdd_sorted.groupByKey() def harvest(seq): allSpans = [] lastIndex = -2 lastLabel = None currentSpan = [] for (wordId, word, label) in seq: currentIndex = int(wordId) if lastIndex+1 == currentIndex and lastLabel == label: # continuing current span currentSpan.append( (currentIndex, word, label) ) else: # end current span if currentSpan: allSpans.append(currentSpan) # begin new span currentSpan = [ (currentIndex, word, label) ] lastLabel = label lastIndex = currentIndex # end current span if currentSpan: allSpans.append(currentSpan) result = [] for span in allSpans: words = [] spanLabel = None for (wordIdx, word, label) in span: spanLabel = label words.append(word) result.append( (' '.join(words), spanLabel) ) return result # ( (parentUri, docId), [ (words1, category1), (words2, category2), ... ] rdd_harvest = rdd_grouped.mapValues(lambda s: harvest(s)) rdd_harvest.saveAsTextFile('out_rdd_harvest') # rdd_flat = rdd_harvest.flatMap(lambda r: [ (e[0][0], e[1]) for e in r ]) # rdd_flat = rdd_harvest.map(lambda r: (r[0][0], r[1])) # parentUri -> (words, category) # we use .distinct() because (e.g.) both title and body might have the same feature rdd_flat = rdd_harvest.map(lambda r: (r[0][0], r[1])).flatMapValues(lambda x: x).distinct() rdd_flat.saveAsTextFile('out_rdd_flat') # rdd_aligned = rdd_flat.mapValues(lambda x: alignToControlledVocab(x, {"eyeColor": smEyeColor.findBestMatch, # "hairType": smHairColor.findBestMatch})) exit(1) rdd_final = rdd_harvest if outputFormat == "sequence": rdd_final.saveAsSequenceFile(output) elif outputFormat == "text": rdd_final.saveAsTextFile(output) else: raise RuntimeError("Unrecognized output format: %s" % outputFormat) def main(argv=None): '''this is called if run from command line''' parser = argparse.ArgumentParser() parser.add_argument('-i','--input', required=True) parser.add_argument('-o','--output', required=True) parser.add_argument('-p','--numPartitions', required=False, default=None, type=int) parser.add_argument('-l','--limit', required=False, default=None, type=int) parser.add_argument('-v','--verbose', required=False, help='verbose', action='store_true') args=parser.parse_args() location = "hdfs" try: if "avatar" in platform.node(): location = "local" except: pass try: if "avatar" in socket.gethostname(): location = "local" except: pass print "### location %s" % location if not args.numPartitions: if location == "local": args.numPartitions = 2 elif location == "hdfs": args.numPartitions = 50 sc = SparkContext(appName="crfsmall") crfsmall(sc, args.input, args.output, limit=args.limit, location=location, outputFormat="text", numPartitions=args.numPartitions) # call main() if this is run as standalone if __name__ == "__main__": sys.exit(main()) calls hj properly #!/usr/bin/env python try: from pyspark import SparkContext, SparkFiles except: print "### NO PYSPARK" import sys import os import platform import socket from hybridJaccard import HybridJaccard import argparse import json import cgi from htmltoken import tokenize import crf_features from base64 import b64encode, b64decode # configDir = os.path.join(os.path.dirname(__file__), "data/config") # def configPath(n): # return os.path.join(configDir, n) # smHairColor = HybridJaccard(ref_path=configPath("hairColor_reference_wiki.txt"), # config_path=configPath("hairColor_config.txt")) # print smHairColor.findBestMatch("redhead") # exit(0) # import snakebite for doing hdfs file manipulations from snakebite.client import Client from snakebite.errors import FileNotFoundException def extract_body(main_json): try: return main_json["hasBodyPart"]["text"] except: pass def extract_title(main_json): try: return main_json["hasTitlePart"]["text"] except: pass def textTokens(texts): # Turn None into empty text texts = texts or "" # Allow for multiple texts texts = texts if isinstance(texts, list) else [texts] v = [] for text in texts: try: for tok in genescaped(text): v.append([tok]) except TypeError as e: print >> sys.stderr, "Error %s" % e print >> sys.stderr, type(text) print >> sys.stderr, "Computing textTokens of %s: %s" % (text, e) v.append("") return v def genescaped(text, maxTokenLength=40): """All tokens in TEXT with any odd characters (such as <>&) encoded using HTML escaping""" for tok in tokenize(text, interpret=cgi.escape, keepTags=False): # Some ads have odd tokens like 1000 As in a row if len(tok) <= maxTokenLength: # yield tok yield tok.replace('\t', ' ') ### The URI + index mechanism isn't good enough to recover data when there are multiple sentences per URI ### which can occur from (a) title + body as separate documents (b) sentence breaking of body ### The intra-sentence space rows won't be maintained by reconstructTuple + groupBy ### Proposed future workarounds: ### (a) sentence-specific temporary URIs ending /processed/title or /processed/1 ### (b) and/or sentence-specific indexing 1.1, 1.2, ... 1.N, 2.1, etc. could work def reconstructTuple(tabsep): """Works only for old multi-line invocation of crf_test, not crf_test_b64""" fields = tabsep.split('\t') try: uri = fields[-3] idx = fields[-2] except: uri = "endOfDocument" idx = "0" return (uri, [idx] + fields) def fakeFindBestMatch(words): if 'blue' in words: return 'blue' else: return 'NONE' def alignToControlledVocab(harvested, vocabs): """harvested is a dict matching category 'eyeColor', 'hairType' to a function""" try: category = harvested['category'] # f = vocabs[category] f = fakeFindBestMatch words = harvested['words'] try: harvested['bestMatch'] = f(words) except Exception as e: return "sm.findBestMatch error:" + str(e) + ":" + str(words) return harvested except Exception as e: return str(e) return None def vectorToUTF8(v, debug=False): "unicode only" def rowToUnicode(r): try: if isinstance(r, list): return u"\t".join([unicode(x) for x in r]) else: return unicode(r) except: print >> sys.stderr, "error in rowToUnicode" return u"" rows = [] if v[-1] == u"": pass else: # print "appending1" v.append(u"") for r in v: rows.append(rowToUnicode(r)) result = u"\n".join(rows) # result now a unicode object # here is the only place where we convert to UTF8 return result.encode('utf-8') ### HISTORICAL def computeSpans(v, verbose=False, indexed=False): # extract the data and write the result as vector currentLabel = None currentTokens = [] spans = [] def addSpan(u, l, words): spans.append( {"uri": u, "category": l, "words": " ".join(words) } ) if verbose: print >> sys.stderr, " Added %s" % (spans[-1],) uri = 'bogus' currentUri = None for row in v: if (len(row) <= 1): # blank/empty line: expecting "" but might be [] if currentLabel and currentTokens: addSpan(currentUri, currentLabel, currentTokens) currentUri = None continue if (len(row) >= 4): # a typical row token = row[0] uri = row[-3] if indexed else row[-2] label = row[-1] if verbose: print >> sys.stderr, "Typical row: token %r uri %r: crflabel %r" % (token, uri, label) # now process this row if label == "O": # unlabeled row if currentLabel: # so this concludes span in progress addSpan(uri, currentLabel, currentTokens) currentLabel = None currentTokens = [] else: pass else: # Labeled row if label == currentLabel: # continue span in progress currentTokens.append(token) elif currentLabel and label != currentLabel: # span/span boundary # first conclude old one addSpan(uri, currentLabel, currentTokens) currentLabel = None currentTokens = [] # then begin new one currentLabel = label currentTokens = [token] elif not currentLabel: # begin novel span currentLabel = label currentTokens = [token] else: raise Exception("Unexpected file structure") currentUri = uri if currentLabel and currentTokens: # Input ended without blank line after last marked span, so hallucinate one addSpan(uri, currentLabel, currentTokens) # Publish results return spans def crfsmall(sc, input, output, limit=None, location='hdfs', outputFormat="text", numPartitions=None): configDir = os.path.join(os.path.dirname(__file__), "data/config") def configPath(n): return os.path.join(configDir, n) binDir = os.path.join(os.path.dirname(__file__), "bin") def binPath(n): return os.path.join(binDir, n) featureListFilename = configPath("features.hair-eye") crfExecutable = binPath("crf_test_filter.sh") crfModelFilename = configPath("dig-hair-eye-train.model") sc.addFile(crfExecutable) sc.addFile(crfModelFilename) rdd_crfl = sc.sequenceFile(input) rdd_crfl.setName('rdd_crfl') if limit: rdd_crfl = sc.parallelize(rdd_crfl.take(limit)) if numPartitions: rdd_crfl = rdd_crfl.repartition(numPartitions) rdd_json = rdd_crfl.mapValues(lambda x: json.loads(x)) rdd_json.setName('rdd_json') # rdd_json.persist() rdd_texts = rdd_json.mapValues(lambda x: (textTokens(extract_body(x)), textTokens(extract_title(x)))) rdd_texts.setName('rdd_texts') c = crf_features.CrfFeatures(featureListFilename) SEPARATOR = '&amp;nbsp;', def makeMatrix(c, uri, bodyTokens, titleTokens): b = c.computeFeatMatrix(bodyTokens, False, addLabels=False, addIndex=False) s = c.computeFeatMatrix([SEPARATOR, ""], False, addLabels=False, addIndex=False) t = c.computeFeatMatrix(titleTokens, False, addLabels=False, addIndex=False) idx = 1 for row in b: if row == u"": pass else: label = uri + "/%05d/%05d" % (0, idx) row.append(label) idx += 1 idx = 1 for row in s: if row == u"": pass else: label = uri + "/%05d/%05d" % (1, idx) row.append(label) idx += 1 idx = 1 for row in t: if row == u"": pass else: label = uri + "/%05d/%05d" % (2, idx) row.append(label) idx += 1 # might be b[0:-1] + s[0:-1] + t? return b[0:-1] + s[0:-1] + t rdd_features = rdd_texts.map(lambda x: makeMatrix(c, x[0], x[1][0], x[1][1])) rdd_features.setName('rdd_features') # rdd_features.persist() # unicode/string representation of the feature matrix rdd_vector = rdd_features.map(lambda x: vectorToUTF8(x)) rdd_vector.setName('rdd_vector') # all strings concatenated together, then base64 encoded into one input for crf_test rdd_pipeinput = sc.parallelize([b64encode(rdd_vector.reduce(lambda a,b: a+b))]) rdd_pipeinput.setName('rdd_pipeinput') executable = SparkFiles.get(os.path.basename(crfExecutable)) model = SparkFiles.get(os.path.basename(crfModelFilename)) cmd = "%s %s" % (executable, model) # this result is base64 encoded rdd_crfoutput = rdd_pipeinput.pipe(cmd) rdd_crfoutput.setName('rdd_crfoutput') rdd_base64decode = rdd_crfoutput.map(lambda x: b64decode(x)) ### There may be a need to utf8 decode this data ### ### There are values like \xed\xa0\xbd which might be a broken emoji # 1. break into physical lines # 2. turn each line into its own spark row # 3. drop any inter-document empty string markers rdd_lines = rdd_base64decode.map(lambda x: x.split("\n")).flatMap(lambda l: l).filter(lambda x: len(x)>1) def processOneLine(l): return l.split("\t") rdd_triples = rdd_lines.map(lambda l: processOneLine(l)) rdd_triples.saveAsTextFile('out_rdd_triples') def organizeByOrigDoc(triple): try: (word, uri, label) = triple (parentUri, docId, wordId) = uri.rsplit('/', 2) return ( (parentUri, docId), (wordId, word, label) ) except Exception as e: print >> sys.stderr, "Can't destructure %r: %s" % (triple, e) return () rdd_reorg = rdd_triples.map(lambda l: organizeByOrigDoc(l)) rdd_reorg.saveAsTextFile('out_rdd_reorg') rdd_sorted = rdd_reorg.sortByKey() rdd_sorted.saveAsTextFile('out_rdd_sorted') # each (parentUri, docId) has a sequence of (wordId, word, label) # we want to consider them in order (by wordId) rdd_grouped = rdd_sorted.groupByKey() def harvest(seq): allSpans = [] lastIndex = -2 lastLabel = None currentSpan = [] for (wordId, word, label) in seq: currentIndex = int(wordId) if lastIndex+1 == currentIndex and lastLabel == label: # continuing current span currentSpan.append( (currentIndex, word, label) ) else: # end current span if currentSpan: allSpans.append(currentSpan) # begin new span currentSpan = [ (currentIndex, word, label) ] lastLabel = label lastIndex = currentIndex # end current span if currentSpan: allSpans.append(currentSpan) result = [] for span in allSpans: words = [] spanLabel = None for (wordIdx, word, label) in span: spanLabel = label words.append(word) result.append( (' '.join(words), spanLabel) ) return result # ( (parentUri, docId), [ (words1, category1), (words2, category2), ... ] rdd_harvest = rdd_grouped.mapValues(lambda s: harvest(s)) rdd_harvest.saveAsTextFile('out_rdd_harvest') # rdd_flat = rdd_harvest.flatMap(lambda r: [ (e[0][0], e[1]) for e in r ]) # rdd_flat = rdd_harvest.map(lambda r: (r[0][0], r[1])) # parentUri -> (words, category) # we use .distinct() because (e.g.) both title and body might have the same feature rdd_flat = rdd_harvest.map(lambda r: (r[0][0], r[1])).flatMapValues(lambda x: x).distinct() rdd_flat.saveAsTextFile('out_rdd_flat') smEyeColor = HybridJaccard(ref_path=configPath("eyeColor_reference_wiki.txt"), config_path=configPath("eyeColor_config.txt")) smHairColor = HybridJaccard(ref_path=configPath("hairColor_reference_wiki.txt"), config_path=configPath("hairColor_config.txt")) hybridJaccards = {"eyeColor": smEyeColor.findBestMatch, "hairType": smHairColor.findBestMatch} def jaccard(tpl): (words, category) = tpl return (category, hybridJaccards[category](words)) rdd_aligned = rdd_flat.mapValues(lambda x: jaccard(x)) rdd_aligned.saveAsTextFile('out_rdd_aligned') exit(1) rdd_final = rdd_harvest if outputFormat == "sequence": rdd_final.saveAsSequenceFile(output) elif outputFormat == "text": rdd_final.saveAsTextFile(output) else: raise RuntimeError("Unrecognized output format: %s" % outputFormat) def main(argv=None): '''this is called if run from command line''' parser = argparse.ArgumentParser() parser.add_argument('-i','--input', required=True) parser.add_argument('-o','--output', required=True) parser.add_argument('-p','--numPartitions', required=False, default=None, type=int) parser.add_argument('-l','--limit', required=False, default=None, type=int) parser.add_argument('-v','--verbose', required=False, help='verbose', action='store_true') args=parser.parse_args() location = "hdfs" try: if "avatar" in platform.node(): location = "local" except: pass try: if "avatar" in socket.gethostname(): location = "local" except: pass print "### location %s" % location if not args.numPartitions: if location == "local": args.numPartitions = 2 elif location == "hdfs": args.numPartitions = 50 sc = SparkContext(appName="crfsmall") crfsmall(sc, args.input, args.output, limit=args.limit, location=location, outputFormat="text", numPartitions=args.numPartitions) # call main() if this is run as standalone if __name__ == "__main__": sys.exit(main())
import numpy as np import falcon import json class Tukey(object): ''' A timeseries is anomalous if any point is 1.5 times the interquartile range less than the first quartile or more than the third quartile. ''' def on_get(self, req, resp): timeseries, tidx, vidx = utils.backend_retreival(req) self._run(req, resp, timeseries, tidx, vidx) def on_post(self, req, resp): timeseries, tidx, vidx = utils.backend_retreival(req) self._run(req, resp, timeseries, tidx, vidx) def _run(self, req, resp, timeseries, tidx, vidx): outlier_threshold = req.get_param_as_int("outlier_threshold", required=False) if outlier_threshold: result = self._work(timeseries, tidx, vidx, outlier_threshold) else: result = self._work(timeseries, tidx=tidx, vidx=vidx) resp.body = json.dumps(result) resp.status = falcon.HTTP_200 def _work(self, timeseries, tidx=0, vidx=1, outlier_threshold=1.5): series = np.array([x[vidx] for x in timeseries]) # Calculate quartiles and IQR q25, q75 = np.percentile(series, [25,75]) iqr = q75 - q25 # Lower and upper outlier boundaries low = q25 - (outlier_threshold * iqr) high = q75 + (outlier_threshold * iqr) # Indexes of outliers low_indexes = np.where(series < low) high_indexes = np.where(series > high) indexes = np.concatenate((low_indexes, high_indexes), axis=1) result = [] for i in indexes.tolist(): for x in i: result.append(timeseries[x]) # Return timeseries of outliers return result removing for loop to make code numpy pythonic import numpy as np import falcon import json class Tukey(object): ''' A timeseries is anomalous if any point is 1.5 times the interquartile range less than the first quartile or more than the third quartile. ''' def on_get(self, req, resp): timeseries, tidx, vidx = utils.backend_retreival(req) self._run(req, resp, timeseries, tidx, vidx) def on_post(self, req, resp): timeseries, tidx, vidx = utils.backend_retreival(req) self._run(req, resp, timeseries, tidx, vidx) def _run(self, req, resp, timeseries, tidx, vidx): outlier_threshold = req.get_param_as_int("outlier_threshold", required=False) if outlier_threshold: result = self._work(timeseries, tidx, vidx, outlier_threshold) else: result = self._work(timeseries, tidx=tidx, vidx=vidx) resp.body = json.dumps(result) resp.status = falcon.HTTP_200 def _work(self, timeseries, tidx=0, vidx=1, outlier_threshold=1.5): series = np.array(timeseries) values = series[:,vidx] # Calculate quartiles and IQR q25, q75 = np.percentile(values, [25,75]) iqr = q75 - q25 # Lower and upper outlier boundaries low = q25 - (outlier_threshold * iqr) high = q75 + (outlier_threshold * iqr) # Indexes of outliers low_indexes = np.where(values < low) high_indexes = np.where(values > high) indexes = np.concatenate((low_indexes, high_indexes), axis=1) indexes = indexes.flatten() # Return timeseries of outliers return series[indexes].tolist()
Return the number of failed tests so moosebuild can detect errors.
#!/usr/bin/python # ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2007 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of the pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Windows DirectSound audio implementation. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import time from pyglet.media import AudioPlayer, Listener, MediaException from pyglet.media.drivers.directsound import lib_dsound as lib from pyglet.window.win32 import _user32 class DirectSoundException(MediaException): pass class DirectSoundAudioPlayer(AudioPlayer): _buffer_size = 44800 * 1 _update_buffer_size = _buffer_size // 4 _buffer_size_secs = None def __init__(self, audio_format): super(DirectSoundAudioPlayer, self).__init__(audio_format) self._playing = False self._timestamp = 0. self._buffer = None self._buffer_playing = False self._play_cursor = 0 self._buffer_time = 0. # ts of buffer at buffer_time_pos self._buffer_time_pos = 0 self._write_cursor = 0 self._timestamps = [] self._eos_count = 0 self._dirty_size = 0 wfx = lib.WAVEFORMATEX() wfx.wFormatTag = lib.WAVE_FORMAT_PCM wfx.nChannels = audio_format.channels wfx.nSamplesPerSec = audio_format.sample_rate wfx.wBitsPerSample = audio_format.sample_size wfx.nBlockAlign = wfx.wBitsPerSample * wfx.nChannels // 8 wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign dsbdesc = lib.DSBUFFERDESC() dsbdesc.dwSize = ctypes.sizeof(dsbdesc) dsbdesc.dwFlags = (lib.DSBCAPS_GLOBALFOCUS | lib.DSBCAPS_GETCURRENTPOSITION2 | lib.DSBCAPS_CTRLVOLUME) if audio_format.channels == 1: dsbdesc.dwFlags |= lib.DSBCAPS_CTRL3D dsbdesc.dwBufferBytes = self._buffer_size dsbdesc.lpwfxFormat = ctypes.pointer(wfx) dsb = lib.IDirectSoundBuffer() dsound.CreateSoundBuffer(dsbdesc, ctypes.byref(dsb), None) self._buffer = dsb self._buffer_size_secs = \ self._buffer_size / float(audio_format.bytes_per_second) def __del__(self): try: self._buffer.Release() except (NameError, AttributeError): pass def get_write_size(self): if not self._playing: return 0 play_cursor = lib.DWORD() self._buffer.GetCurrentPosition(play_cursor, None) play_cursor = play_cursor.value if self._write_cursor == play_cursor and self._buffer_playing: return 0 elif self._write_cursor < play_cursor: write_size = play_cursor - self._write_cursor else: write_size = self._buffer_size - self._write_cursor + play_cursor if write_size < self._update_buffer_size: return 0 return write_size def write(self, audio_data, length=None): # Pass audio_data=None, length>0 to write silence if length is None: write_size = self.get_write_size() length = min(audio_data.length, write_size) if length == 0: return 0 p1 = ctypes.c_void_p() l1 = lib.DWORD() p2 = ctypes.c_void_p() l2 = lib.DWORD() self._buffer.Lock(self._write_cursor, length, ctypes.byref(p1), l1, ctypes.byref(p2), l2, 0) assert length == l1.value + l2.value if audio_data: if self._write_cursor > self._play_cursor: wc = self._write_cursor else: wc = self._write_cursor + self._buffer_size self._timestamps.append((wc, audio_data.timestamp)) ctypes.memmove(p1, audio_data.data, l1.value) audio_data.consume(l1.value, self.audio_format) if l2.value: ctypes.memmove(p2, audio_data.data, l2.value) audio_data.consume(l2.value, self.audio_format) else: ctypes.memset(p1, 0, l1.value) if l2.value: ctypes.memset(p2, 0, l2.value) pass self._buffer.Unlock(p1, l1, p2, l2) self._write_cursor += length self._write_cursor %= self._buffer_size def write_eos(self): if self._write_cursor > self._play_cursor: wc = self._write_cursor else: wc = self._write_cursor + self._buffer_size self._timestamps.append((wc, 'eos')) def write_end(self): if not self._dirty_size: self._dirty_size = self._buffer_size def pump(self): # Update play cursor, check for wraparound and EOS markers play_cursor = lib.DWORD() self._buffer.GetCurrentPosition(play_cursor, None) if play_cursor.value < self._play_cursor: # Wrapped around self._buffer_time_pos -= self._buffer_size self._timestamps = \ [(a - self._buffer_size, t) for a, t in self._timestamps] self._play_cursor = play_cursor.value try: while self._timestamps[0][0] < self._play_cursor: pos, timestamp = self._timestamps.pop(0) if timestamp == 'eos': self._eos_count += 1 else: self._buffer_time = timestamp self._buffer_time_pos = pos except IndexError: pass self._timestamp = self._buffer_time + \ (self._play_cursor - self._buffer_time_pos) \ / float(self.audio_format.bytes_per_second) # Write silence if self._dirty_size: write_size = self.get_write_size() length = min(write_size, self._dirty_size) self.write(None, length) self._dirty_size -= length if self._dirty_size < 0: self._dirty_size = 0 if self._playing and not self._buffer_playing: self._buffer.Play(0, 0, lib.DSBPLAY_LOOPING) self._buffer_playing = True def get_time(self): return self._timestamp def play(self): if self._playing: return self._playing = True self._buffer.Play(0, 0, lib.DSBPLAY_LOOPING) self._buffer_playing = True self._write_cursor = 0 self._buffer.SetCurrentPosition(0) self._buffer_time = 0. self._buffer_time_pos = 0 def stop(self): if not self._playing: return self._playing = False self._buffer.Stop() self._buffer_playing = False def clear(self): self._eos_count = 0 self._eos_cursors = [] def clear_eos(self): if self._eos_count > 0: self._eos_count -= 1 return True return False def _get_source(self): if self._sources: return self._sources[0] return None class DirectSoundListener(Listener): def _set_volume(self, volume): self._volume = volume def _set_position(self, position): self._position = position def _set_velocity(self, velocity): self._velocity = velocity def _set_forward_orientation(self, orientation): self._forward_orientation = orientation def _set_up_orientation(self, orientation): self._up_orientation = orientation def _set_doppler_factor(self, factor): self._doppler_factor = factor def _set_speed_of_sound(self, speed_of_sound): self._speed_of_sound = speed_of_sound dsound = None def driver_init(): global dsound dsound = lib.IDirectSound() lib.DirectSoundCreate(None, ctypes.byref(dsound), None) # A trick used by mplayer.. use desktop as window handle since it would # be complex to use pyglet window handles (and what to do when application # is audio only?). hwnd = _user32.GetDesktopWindow() dsound.SetCooperativeLevel(hwnd, lib.DSSCL_NORMAL) driver_listener = DirectSoundListener() driver_audio_player_class = DirectSoundAudioPlayer Fix paste-o in directsound. Seeking is still a bit stuttery. #!/usr/bin/python # ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2007 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of the pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- '''Windows DirectSound audio implementation. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import time from pyglet.media import AudioPlayer, Listener, MediaException from pyglet.media.drivers.directsound import lib_dsound as lib from pyglet.window.win32 import _user32 class DirectSoundException(MediaException): pass class DirectSoundAudioPlayer(AudioPlayer): _buffer_size = 44800 * 1 _update_buffer_size = _buffer_size // 4 _buffer_size_secs = None def __init__(self, audio_format): super(DirectSoundAudioPlayer, self).__init__(audio_format) self._playing = False self._timestamp = 0. self._buffer = None self._buffer_playing = False self._play_cursor = 0 self._buffer_time = 0. # ts of buffer at buffer_time_pos self._buffer_time_pos = 0 self._write_cursor = 0 self._timestamps = [] self._eos_count = 0 self._dirty_size = 0 wfx = lib.WAVEFORMATEX() wfx.wFormatTag = lib.WAVE_FORMAT_PCM wfx.nChannels = audio_format.channels wfx.nSamplesPerSec = audio_format.sample_rate wfx.wBitsPerSample = audio_format.sample_size wfx.nBlockAlign = wfx.wBitsPerSample * wfx.nChannels // 8 wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign dsbdesc = lib.DSBUFFERDESC() dsbdesc.dwSize = ctypes.sizeof(dsbdesc) dsbdesc.dwFlags = (lib.DSBCAPS_GLOBALFOCUS | lib.DSBCAPS_GETCURRENTPOSITION2 | lib.DSBCAPS_CTRLVOLUME) if audio_format.channels == 1: dsbdesc.dwFlags |= lib.DSBCAPS_CTRL3D dsbdesc.dwBufferBytes = self._buffer_size dsbdesc.lpwfxFormat = ctypes.pointer(wfx) dsb = lib.IDirectSoundBuffer() dsound.CreateSoundBuffer(dsbdesc, ctypes.byref(dsb), None) self._buffer = dsb self._buffer_size_secs = \ self._buffer_size / float(audio_format.bytes_per_second) def __del__(self): try: self._buffer.Release() except (NameError, AttributeError): pass def get_write_size(self): if not self._playing: return 0 play_cursor = lib.DWORD() self._buffer.GetCurrentPosition(play_cursor, None) play_cursor = play_cursor.value if self._write_cursor == play_cursor and self._buffer_playing: return 0 elif self._write_cursor < play_cursor: write_size = play_cursor - self._write_cursor else: write_size = self._buffer_size - self._write_cursor + play_cursor if write_size < self._update_buffer_size: return 0 return write_size def write(self, audio_data, length=None): # Pass audio_data=None, length>0 to write silence if length is None: write_size = self.get_write_size() length = min(audio_data.length, write_size) if length == 0: return 0 p1 = ctypes.c_void_p() l1 = lib.DWORD() p2 = ctypes.c_void_p() l2 = lib.DWORD() self._buffer.Lock(self._write_cursor, length, ctypes.byref(p1), l1, ctypes.byref(p2), l2, 0) assert length == l1.value + l2.value if audio_data: if self._write_cursor > self._play_cursor: wc = self._write_cursor else: wc = self._write_cursor + self._buffer_size self._timestamps.append((wc, audio_data.timestamp)) ctypes.memmove(p1, audio_data.data, l1.value) audio_data.consume(l1.value, self.audio_format) if l2.value: ctypes.memmove(p2, audio_data.data, l2.value) audio_data.consume(l2.value, self.audio_format) else: ctypes.memset(p1, 0, l1.value) if l2.value: ctypes.memset(p2, 0, l2.value) pass self._buffer.Unlock(p1, l1, p2, l2) self._write_cursor += length self._write_cursor %= self._buffer_size def write_eos(self): if self._write_cursor > self._play_cursor: wc = self._write_cursor else: wc = self._write_cursor + self._buffer_size self._timestamps.append((wc, 'eos')) def write_end(self): if not self._dirty_size: self._dirty_size = self._buffer_size def pump(self): # Update play cursor, check for wraparound and EOS markers play_cursor = lib.DWORD() self._buffer.GetCurrentPosition(play_cursor, None) if play_cursor.value < self._play_cursor: # Wrapped around self._buffer_time_pos -= self._buffer_size self._timestamps = \ [(a - self._buffer_size, t) for a, t in self._timestamps] self._play_cursor = play_cursor.value try: while self._timestamps[0][0] < self._play_cursor: pos, timestamp = self._timestamps.pop(0) if timestamp == 'eos': self._eos_count += 1 else: self._buffer_time = timestamp self._buffer_time_pos = pos except IndexError: pass self._timestamp = self._buffer_time + \ (self._play_cursor - self._buffer_time_pos) \ / float(self.audio_format.bytes_per_second) # Write silence if self._dirty_size: write_size = self.get_write_size() length = min(write_size, self._dirty_size) self.write(None, length) self._dirty_size -= length if self._dirty_size < 0: self._dirty_size = 0 if self._playing and not self._buffer_playing: self._buffer.Play(0, 0, lib.DSBPLAY_LOOPING) self._buffer_playing = True def get_time(self): return self._timestamp def play(self): if self._playing: return self._playing = True self._buffer.Play(0, 0, lib.DSBPLAY_LOOPING) self._buffer_playing = True def stop(self): if not self._playing: return self._playing = False self._buffer.Stop() self._buffer_playing = False def clear(self): self._eos_count = 0 self._timestamps = [] self._write_cursor = 0 self._buffer.SetCurrentPosition(0) self._buffer_time = 0. self._buffer_time_pos = 0 def clear_eos(self): if self._eos_count > 0: self._eos_count -= 1 return True return False def _get_source(self): if self._sources: return self._sources[0] return None class DirectSoundListener(Listener): def _set_volume(self, volume): self._volume = volume def _set_position(self, position): self._position = position def _set_velocity(self, velocity): self._velocity = velocity def _set_forward_orientation(self, orientation): self._forward_orientation = orientation def _set_up_orientation(self, orientation): self._up_orientation = orientation def _set_doppler_factor(self, factor): self._doppler_factor = factor def _set_speed_of_sound(self, speed_of_sound): self._speed_of_sound = speed_of_sound dsound = None def driver_init(): global dsound dsound = lib.IDirectSound() lib.DirectSoundCreate(None, ctypes.byref(dsound), None) # A trick used by mplayer.. use desktop as window handle since it would # be complex to use pyglet window handles (and what to do when application # is audio only?). hwnd = _user32.GetDesktopWindow() dsound.SetCooperativeLevel(hwnd, lib.DSSCL_NORMAL) driver_listener = DirectSoundListener() driver_audio_player_class = DirectSoundAudioPlayer