signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def get_log_report(log: Union[logging.Logger,<EOL>logging.PlaceHolder]) -> Dict[str, Any]:
if isinstance(log, logging.Logger):<EOL><INDENT>return {<EOL>'<STR_LIT>': str(log),<EOL>'<STR_LIT>': log.level,<EOL>'<STR_LIT>': log.disabled,<EOL>'<STR_LIT>': log.propagate,<EOL>'<STR_LIT>': str(log.parent),<EOL>'<STR_LIT>': str(log.manager),<EOL>'<STR_LIT>': [get_handler_report(h) for h in log.handlers],<EOL>}<EOL><D...
Returns information on a log, as a dictionary. For debugging.
f14667:m14
def print_report_on_all_logs() -> None:
d = {}<EOL>for name, obj in logging.Logger.manager.loggerDict.items():<EOL><INDENT>d[name] = get_log_report(obj)<EOL><DEDENT>rootlogger = logging.getLogger()<EOL>d['<STR_LIT>'] = get_log_report(rootlogger)<EOL>print(json.dumps(d, sort_keys=True, indent=<NUM_LIT:4>, separators=('<STR_LIT:U+002C>', '<STR_LIT>')))<EOL>
Use :func:`print` to report information on all logs.
f14667:m15
def set_level_for_logger_and_its_handlers(log: logging.Logger,<EOL>level: int) -> None:
log.setLevel(level)<EOL>for h in log.handlers: <EOL><INDENT>h.setLevel(level)<EOL><DEDENT>
Set a log level for a log and all its handlers. Args: log: log to modify level: log level to set
f14667:m16
def get_brace_style_log_with_null_handler(name: str) -> BraceStyleAdapter:
log = logging.getLogger(name)<EOL>log.addHandler(logging.NullHandler())<EOL>return BraceStyleAdapter(log)<EOL>
For use by library functions. Returns a log with the specifed name that has a null handler attached, and a :class:`BraceStyleAdapter`.
f14667:m17
def __init__(self, append_br: bool = False,<EOL>replace_nl_with_br: bool = True) -> None:
super().__init__(<EOL>fmt='<STR_LIT>',<EOL>datefmt='<STR_LIT>',<EOL>style='<STR_LIT:%>'<EOL>)<EOL>self.append_br = append_br<EOL>self.replace_nl_with_br = replace_nl_with_br<EOL>
r""" Args: append_br: append ``<br>`` to each line? replace_nl_with_br: replace ``\n`` with ``<br>`` in messages? See https://hg.python.org/cpython/file/3.5/Lib/logging/__init__.py
f14667:c0:m0
def format(self, record: logging.LogRecord) -> str:
<EOL>super().format(record)<EOL>record.asctime = self.formatTime(record, self.datefmt)<EOL>bg_col = self.log_background_colors[record.levelno]<EOL>msg = escape(record.getMessage())<EOL>if self.replace_nl_with_br:<EOL><INDENT>msg = msg.replace("<STR_LIT:\n>", "<STR_LIT>")<EOL><DEDENT>html = (<EOL>'<STR_LIT>'<EOL>'<STR_L...
Internal function to format the :class:`LogRecord` as HTML. See https://docs.python.org/3.4/library/logging.html#logging.LogRecord
f14667:c0:m1
def emit(self, record: logging.LogRecord) -> None:
<EOL>try:<EOL><INDENT>html = self.format(record)<EOL>self.logfunction(html)<EOL><DEDENT>except: <EOL><INDENT>self.handleError(record)<EOL><DEDENT>
Internal function to process a :class:`LogRecord`.
f14667:c1:m1
def __init__(self,<EOL>logger: logging.Logger,<EOL>pass_special_logger_args: bool = True,<EOL>strip_special_logger_args_from_fmt: bool = False) -> None:
<EOL>super().__init__(logger=logger, extra=None)<EOL>self.pass_special_logger_args = pass_special_logger_args<EOL>self.strip_special_logger_args_from_fmt = strip_special_logger_args_from_fmt <EOL>sig = signature(self.logger._log)<EOL>self.logargnames = [p.name for p in sig.parameters.values()<EOL>if p.kind == Paramete...
Wraps a logger so we can use ``{}``-style string formatting. Args: logger: a logger pass_special_logger_args: should we continue to pass any special arguments to the logger itself? True is standard; False probably brings a slight performance benefit, but prevents log.exception()...
f14667:c3:m0
def get_external_command_output(command: str) -> bytes:
args = shlex.split(command)<EOL>ret = subprocess.check_output(args) <EOL>return ret<EOL>
Takes a command-line command, executes it, and returns its ``stdout`` output. Args: command: command string Returns: output from the command as ``bytes``
f14668:m0
def get_pipe_series_output(commands: Sequence[str],<EOL>stdinput: BinaryIO = None) -> bytes:
<EOL>processes = [] <EOL>for i in range(len(commands)):<EOL><INDENT>if i == <NUM_LIT:0>: <EOL><INDENT>processes.append(<EOL>subprocess.Popen(<EOL>shlex.split(commands[i]),<EOL>stdin=subprocess.PIPE,<EOL>stdout=subprocess.PIPE<EOL>)<EOL>)<EOL><DEDENT>else: <EOL><INDENT>processes.append(<EOL>subprocess.Popen(<EOL>shle...
Get the output from a piped series of commands. Args: commands: sequence of command strings stdinput: optional ``stdin`` data to feed into the start of the pipe Returns: ``stdout`` from the end of the pipe
f14668:m1
def launch_external_file(filename: str, raise_if_fails: bool = False) -> None:
log.info("<STR_LIT>", filename)<EOL>try:<EOL><INDENT>if sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>cmdargs = ["<STR_LIT>", filename]<EOL>subprocess.call(cmdargs)<EOL><DEDENT>else:<EOL><INDENT>os.startfile(filename)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>log.critical("<STR_LIT>",<EOL>filename, str...
Launches a file using the operating system's standard launcher. Args: filename: file to launch raise_if_fails: raise any exceptions from ``subprocess.call(["xdg-open", filename])`` (Linux) or ``os.startfile(filename)`` (otherwise)? If not, exceptions are suppressed.
f14668:m2
def kill_proc_tree(pid: int,<EOL>including_parent: bool = True,<EOL>timeout_s: float = <NUM_LIT:5>)-> Tuple[Set[psutil.Process], Set[psutil.Process]]:
<EOL>t = psutil.Process(pid)<EOL>ll = parent.children(recursive=True) <EOL>cluding_parent:<EOL>o_kill.append(parent)<EOL>roc in to_kill:<EOL>roc.kill() <EOL><INDENT>still_alive = psutil.wait_procs(to_kill, timeout=timeout_s)<EOL><DEDENT>n gone, still_alive<EOL>
Kills a tree of processes, starting with the parent. Slightly modified from https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows. Args: pid: process ID of the parent including_parent: kill the parent too? timeout_s: timeout to wait for processes to close Returns: ...
f14668:m3
def _getch_windows() -> str:
return msvcrt.getch().decode('<STR_LIT:utf-8>')<EOL>
Under Windows, wets a single character from standard input. Does not echo to the screen.
f14669:m0
def _getch_unix() -> str:
return sys.stdin.read(<NUM_LIT:1>)<EOL>
Under UNIX, gets a single character from standard input. Does not echo to the screen. Note that the terminal will have been pre-configured, below.
f14669:m1
def _kbhit_windows() -> bool:
return msvcrt.kbhit()<EOL>
Under Windows: is a keystroke available?
f14669:m2
def _kbhit_unix() -> bool:
dr, dw, de = select.select([sys.stdin], [], [], <NUM_LIT:0>)<EOL>return dr != []<EOL>
Under UNIX: is a keystroke available?
f14669:m3
def set_normal_term() -> None:
termios.tcsetattr(_fd, termios.TCSAFLUSH, _old_term)<EOL>
Under UNIX: switch to a normal terminal. (Compare :func:`set_curses_term`.)
f14669:m4
def set_curses_term() -> None:
termios.tcsetattr(_fd, termios.TCSAFLUSH, _new_term)<EOL>
Under UNIX: switch to an unbuffered, curses-style terminal. (Compare :func:`set_normal_term`.)
f14669:m5
def get_config_string_option(parser: ConfigParser,<EOL>section: str,<EOL>option: str,<EOL>default: str = None) -> str:
if not parser.has_section(section):<EOL><INDENT>raise ValueError("<STR_LIT>" + section)<EOL><DEDENT>return parser.get(section, option, fallback=default)<EOL>
Retrieves a string value from a parser. Args: parser: instance of :class:`ConfigParser` section: section name within config file option: option (variable) name within that section default: value to return if option is absent Returns: string value Raises: ValueError: if the section is absent
f14670:m0
def read_config_string_options(obj: Any,<EOL>parser: ConfigParser,<EOL>section: str,<EOL>options: Iterable[str],<EOL>default: str = None) -> None:
<EOL>for o in options:<EOL><INDENT>setattr(obj, o, get_config_string_option(parser, section, o,<EOL>default=default))<EOL><DEDENT>
Reads config options and writes them as attributes of ``obj``, with attribute names as per ``options``. Args: obj: the object to modify parser: instance of :class:`ConfigParser` section: section name within config file options: option (variable) names within that section default: value to use for a...
f14670:m1
def get_config_multiline_option(parser: ConfigParser,<EOL>section: str,<EOL>option: str,<EOL>default: List[str] = None) -> List[str]:
default = default or []<EOL>if not parser.has_section(section):<EOL><INDENT>raise ValueError("<STR_LIT>" + section)<EOL><DEDENT>try:<EOL><INDENT>multiline = parser.get(section, option)<EOL>values = [x.strip() for x in multiline.splitlines() if x.strip()]<EOL>return values<EOL><DEDENT>except NoOptionError:<EOL><INDENT>r...
Retrieves a multi-line string value from a parser as a list of strings (one per line, ignoring blank lines). Args: parser: instance of :class:`ConfigParser` section: section name within config file option: option (variable) name within that section default: value to return if option is absent (``None``...
f14670:m2
def read_config_multiline_options(obj: Any,<EOL>parser: ConfigParser,<EOL>section: str,<EOL>options: Iterable[str]) -> None:
for o in options:<EOL><INDENT>setattr(obj, o, get_config_multiline_option(parser, section, o))<EOL><DEDENT>
This is to :func:`read_config_string_options` as :func:`get_config_multiline_option` is to :func:`get_config_string_option`.
f14670:m3
def get_config_bool_option(parser: ConfigParser,<EOL>section: str,<EOL>option: str,<EOL>default: bool = None) -> bool:
if not parser.has_section(section):<EOL><INDENT>raise ValueError("<STR_LIT>" + section)<EOL><DEDENT>return parser.getboolean(section, option, fallback=default)<EOL>
Retrieves a boolean value from a parser. Args: parser: instance of :class:`ConfigParser` section: section name within config file option: option (variable) name within that section default: value to return if option is absent Returns: string value Raises: ValueError: if the section is absent
f14670:m4
def get_config_parameter(config: ConfigParser,<EOL>section: str,<EOL>param: str,<EOL>fn: Callable[[Any], Any],<EOL>default: Any) -> Any:
try:<EOL><INDENT>value = fn(config.get(section, param))<EOL><DEDENT>except (TypeError, ValueError, NoOptionError):<EOL><INDENT>log.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", param, section, default)<EOL>if default is None:<EOL><INDENT>value = default<EOL><DEDENT>else:<EOL><INDENT>value = fn(default)<EOL><DEDENT><DEDENT>...
Fetch parameter from ``configparser`` ``.INI`` file. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section fn: function to apply to string parameter (e.g. ``int``) default: default value Returns: parameter value, or ``None``...
f14670:m5
def get_config_parameter_boolean(config: ConfigParser,<EOL>section: str,<EOL>param: str,<EOL>default: bool) -> bool:
try:<EOL><INDENT>value = config.getboolean(section, param)<EOL><DEDENT>except (TypeError, ValueError, NoOptionError):<EOL><INDENT>log.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", param, section, default)<EOL>value = default<EOL><DEDENT>return value<EOL>
Get Boolean parameter from ``configparser`` ``.INI`` file. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value Returns: parameter value, or default
f14670:m6
def get_config_parameter_loglevel(config: ConfigParser,<EOL>section: str,<EOL>param: str,<EOL>default: int) -> int:
try:<EOL><INDENT>value = config.get(section, param).lower()<EOL>if value == "<STR_LIT>":<EOL><INDENT>return logging.DEBUG <EOL><DEDENT>elif value == "<STR_LIT:info>":<EOL><INDENT>return logging.INFO<EOL><DEDENT>elif value in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>return logging.WARN<EOL><DEDENT>elif value == "<STR_LI...
Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g. mapping ``'debug'`` to ``logging.DEBUG``. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value Returns: parameter value, or default
f14670:m7
def get_config_parameter_multiline(config: ConfigParser,<EOL>section: str,<EOL>param: str,<EOL>default: List[str]) -> List[str]:
try:<EOL><INDENT>multiline = config.get(section, param)<EOL>lines = [x.strip() for x in multiline.splitlines()]<EOL>return [line for line in lines if line]<EOL><DEDENT>except (TypeError, ValueError, NoOptionError):<EOL><INDENT>log.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", param, section, default)<EOL>return default<EOL...
Get multi-line string parameter from ``configparser`` ``.INI`` file, as a list of strings (one per line, ignoring blank lines). Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value Returns: parameter value...
f14670:m8
def download_if_not_exists(url: str, filename: str,<EOL>skip_cert_verify: bool = True,<EOL>mkdir: bool = True) -> None:
if os.path.isfile(filename):<EOL><INDENT>log.info("<STR_LIT>", filename)<EOL>return<EOL><DEDENT>if mkdir:<EOL><INDENT>directory, basename = os.path.split(os.path.abspath(filename))<EOL>mkdir_p(directory)<EOL><DEDENT>download(url=url,<EOL>filename=filename,<EOL>skip_cert_verify=skip_cert_verify)<EOL>
Downloads a URL to a file, unless the file already exists.
f14672:m0
def git_clone(prettyname: str, url: str, directory: str,<EOL>branch: str = None,<EOL>commit: str = None,<EOL>clone_options: List[str] = None,<EOL>run_func: Callable[[List[str]], Any] = None) -> bool:
run_func = run_func or subprocess.check_call<EOL>clone_options = clone_options or [] <EOL>if os.path.isdir(directory):<EOL><INDENT>log.info("<STR_LIT>"<EOL>"<STR_LIT>".format(prettyname, directory))<EOL>return False<EOL><DEDENT>log.info("<STR_LIT>",<EOL>prettyname, url, directory)<EOL>require_executable(GIT)<EOL>gitar...
Fetches a Git repository, unless we have it already. Args: prettyname: name to display to user url: URL directory: destination directory branch: repository branch commit: repository commit tag clone_options: additional options to pass to ``git clone`` run_func: function to use to call an ex...
f14672:m1
def untar_to_directory(tarfile: str,<EOL>directory: str,<EOL>verbose: bool = False,<EOL>gzipped: bool = False,<EOL>skip_if_dir_exists: bool = True,<EOL>run_func: Callable[[List[str]], Any] = None,<EOL>chdir_via_python: bool = True) -> None:
if skip_if_dir_exists and os.path.isdir(directory):<EOL><INDENT>log.info("<STR_LIT>",<EOL>tarfile, directory)<EOL>return<EOL><DEDENT>log.info("<STR_LIT>", tarfile, directory)<EOL>require_executable(TAR)<EOL>mkdir_p(directory)<EOL>args = [TAR, "<STR_LIT>"] <EOL>if verbose:<EOL><INDENT>args.append("<STR_LIT>") <EOL><DE...
Unpacks a TAR file into a specified directory. Args: tarfile: filename of the ``.tar`` file directory: destination directory verbose: be verbose? gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file? skip_if_dir_exists: don't do anything if the destrination directory exists? r...
f14672:m2
def make_copy_paste_env(env: Dict[str, str]) -> str:
windows = platform.system() == "<STR_LIT>"<EOL>cmd = "<STR_LIT>" if windows else "<STR_LIT>"<EOL>return (<EOL>"<STR_LIT:\n>".join(<EOL>"<STR_LIT>".format(<EOL>cmd=cmd,<EOL>k=k,<EOL>v=env[k] if windows else subprocess.list2cmdline([env[k]])<EOL>) for k in sorted(env.keys())<EOL>)<EOL>)<EOL>
Convert an environment into a set of commands that can be copied/pasted, on the build platform, to recreate that environment.
f14672:m3
def run(args: List[str],<EOL>env: Dict[str, str] = None,<EOL>capture_stdout: bool = False,<EOL>echo_stdout: bool = True,<EOL>capture_stderr: bool = False,<EOL>echo_stderr: bool = True,<EOL>debug_show_env: bool = True,<EOL>encoding: str = sys.getdefaultencoding(),<EOL>allow_failure: bool = False,<EOL>**kwargs) -> Tuple[...
cwd = os.getcwd()<EOL>copy_paste_cmd = subprocess.list2cmdline(args)<EOL>csep = "<STR_LIT:=>" * <NUM_LIT><EOL>esep = "<STR_LIT:->" * <NUM_LIT><EOL>effective_env = env or os.environ<EOL>if debug_show_env:<EOL><INDENT>log.debug(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(esep=esep, env=make_co...
Runs an external process, announcing it. Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not retrieved, the output will be visible to the user). Args: args: list of command-line arguments (the first being the executable) env: operating system environment to use (if ``None``, the current OS ...
f14672:m4
def fetch(args: List[str], env: Dict[str, str] = None,<EOL>encoding: str = sys.getdefaultencoding()) -> str:
stdout, _ = run(args, env=env, capture_stdout=True,<EOL>echo_stdout=False, encoding=encoding)<EOL>log.debug(stdout)<EOL>return stdout<EOL>
Run a command and returns its stdout. Args: args: the command-line arguments env: the operating system environment to use encoding: the encoding to use for ``stdout`` Returns: the command's ``stdout`` output
f14672:m5
def launch_slurm(jobname: str,<EOL>cmd: str,<EOL>memory_mb: int,<EOL>project: str,<EOL>qos: str,<EOL>email: str,<EOL>duration: timedelta,<EOL>tasks_per_node: int,<EOL>cpus_per_task: int,<EOL>partition: str = "<STR_LIT>",<EOL>modules: List[str] = None,<EOL>directory: str = os.getcwd(),<EOL>encoding: str = "<STR_LIT:asci...
if partition:<EOL><INDENT>partition_cmd = "<STR_LIT>".format(partition)<EOL><DEDENT>else:<EOL><INDENT>partition_cmd = "<STR_LIT>"<EOL><DEDENT>if modules is None:<EOL><INDENT>modules = ["<STR_LIT>"]<EOL><DEDENT>log.info("<STR_LIT>", jobname)<EOL>script = """<STR_LIT>""".format( <EOL>cmd=cmd,<EOL>cpus_per_task=cpus_per_...
Launch a job into the SLURM environment. Args: jobname: name of the job cmd: command to be executed memory_mb: maximum memory requirement per process (Mb) project: project name qos: quality-of-service name email: user's e-mail address duration: maximum duration per job tasks_per_node: t...
f14673:m0
def launch_cambridge_hphi(<EOL>jobname: str,<EOL>cmd: str,<EOL>memory_mb: int,<EOL>qos: str,<EOL>email: str,<EOL>duration: timedelta,<EOL>cpus_per_task: int,<EOL>project: str = "<STR_LIT>",<EOL>tasks_per_node: int = <NUM_LIT:1>,<EOL>partition: str = "<STR_LIT>", <EOL>modules: List[str] = None,<EOL>directory: str = os....
if modules is None:<EOL><INDENT>modules = ["<STR_LIT>"]<EOL><DEDENT>launch_slurm(<EOL>cmd=cmd,<EOL>cpus_per_task=cpus_per_task,<EOL>directory=directory,<EOL>duration=duration,<EOL>email=email,<EOL>encoding=encoding,<EOL>jobname=jobname,<EOL>memory_mb=memory_mb,<EOL>modules=modules,<EOL>partition=partition,<EOL>project=...
Specialization of :func:`launch_slurm` (q.v.) with defaults for the University of Cambridge WBIC HPHI.
f14673:m1
def normalized_frequency(f: float, sampling_freq: float) -> float:
<EOL>n f / (sampling_freq / <NUM_LIT>)<EOL>
Returns a normalized frequency: Args: f: frequency :math:`f` sampling_freq: sampling frequency :math:`f_s` Returns: normalized frequency .. math:: f_n = f / (f_s / 2) Principles: - if maximum frequency of interest is :math:`f`, then you should sample at the Nyquist rate of :math:...
f14674:m0
def lowpass_filter(data: FLOATS_TYPE,<EOL>sampling_freq_hz: float,<EOL>cutoff_freq_hz: float,<EOL>numtaps: int) -> FLOATS_TYPE:
coeffs = firwin(<EOL>numtaps=numtaps,<EOL>cutoff=normalized_frequency(cutoff_freq_hz, sampling_freq_hz),<EOL>pass_zero=True<EOL>) <EOL>filtered_data = lfilter(b=coeffs, a=<NUM_LIT:1.0>, x=data)<EOL>return filtered_data<EOL>
Apply a low-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :math:`f_s`, in Hz (or other consistent units) cutoff_freq_hz: filter cutoff frequency in Hz (or other consistent units) numtaps: number of filter taps Returns: filtered da...
f14674:m1
def highpass_filter(data: FLOATS_TYPE,<EOL>sampling_freq_hz: float,<EOL>cutoff_freq_hz: float,<EOL>numtaps: int) -> FLOATS_TYPE:
coeffs = firwin(<EOL>numtaps=numtaps,<EOL>cutoff=normalized_frequency(cutoff_freq_hz, sampling_freq_hz),<EOL>pass_zero=False<EOL>)<EOL>filtered_data = lfilter(b=coeffs, a=<NUM_LIT:1.0>, x=data)<EOL>return filtered_data<EOL>
Apply a high-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :math:`f_s`, in Hz (or other consistent units) cutoff_freq_hz: filter cutoff frequency in Hz (or other consistent units) numtaps: number of filter taps Returns: filtered d...
f14674:m2
def bandpass_filter(data: FLOATS_TYPE,<EOL>sampling_freq_hz: float,<EOL>lower_freq_hz: float,<EOL>upper_freq_hz: float,<EOL>numtaps: int) -> FLOATS_TYPE:
f1 = normalized_frequency(lower_freq_hz, sampling_freq_hz)<EOL>f2 = normalized_frequency(upper_freq_hz, sampling_freq_hz)<EOL>coeffs = firwin(<EOL>numtaps=numtaps,<EOL>cutoff=[f1, f2],<EOL>pass_zero=False<EOL>)<EOL>filtered_data = lfilter(b=coeffs, a=<NUM_LIT:1.0>, x=data)<EOL>return filtered_data<EOL>
Apply a band-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :math:`f_s`, in Hz (or other consistent units) lower_freq_hz: filter cutoff lower frequency in Hz (or other consistent units) upper_freq_hz: filter cutoff upper frequency in Hz...
f14674:m3
def notch_filter(data: FLOATS_TYPE,<EOL>sampling_freq_hz: float,<EOL>notch_freq_hz: float,<EOL>quality_factor: float) -> FLOATS_TYPE:
b, a = iirnotch(<EOL>w0=normalized_frequency(notch_freq_hz, sampling_freq_hz),<EOL>Q=quality_factor<EOL>)<EOL>filtered_data = lfilter(b=b, a=a, x=data)<EOL>return filtered_data<EOL>
Design and use a notch (band reject) filter to filter the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :math:`f_s`, in Hz (or other consistent units) notch_freq_hz: notch frequency, in Hz (or other consistent units) quality_factor: notch filter quality ...
f14674:m4
def formatdt(date: datetime.date, include_time: bool = True) -> str:
if include_time:<EOL><INDENT>return date.strftime("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>return date.strftime("<STR_LIT>")<EOL><DEDENT>
Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy with no timezone (or, if ``include_time`` is ``False``, omit the time).
f14675:m0
def convert_duration(duration: datetime.timedelta,<EOL>units: str) -> Optional[float]:
if duration is None:<EOL><INDENT>return None<EOL><DEDENT>s = duration.total_seconds()<EOL>if units in ['<STR_LIT:s>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>return s<EOL><DEDENT>if units in ['<STR_LIT:m>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>return s / SECONDS_PER_MINUTE<EOL><DEDENT>if units in ['<STR_LIT:h>', '<STR...
Convert a ``datetime.timedelta`` object -- a duration -- into other units. Possible units: ``s``, ``sec``, ``seconds`` ``m``, ``min``, ``minutes`` ``h``, ``hr``, ``hours`` ``d``, ``days`` ``w``, ``weeks`` ``y``, ``years``
f14675:m1
def is_bank_holiday(date: datetime.date) -> bool:
return date in BANK_HOLIDAYS<EOL>
Is the specified date (a ``datetime.date`` object) a UK bank holiday? Uses the ``BANK_HOLIDAYS`` list.
f14675:m2
def is_weekend(date: datetime.date) -> bool:
return date.weekday() in [<NUM_LIT:5>, <NUM_LIT:6>]<EOL>
Is the specified date (a ``datetime.date`` object) a weekend?
f14675:m3
def is_saturday(date: datetime.date) -> bool:
return date.weekday() == <NUM_LIT:5><EOL>
Is the specified date (a ``datetime.date`` object) a Saturday?
f14675:m4
def is_sunday(date: datetime.date) -> bool:
return date.weekday() == <NUM_LIT:6><EOL>
Is the specified date (a ``datetime.date`` object) a Sunday?
f14675:m5
def is_normal_working_day(date: datetime.date) -> bool:
return not(is_weekend(date) or is_bank_holiday(date))<EOL>
Is the specified date (a ``datetime.date`` object) a normal working day, i.e. not a weekend or a bank holiday?
f14675:m6
def __init__(self, start: datetime.datetime,<EOL>end: datetime.datetime) -> None:
if start is None or end is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if start > end:<EOL><INDENT>(start, end) = (end, start)<EOL><DEDENT>self.start = start<EOL>self.end = end<EOL>
Creates the interval.
f14675:c0:m0
def __repr__(self) -> str:
return "<STR_LIT>".format(<EOL>repr(self.start), repr(self.end))<EOL>
Returns the canonical string representation of the object.
f14675:c0:m1
def __str__(self) -> str:
return "<STR_LIT>".format(formatdt(self.start), formatdt(self.end))<EOL>
Returns a string representation of the object.
f14675:c0:m2
def __add__(self, value: datetime.timedelta) -> "<STR_LIT>":
return Interval(self.start + value, self.end + value)<EOL>
Adds a constant (``datetime.timedelta`` object) to the interval's start and end. Returns the new :class:`Interval`.
f14675:c0:m3
def __lt__(self, other: "<STR_LIT>") -> bool:
return self.start < other.start<EOL>
Allows sorting (on start time).
f14675:c0:m4
def copy(self) -> "<STR_LIT>":
return Interval(self.start, self.end)<EOL>
Returns a copy of the interval.
f14675:c0:m5
def overlaps(self, other: "<STR_LIT>") -> bool:
return not(self.end <= other.start or self.start >= other.end)<EOL>
Does this interval overlap the other? Overlap: .. code-block:: none S--------S S---S S---S O---O O---O O---O Simpler method of testing is for non-overlap! .. code-block:: none S---S S---S O---O O---O
f14675:c0:m6
def contiguous(self, other: "<STR_LIT>") -> bool:
return not(self.end < other.start or self.start > other.end)<EOL>
Does this interval overlap or touch the other?
f14675:c0:m7
def contains(self, time: datetime.datetime,<EOL>inclusive: bool = True) -> bool:
if inclusive:<EOL><INDENT>return self.start <= time <= self.end<EOL><DEDENT>else:<EOL><INDENT>return self.start < time < self.end<EOL><DEDENT>
Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks?
f14675:c0:m8
def within(self, other: "<STR_LIT>", inclusive: bool = True) -> bool:
if not other:<EOL><INDENT>return False<EOL><DEDENT>if inclusive:<EOL><INDENT>return self.start >= other.start and self.end <= other.end<EOL><DEDENT>else:<EOL><INDENT>return self.start > other.start and self.end < other.end<EOL><DEDENT>
Is this interval contained within the other? Args: other: the :class:`Interval` to check inclusive: use inclusive rather than exclusive range checks?
f14675:c0:m9
def union(self, other: "<STR_LIT>") -> "<STR_LIT>":
return Interval(<EOL>min(self.start, other.start),<EOL>max(self.end, other.end)<EOL>)<EOL>
Returns an interval spanning the extent of this and the ``other``.
f14675:c0:m10
def intersection(self, other: "<STR_LIT>") -> Optional["<STR_LIT>"]:
if not self.contiguous(other):<EOL><INDENT>return None<EOL><DEDENT>return Interval(<EOL>max(self.start, other.start),<EOL>min(self.end, other.end)<EOL>)<EOL>
Returns an :class:`Interval` representing the intersection of this and the ``other``, or ``None`` if they don't overlap.
f14675:c0:m11
def cut(self, times: Union[datetime.datetime,<EOL>List[datetime.datetime]]) -> List["<STR_LIT>"]:
if not isinstance(times, list):<EOL><INDENT>time = times<EOL>if not self.contains(time):<EOL><INDENT>return []<EOL><DEDENT>return [<EOL>Interval(self.start, time),<EOL>Interval(time, self.end)<EOL>]<EOL><DEDENT>else:<EOL><INDENT>times = [t for t in times if self.contains(t)] <EOL>times.sort()<EOL>times = [self.start] ...
Returns a list of intervals produced by using times (a list of ``datetime.datetime`` objects, or a single such object) as a set of knives to slice this interval.
f14675:c0:m12
def duration(self) -> datetime.timedelta:
return self.end - self.start<EOL>
Returns a datetime.timedelta object representing the duration of this interval.
f14675:c0:m13
def duration_in(self, units: str) -> float:
return convert_duration(self.duration(), units)<EOL>
Returns the duration of this interval in the specified units, as per :func:`convert_duration`.
f14675:c0:m14
@staticmethod<EOL><INDENT>def wholeday(date: datetime.date) -> "<STR_LIT>":<DEDENT>
start = datetime.datetime.combine(date, datetime.time())<EOL>return Interval(<EOL>start,<EOL>start + datetime.timedelta(days=<NUM_LIT:1>)<EOL>)<EOL>
Returns an :class:`Interval` covering the date given (midnight at the start of that day to midnight at the start of the next day).
f14675:c0:m15
@staticmethod<EOL><INDENT>def daytime(date: datetime.date,<EOL>daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),<EOL>nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H))-> "<STR_LIT>":<DEDENT>
return Interval(<EOL>datetime.datetime.combine(date, daybreak),<EOL>datetime.datetime.combine(date, nightfall),<EOL>)<EOL>
Returns an :class:`Interval` representing daytime on the date given.
f14675:c0:m16
@staticmethod<EOL><INDENT>def dayspan(startdate: datetime.date,<EOL>enddate: datetime.date,<EOL>include_end: bool = True) -> Optional["<STR_LIT>"]:<DEDENT>
if enddate < startdate:<EOL><INDENT>return None<EOL><DEDENT>if enddate == startdate and include_end:<EOL><INDENT>return None<EOL><DEDENT>start_dt = datetime.datetime.combine(startdate, datetime.time())<EOL>end_dt = datetime.datetime.combine(enddate, datetime.time())<EOL>if include_end:<EOL><INDENT>end_dt += datetime.ti...
Returns an :class:`Interval` representing the date range given, from midnight at the start of the first day to midnight at the end of the last (i.e. at the start of the next day after the last), or if include_end is False, 24h before that. If the parameters are invalid, returns ``None``.
f14675:c0:m17
def component_on_date(self, date: datetime.date) -> Optional["<STR_LIT>"]:
return self.intersection(Interval.wholeday(date))<EOL>
Returns the part of this interval that falls on the date given, or ``None`` if the interval doesn't have any part during that date.
f14675:c0:m18
def day_night_duration(<EOL>self,<EOL>daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),<EOL>nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H))-> Tuple[datetime.timedelta, datetime.timedelta]:
daytotal = datetime.timedelta()<EOL>nighttotal = datetime.timedelta()<EOL>startdate = self.start.date()<EOL>enddate = self.end.date()<EOL>ndays = (enddate - startdate).days + <NUM_LIT:1><EOL>for i in range(ndays):<EOL><INDENT>date = startdate + datetime.timedelta(days=i)<EOL>component = self.component_on_date(date)<EOL...
Returns a ``(day, night)`` tuple of ``datetime.timedelta`` objects giving the duration of this interval that falls into day and night respectively.
f14675:c0:m19
def duration_outside_nwh(<EOL>self,<EOL>starttime: datetime.time = datetime.time(NORMAL_DAY_START_H),<EOL>endtime: datetime.time = datetime.time(NORMAL_DAY_END_H),<EOL>weekdays_only: bool = False,<EOL>weekends_only: bool = False) -> datetime.timedelta:
if weekdays_only and weekends_only:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>ooh = datetime.timedelta() <EOL>startdate = self.start.date()<EOL>enddate = self.end.date()<EOL>ndays = (enddate - startdate).days + <NUM_LIT:1><EOL>for i in range(ndays):<EOL><INDENT>date = startdate + datetime.timedelta(days=i)...
Returns a duration (a ``datetime.timedelta`` object) representing the number of hours outside normal working hours. This is not simply a subset of :meth:`day_night_duration`, because weekends are treated differently (they are always out of hours). The options allow the calculation of components on weekdays or weekend...
f14675:c0:m20
def n_weekends(self) -> int:
startdate = self.start.date()<EOL>enddate = self.end.date()<EOL>ndays = (enddate - startdate).days + <NUM_LIT:1><EOL>in_weekend = False<EOL>n_weekends = <NUM_LIT:0><EOL>for i in range(ndays):<EOL><INDENT>date = startdate + datetime.timedelta(days=i)<EOL>if not in_weekend and is_weekend(date):<EOL><INDENT>in_weekend = T...
Returns the number of weekends that this interval covers. Includes partial weekends.
f14675:c0:m21
def saturdays_of_weekends(self) -> Set[datetime.date]:
startdate = self.start.date()<EOL>enddate = self.end.date()<EOL>ndays = (enddate - startdate).days + <NUM_LIT:1><EOL>saturdays = set()<EOL>for i in range(ndays):<EOL><INDENT>date = startdate + datetime.timedelta(days=i)<EOL>if is_saturday(date):<EOL><INDENT>saturdays.add(date)<EOL><DEDENT>elif is_sunday(date):<EOL><IND...
Returns the dates of all Saturdays that are part of weekends that this interval covers (each Saturday representing a unique identifier for that weekend). The Saturday itself isn't necessarily the part of the weekend that the interval covers!
f14675:c0:m22
def __init__(self,<EOL>intervals: List[Interval] = None,<EOL>no_overlap: bool = True,<EOL>no_contiguous: bool = True) -> None:
<EOL>self.intervals = [] if intervals is None else list(intervals)<EOL>self.no_overlap = no_overlap<EOL>self.no_contiguous = no_contiguous<EOL>for i in self.intervals:<EOL><INDENT>if not isinstance(i, Interval):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(repr(self.intervals)))<EOL><DEDENT><DEDE...
Creates the :class:`IntervalList`. Args: intervals: optional list of :class:`Interval` objects to incorporate into the :class:`IntervalList` no_overlap: merge intervals that overlap (now and on subsequent addition)? no_contiguous: if ``no_overlap`` is set, merge intervals that are c...
f14675:c1:m0
def __repr__(self) -> str:
return (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>repr(self.intervals),<EOL>self.no_overlap,<EOL>self.no_contiguous))<EOL>
Returns the canonical string representation of the object.
f14675:c1:m1
def copy(self, no_overlap: bool = None,<EOL>no_contiguous: bool = None) -> "<STR_LIT>":
if no_overlap is None:<EOL><INDENT>no_overlap = self.no_overlap<EOL><DEDENT>if no_contiguous is None:<EOL><INDENT>no_contiguous = self.no_contiguous<EOL><DEDENT>return IntervalList(self.intervals, no_overlap=no_overlap,<EOL>no_contiguous=no_contiguous)<EOL>
Makes and returns a copy of the :class:`IntervalList`. The ``no_overlap``/``no_contiguous`` parameters can be changed. Args: no_overlap: merge intervals that overlap (now and on subsequent addition)? no_contiguous: if ``no_overlap`` is set, merge intervals that are contiguous too?
f14675:c1:m2
def list(self) -> List[Interval]:
return self.intervals<EOL>
Returns the contained list of :class:`Interval` objects.
f14675:c1:m3
def add(self, interval: Interval) -> None:
if interval is None:<EOL><INDENT>return<EOL><DEDENT>if not isinstance(interval, Interval):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>")<EOL><DEDENT>self.intervals.append(interval)<EOL>self._tidy()<EOL>
Adds an interval to the list. If ``self.no_overlap`` is True, as is the default, it will merge any overlapping intervals thus created.
f14675:c1:m4
def _tidy(self) -> None:
if self.no_overlap:<EOL><INDENT>self.remove_overlap(self.no_contiguous) <EOL><DEDENT>else:<EOL><INDENT>self._sort()<EOL><DEDENT>
Removes overlaps, etc., and sorts.
f14675:c1:m5
def _sort(self) -> None:
self.intervals.sort()<EOL>
Sorts (in place) by interval start time.
f14675:c1:m6
def _remove_overlap_sub(self, also_remove_contiguous: bool) -> bool:
<EOL>for i in range(len(self.intervals)):<EOL><INDENT>for j in range(i + <NUM_LIT:1>, len(self.intervals)):<EOL><INDENT>first = self.intervals[i]<EOL>second = self.intervals[j]<EOL>if also_remove_contiguous:<EOL><INDENT>test = first.contiguous(second)<EOL><DEDENT>else:<EOL><INDENT>test = first.overlaps(second)<EOL><DED...
Called by :meth:`remove_overlap`. Removes the first overlap found. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? Returns: bool: ``True`` if an overlap was removed; ``False`` otherwise
f14675:c1:m7
def remove_overlap(self, also_remove_contiguous: bool = False) -> None:
overlap = True<EOL>while overlap:<EOL><INDENT>overlap = self._remove_overlap_sub(also_remove_contiguous)<EOL><DEDENT>self._sort()<EOL>
Merges any overlapping intervals. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging?
f14675:c1:m8
def is_empty(self) -> bool:
return len(self.intervals) == <NUM_LIT:0><EOL>
Do we have no intervals?
f14675:c1:m10
def any_overlap(self) -> bool:
return self._any_overlap_or_contiguous(test_overlap=True)<EOL>
Do any of the intervals overlap?
f14675:c1:m11
def any_contiguous(self) -> bool:
return self._any_overlap_or_contiguous(test_overlap=False)<EOL>
Are any of the intervals contiguous?
f14675:c1:m12
def start_datetime(self) -> Optional[datetime.datetime]:
if not self.intervals:<EOL><INDENT>return None<EOL><DEDENT>return self.intervals[<NUM_LIT:0>].start<EOL>
Returns the start date of the set of intervals, or ``None`` if empty.
f14675:c1:m13
def end_datetime(self) -> Optional[datetime.datetime]:
if not self.intervals:<EOL><INDENT>return None<EOL><DEDENT>return max([x.end for x in self.intervals])<EOL>
Returns the end date of the set of intervals, or ``None`` if empty.
f14675:c1:m14
def start_date(self) -> Optional[datetime.date]:
if not self.intervals:<EOL><INDENT>return None<EOL><DEDENT>return self.start_datetime().date()<EOL>
Returns the start date of the set of intervals, or ``None`` if empty.
f14675:c1:m15
def end_date(self) -> Optional[datetime.date]:
if not self.intervals:<EOL><INDENT>return None<EOL><DEDENT>return self.end_datetime().date()<EOL>
Returns the end date of the set of intervals, or ``None`` if empty.
f14675:c1:m16
def extent(self) -> Optional[Interval]:
if not self.intervals:<EOL><INDENT>return None<EOL><DEDENT>return Interval(self.start_datetime(), self.end_datetime())<EOL>
Returns an :class:`Interval` running from the earliest start of an interval in this list to the latest end. Returns ``None`` if we are empty.
f14675:c1:m17
def total_duration(self) -> datetime.timedelta:
total = datetime.timedelta()<EOL>for interval in self.intervals:<EOL><INDENT>total += interval.duration()<EOL><DEDENT>return total<EOL>
Returns a ``datetime.timedelta`` object with the total sum of durations. If there is overlap, time will be double-counted, so beware!
f14675:c1:m18
def get_overlaps(self) -> "<STR_LIT>":
overlaps = IntervalList()<EOL>for i in range(len(self.intervals)):<EOL><INDENT>for j in range(i + <NUM_LIT:1>, len(self.intervals)):<EOL><INDENT>first = self.intervals[i]<EOL>second = self.intervals[j]<EOL>ol = first.intersection(second)<EOL>if ol is not None:<EOL><INDENT>overlaps.add(ol)<EOL><DEDENT><DEDENT><DEDENT>re...
Returns an :class:`IntervalList` containing intervals representing periods of overlap between intervals in this one.
f14675:c1:m19
def durations(self) -> List[datetime.timedelta]:
return [x.duration() for x in self.intervals]<EOL>
Returns a list of ``datetime.timedelta`` objects representing the durations of each interval in our list.
f14675:c1:m20
def longest_duration(self) -> Optional[datetime.timedelta]:
if not self.intervals:<EOL><INDENT>return None<EOL><DEDENT>return max(self.durations())<EOL>
Returns the duration of the longest interval, or None if none.
f14675:c1:m21
def longest_interval(self) -> Optional[Interval]:
longest_duration = self.longest_duration()<EOL>for i in self.intervals:<EOL><INDENT>if i.duration() == longest_duration:<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return None<EOL>
Returns the longest interval, or ``None`` if none.
f14675:c1:m22
def first_interval_starting(self, start: datetime.datetime) ->Optional[Interval]:
for i in self.intervals:<EOL><INDENT>if i.start == start:<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return None<EOL>
Returns our first interval that starts with the ``start`` parameter, or ``None``.
f14675:c1:m25
def first_interval_ending(self, end: datetime.datetime)-> Optional[Interval]:
for i in self.intervals:<EOL><INDENT>if i.end == end:<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return None<EOL>
Returns our first interval that ends with the ``end`` parameter, or ``None``.
f14675:c1:m26
def gaps(self) -> "<STR_LIT>":
if len(self.intervals) < <NUM_LIT:2>:<EOL><INDENT>return IntervalList(None)<EOL><DEDENT>gaps = []<EOL>for i in range(len(self.intervals) - <NUM_LIT:1>):<EOL><INDENT>gap = Interval(<EOL>self.intervals[i].end,<EOL>self.intervals[i + <NUM_LIT:1>].start<EOL>)<EOL>gaps.append(gap)<EOL><DEDENT>return IntervalList(gaps)<EOL>
Returns all the gaps between intervals, as an :class:`IntervalList`.
f14675:c1:m27
def subset(self, interval: Interval,<EOL>flexibility: int = <NUM_LIT:2>) -> "<STR_LIT>":
if flexibility not in [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>permitted = []<EOL>for i in self.intervals:<EOL><INDENT>if flexibility == <NUM_LIT:0>:<EOL><INDENT>ok = i.start > interval.start and i.end < interval.end<EOL><DEDENT>elif flexibility == <NUM_LIT:1>:<EOL>...
Returns an IntervalList that's a subset of this one, only containing intervals that meet the "interval" parameter criterion. What "meet" means is defined by the ``flexibility`` parameter. ``flexibility == 0``: permits only wholly contained intervals: .. code-block:: none interval: I--------------...
f14675:c1:m30
def gap_subset(self, interval: Interval,<EOL>flexibility: int = <NUM_LIT:2>) -> "<STR_LIT>":
return self.gaps().subset(interval, flexibility)<EOL>
Returns an IntervalList that's a subset of this one, only containing *gaps* between intervals that meet the interval criterion. See :meth:`subset` for the meaning of parameters.
f14675:c1:m31
def n_weekends(self) -> int:
saturdays = set()<EOL>for interval in self.intervals:<EOL><INDENT>saturdays.update(interval.saturdays_of_weekends())<EOL><DEDENT>return len(saturdays)<EOL>
Returns the number of weekends that the intervals collectively touch (where "touching a weekend" means "including time on a Saturday or a Sunday").
f14675:c1:m32
def duration_outside_nwh(<EOL>self,<EOL>starttime: datetime.time = datetime.time(NORMAL_DAY_START_H),<EOL>endtime: datetime.time = datetime.time(NORMAL_DAY_END_H))-> datetime.timedelta:
total = datetime.timedelta()<EOL>for interval in self.intervals:<EOL><INDENT>total += interval.duration_outside_nwh(starttime, endtime)<EOL><DEDENT>return total<EOL>
Returns the total duration outside normal working hours, i.e. evenings/nights, weekends (and Bank Holidays).
f14675:c1:m33
def max_consecutive_days(self) -> Optional[Tuple[int, Interval]]:
if len(self.intervals) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>startdate = self.start_date()<EOL>enddate = self.end_date()<EOL>seq = '<STR_LIT>'<EOL>ndays = (enddate - startdate).days + <NUM_LIT:1><EOL>for i in range(ndays):<EOL><INDENT>date = startdate + datetime.timedelta(days=i)<EOL>wholeday = Interval.w...
The length of the longest sequence of days in which all days include an interval. Returns: tuple: ``(longest_length, longest_interval)`` where ``longest_interval`` is a :class:`Interval` containing the start and end date of the longest span -- or ``None`` if we contain no intervals...
f14675:c1:m34