repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
NLeSC/noodles
noodles/run/logging.py
make_logger
def make_logger(name, stream_type, jobs): """Create a logger component. :param name: name of logger child, i.e. logger will be named `noodles.<name>`. :type name: str :param stream_type: type of the stream that this logger will be inserted into, should be |pull_map| or |push_map|. :type stream_type: function :param jobs: job-keeper instance. :type jobs: dict, |JobKeeper| or |JobDB|. :return: a stream. The resulting stream receives messages and sends them on after sending an INFO message to the logger. In the case of a |JobMessage| or |ResultMessage| a meaningful message is composed otherwise the string representation of the object is passed.""" logger = logging.getLogger('noodles').getChild(name) # logger.setLevel(logging.DEBUG) @stream_type def log_message(message): if message is EndOfQueue: logger.info("-end-of-queue-") elif isinstance(message, JobMessage): logger.info( "job %10s: %s", message.key, message.node) elif isinstance(message, ResultMessage): job = jobs[message.key] if is_workflow(message.value): logger.info( "result %10s [%s]: %s -> workflow %x", message.key, job.node, message.status, id(message.value)) else: value_string = repr(message.value) logger.info( "result %10s [%s]: %s -> %s", message.key, job.node, message.status, _sugar(value_string)) else: logger.info( "unknown message: %s", message) return message return log_message
python
def make_logger(name, stream_type, jobs): """Create a logger component. :param name: name of logger child, i.e. logger will be named `noodles.<name>`. :type name: str :param stream_type: type of the stream that this logger will be inserted into, should be |pull_map| or |push_map|. :type stream_type: function :param jobs: job-keeper instance. :type jobs: dict, |JobKeeper| or |JobDB|. :return: a stream. The resulting stream receives messages and sends them on after sending an INFO message to the logger. In the case of a |JobMessage| or |ResultMessage| a meaningful message is composed otherwise the string representation of the object is passed.""" logger = logging.getLogger('noodles').getChild(name) # logger.setLevel(logging.DEBUG) @stream_type def log_message(message): if message is EndOfQueue: logger.info("-end-of-queue-") elif isinstance(message, JobMessage): logger.info( "job %10s: %s", message.key, message.node) elif isinstance(message, ResultMessage): job = jobs[message.key] if is_workflow(message.value): logger.info( "result %10s [%s]: %s -> workflow %x", message.key, job.node, message.status, id(message.value)) else: value_string = repr(message.value) logger.info( "result %10s [%s]: %s -> %s", message.key, job.node, message.status, _sugar(value_string)) else: logger.info( "unknown message: %s", message) return message return log_message
[ "def", "make_logger", "(", "name", ",", "stream_type", ",", "jobs", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'noodles'", ")", ".", "getChild", "(", "name", ")", "# logger.setLevel(logging.DEBUG)", "@", "stream_type", "def", "log_message", "(...
Create a logger component. :param name: name of logger child, i.e. logger will be named `noodles.<name>`. :type name: str :param stream_type: type of the stream that this logger will be inserted into, should be |pull_map| or |push_map|. :type stream_type: function :param jobs: job-keeper instance. :type jobs: dict, |JobKeeper| or |JobDB|. :return: a stream. The resulting stream receives messages and sends them on after sending an INFO message to the logger. In the case of a |JobMessage| or |ResultMessage| a meaningful message is composed otherwise the string representation of the object is passed.
[ "Create", "a", "logger", "component", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/logging.py#L22-L70
train
30,900
NLeSC/noodles
noodles/run/process.py
run_process
def run_process(workflow, *, n_processes, registry, verbose=False, jobdirs=False, init=None, finish=None, deref=False): """Run the workflow using a number of new python processes. Use this runner to test the workflow in a situation where data serial is needed. :param workflow: The workflow. :type workflow: `Workflow` or `PromisedObject` :param n_processes: Number of processes to start. :param registry: The serial registry. :param verbose: Request verbose output on worker side :param jobdirs: Create a new directory for each job to prevent filename collision.(NYI) :param init: An init function that needs to be run in each process before other jobs can be run. This should be a scheduled function returning True on success. :param finish: A function that wraps up when the worker closes down. :param deref: Set this to True to pass the result through one more encoding and decoding step with object derefencing turned on. :type deref: bool :returns: the result of evaluating the workflow :rtype: any """ workers = {} for i in range(n_processes): new_worker = process_worker(registry, verbose, jobdirs, init, finish) workers['worker {0:2}'.format(i)] = new_worker worker_names = list(workers.keys()) def random_selector(_): """Selects a worker to send a job to at random.""" return random.choice(worker_names) master_worker = hybrid_threaded_worker(random_selector, workers) result = Scheduler().run(master_worker, get_workflow(workflow)) for worker in workers.values(): try: worker.sink().send(EndOfQueue) except StopIteration: pass # w.aux.join() if deref: return registry().dereference(result, host='localhost') else: return result
python
def run_process(workflow, *, n_processes, registry, verbose=False, jobdirs=False, init=None, finish=None, deref=False): """Run the workflow using a number of new python processes. Use this runner to test the workflow in a situation where data serial is needed. :param workflow: The workflow. :type workflow: `Workflow` or `PromisedObject` :param n_processes: Number of processes to start. :param registry: The serial registry. :param verbose: Request verbose output on worker side :param jobdirs: Create a new directory for each job to prevent filename collision.(NYI) :param init: An init function that needs to be run in each process before other jobs can be run. This should be a scheduled function returning True on success. :param finish: A function that wraps up when the worker closes down. :param deref: Set this to True to pass the result through one more encoding and decoding step with object derefencing turned on. :type deref: bool :returns: the result of evaluating the workflow :rtype: any """ workers = {} for i in range(n_processes): new_worker = process_worker(registry, verbose, jobdirs, init, finish) workers['worker {0:2}'.format(i)] = new_worker worker_names = list(workers.keys()) def random_selector(_): """Selects a worker to send a job to at random.""" return random.choice(worker_names) master_worker = hybrid_threaded_worker(random_selector, workers) result = Scheduler().run(master_worker, get_workflow(workflow)) for worker in workers.values(): try: worker.sink().send(EndOfQueue) except StopIteration: pass # w.aux.join() if deref: return registry().dereference(result, host='localhost') else: return result
[ "def", "run_process", "(", "workflow", ",", "*", ",", "n_processes", ",", "registry", ",", "verbose", "=", "False", ",", "jobdirs", "=", "False", ",", "init", "=", "None", ",", "finish", "=", "None", ",", "deref", "=", "False", ")", ":", "workers", "...
Run the workflow using a number of new python processes. Use this runner to test the workflow in a situation where data serial is needed. :param workflow: The workflow. :type workflow: `Workflow` or `PromisedObject` :param n_processes: Number of processes to start. :param registry: The serial registry. :param verbose: Request verbose output on worker side :param jobdirs: Create a new directory for each job to prevent filename collision.(NYI) :param init: An init function that needs to be run in each process before other jobs can be run. This should be a scheduled function returning True on success. :param finish: A function that wraps up when the worker closes down. :param deref: Set this to True to pass the result through one more encoding and decoding step with object derefencing turned on. :type deref: bool :returns: the result of evaluating the workflow :rtype: any
[ "Run", "the", "workflow", "using", "a", "number", "of", "new", "python", "processes", ".", "Use", "this", "runner", "to", "test", "the", "workflow", "in", "a", "situation", "where", "data", "serial", "is", "needed", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/process.py#L91-L155
train
30,901
NLeSC/noodles
noodles/run/xenon/dynamic_pool.py
xenon_interactive_worker
def xenon_interactive_worker( machine, worker_config, input_queue=None, stderr_sink=None): """Uses Xenon to run a single remote interactive worker. Jobs are read from stdin, and results written to stdout. :param machine: Specification of the machine on which to run. :type machine: noodles.run.xenon.Machine :param worker_config: Job configuration. Specifies the command to be run remotely. :type worker_config: noodles.run.xenon.XenonJobConfig """ if input_queue is None: input_queue = Queue() registry = worker_config.registry() @pull_map def serialise(obj): """Serialise incoming objects, yielding strings.""" if isinstance(obj, JobMessage): print('serializing:', str(obj.node), file=sys.stderr) return (registry.to_json(obj, host='scheduler') + '\n').encode() @pull_map def echo(line): print('{} input: {}'.format(worker_config.name, line), file=sys.stderr) return line def do_iterate(source): for x in source(): if x is EndOfQueue: yield EndOfWork return yield x job, output_stream = machine.scheduler.submit_interactive_job( worker_config.xenon_job_description, echo(lambda: serialise(lambda: do_iterate(input_queue.source)))) @sink_map def echo_stderr(text): """Print lines.""" for line in text.split('\n'): print("{}: {}".format(worker_config.name, line), file=sys.stderr) if stderr_sink is None: stderr_sink = echo_stderr() @pull def read_output(source): """Handle output from job, sending stderr data to given `stderr_sink`, passing on lines from stdout.""" line_buffer = "" try: for chunk in source(): if chunk.stdout: lines = chunk.stdout.decode().splitlines(keepends=True) if not lines: continue if lines[0][-1] == '\n': yield line_buffer + lines[0] line_buffer = "" else: line_buffer += lines[0] if len(lines) == 1: continue yield from lines[1:-1] if lines[-1][-1] == '\n': yield lines[-1] else: line_buffer = lines[-1] if chunk.stderr: for line in chunk.stderr.decode().split('\n'): stripped_line = line.strip() if stripped_line != '': stderr_sink.send(stripped_line) except grpc.RpcError as e: return @pull_map def deserialise(line): result = registry.from_json(line, deref=False) return result return Connection( lambda: deserialise(lambda: read_output(lambda: output_stream)), input_queue.sink, aux=job)
python
def xenon_interactive_worker( machine, worker_config, input_queue=None, stderr_sink=None): """Uses Xenon to run a single remote interactive worker. Jobs are read from stdin, and results written to stdout. :param machine: Specification of the machine on which to run. :type machine: noodles.run.xenon.Machine :param worker_config: Job configuration. Specifies the command to be run remotely. :type worker_config: noodles.run.xenon.XenonJobConfig """ if input_queue is None: input_queue = Queue() registry = worker_config.registry() @pull_map def serialise(obj): """Serialise incoming objects, yielding strings.""" if isinstance(obj, JobMessage): print('serializing:', str(obj.node), file=sys.stderr) return (registry.to_json(obj, host='scheduler') + '\n').encode() @pull_map def echo(line): print('{} input: {}'.format(worker_config.name, line), file=sys.stderr) return line def do_iterate(source): for x in source(): if x is EndOfQueue: yield EndOfWork return yield x job, output_stream = machine.scheduler.submit_interactive_job( worker_config.xenon_job_description, echo(lambda: serialise(lambda: do_iterate(input_queue.source)))) @sink_map def echo_stderr(text): """Print lines.""" for line in text.split('\n'): print("{}: {}".format(worker_config.name, line), file=sys.stderr) if stderr_sink is None: stderr_sink = echo_stderr() @pull def read_output(source): """Handle output from job, sending stderr data to given `stderr_sink`, passing on lines from stdout.""" line_buffer = "" try: for chunk in source(): if chunk.stdout: lines = chunk.stdout.decode().splitlines(keepends=True) if not lines: continue if lines[0][-1] == '\n': yield line_buffer + lines[0] line_buffer = "" else: line_buffer += lines[0] if len(lines) == 1: continue yield from lines[1:-1] if lines[-1][-1] == '\n': yield lines[-1] else: line_buffer = lines[-1] if chunk.stderr: for line in chunk.stderr.decode().split('\n'): stripped_line = line.strip() if stripped_line != '': stderr_sink.send(stripped_line) except grpc.RpcError as e: return @pull_map def deserialise(line): result = registry.from_json(line, deref=False) return result return Connection( lambda: deserialise(lambda: read_output(lambda: output_stream)), input_queue.sink, aux=job)
[ "def", "xenon_interactive_worker", "(", "machine", ",", "worker_config", ",", "input_queue", "=", "None", ",", "stderr_sink", "=", "None", ")", ":", "if", "input_queue", "is", "None", ":", "input_queue", "=", "Queue", "(", ")", "registry", "=", "worker_config"...
Uses Xenon to run a single remote interactive worker. Jobs are read from stdin, and results written to stdout. :param machine: Specification of the machine on which to run. :type machine: noodles.run.xenon.Machine :param worker_config: Job configuration. Specifies the command to be run remotely. :type worker_config: noodles.run.xenon.XenonJobConfig
[ "Uses", "Xenon", "to", "run", "a", "single", "remote", "interactive", "worker", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/xenon/dynamic_pool.py#L16-L112
train
30,902
NLeSC/noodles
noodles/run/xenon/dynamic_pool.py
XenonInteractiveWorker.wait_until_running
def wait_until_running(self, callback=None): """Waits until the remote worker is running, then calls the callback. Usually, this method is passed to a different thread; the callback is then a function patching results through to the result queue.""" status = self.machine.scheduler.wait_until_running( self.job, self.worker_config.time_out) if status.running: self.online = True if callback: callback(self) else: raise TimeoutError("Timeout while waiting for worker to run: " + self.worker_config.name)
python
def wait_until_running(self, callback=None): """Waits until the remote worker is running, then calls the callback. Usually, this method is passed to a different thread; the callback is then a function patching results through to the result queue.""" status = self.machine.scheduler.wait_until_running( self.job, self.worker_config.time_out) if status.running: self.online = True if callback: callback(self) else: raise TimeoutError("Timeout while waiting for worker to run: " + self.worker_config.name)
[ "def", "wait_until_running", "(", "self", ",", "callback", "=", "None", ")", ":", "status", "=", "self", ".", "machine", ".", "scheduler", ".", "wait_until_running", "(", "self", ".", "job", ",", "self", ".", "worker_config", ".", "time_out", ")", "if", ...
Waits until the remote worker is running, then calls the callback. Usually, this method is passed to a different thread; the callback is then a function patching results through to the result queue.
[ "Waits", "until", "the", "remote", "worker", "is", "running", "then", "calls", "the", "callback", ".", "Usually", "this", "method", "is", "passed", "to", "a", "different", "thread", ";", "the", "callback", "is", "then", "a", "function", "patching", "results"...
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/xenon/dynamic_pool.py#L130-L143
train
30,903
NLeSC/noodles
noodles/run/xenon/dynamic_pool.py
DynamicPool.add_xenon_worker
def add_xenon_worker(self, worker_config): """Adds a worker to the pool; sets gears in motion.""" c = XenonInteractiveWorker(self.machine, worker_config) w = RemoteWorker( worker_config.name, threading.Lock(), worker_config.n_threads, [], *c.setup()) with self.wlock: self.workers[worker_config.name] = w def populate(job_source): """Populate the worker with jobs, if jobs are available.""" with w.lock, self.plock: # Worker lock ~~~~~~~~~~~~~~~~~~ while len(w.jobs) < w.max and not self.job_queue.empty(): msg = next(job_source) w.sink.send(msg) if msg is not EndOfQueue: key, job = msg w.jobs.append(key) else: break # lock end ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def activate(_): """Activate the worker.""" job_source = self.job_queue.source() populate(job_source) sink = self.result_queue.sink() for result in w.source: sink.send(result) # do bookkeeping and submit a new job to the worker with w.lock: # Worker lock ~~~~~~~~~~~~~~~~~~~~~ w.jobs.remove(result.key) populate(job_source) # lock end ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for key in w.jobs: sink.send(ResultMessage( key, 'aborted', None, 'connection to remote worker lost.')) # Start the `activate` function when the worker goes online. t = threading.Thread( target=self.count(c.wait_until_running), args=(activate,), daemon=True) t.start()
python
def add_xenon_worker(self, worker_config): """Adds a worker to the pool; sets gears in motion.""" c = XenonInteractiveWorker(self.machine, worker_config) w = RemoteWorker( worker_config.name, threading.Lock(), worker_config.n_threads, [], *c.setup()) with self.wlock: self.workers[worker_config.name] = w def populate(job_source): """Populate the worker with jobs, if jobs are available.""" with w.lock, self.plock: # Worker lock ~~~~~~~~~~~~~~~~~~ while len(w.jobs) < w.max and not self.job_queue.empty(): msg = next(job_source) w.sink.send(msg) if msg is not EndOfQueue: key, job = msg w.jobs.append(key) else: break # lock end ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def activate(_): """Activate the worker.""" job_source = self.job_queue.source() populate(job_source) sink = self.result_queue.sink() for result in w.source: sink.send(result) # do bookkeeping and submit a new job to the worker with w.lock: # Worker lock ~~~~~~~~~~~~~~~~~~~~~ w.jobs.remove(result.key) populate(job_source) # lock end ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for key in w.jobs: sink.send(ResultMessage( key, 'aborted', None, 'connection to remote worker lost.')) # Start the `activate` function when the worker goes online. t = threading.Thread( target=self.count(c.wait_until_running), args=(activate,), daemon=True) t.start()
[ "def", "add_xenon_worker", "(", "self", ",", "worker_config", ")", ":", "c", "=", "XenonInteractiveWorker", "(", "self", ".", "machine", ",", "worker_config", ")", "w", "=", "RemoteWorker", "(", "worker_config", ".", "name", ",", "threading", ".", "Lock", "(...
Adds a worker to the pool; sets gears in motion.
[ "Adds", "a", "worker", "to", "the", "pool", ";", "sets", "gears", "in", "motion", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/xenon/dynamic_pool.py#L202-L250
train
30,904
NLeSC/noodles
noodles/patterns/find_first.py
find_first
def find_first(pred, lst): """Find the first result of a list of promises `lst` that satisfies a predicate `pred`. :param pred: a function of one argument returning `True` or `False`. :param lst: a list of promises or values. :return: a promise of a value or `None`. This is a wrapper around :func:`s_find_first`. The first item on the list is passed *as is*, forcing evalutation. The tail of the list is quoted, and only unquoted if the predicate fails on the result of the first promise. If the input list is empty, `None` is returned.""" if lst: return s_find_first(pred, lst[0], [quote(l) for l in lst[1:]]) else: return None
python
def find_first(pred, lst): """Find the first result of a list of promises `lst` that satisfies a predicate `pred`. :param pred: a function of one argument returning `True` or `False`. :param lst: a list of promises or values. :return: a promise of a value or `None`. This is a wrapper around :func:`s_find_first`. The first item on the list is passed *as is*, forcing evalutation. The tail of the list is quoted, and only unquoted if the predicate fails on the result of the first promise. If the input list is empty, `None` is returned.""" if lst: return s_find_first(pred, lst[0], [quote(l) for l in lst[1:]]) else: return None
[ "def", "find_first", "(", "pred", ",", "lst", ")", ":", "if", "lst", ":", "return", "s_find_first", "(", "pred", ",", "lst", "[", "0", "]", ",", "[", "quote", "(", "l", ")", "for", "l", "in", "lst", "[", "1", ":", "]", "]", ")", "else", ":", ...
Find the first result of a list of promises `lst` that satisfies a predicate `pred`. :param pred: a function of one argument returning `True` or `False`. :param lst: a list of promises or values. :return: a promise of a value or `None`. This is a wrapper around :func:`s_find_first`. The first item on the list is passed *as is*, forcing evalutation. The tail of the list is quoted, and only unquoted if the predicate fails on the result of the first promise. If the input list is empty, `None` is returned.
[ "Find", "the", "first", "result", "of", "a", "list", "of", "promises", "lst", "that", "satisfies", "a", "predicate", "pred", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/patterns/find_first.py#L4-L20
train
30,905
NLeSC/noodles
noodles/patterns/find_first.py
s_find_first
def s_find_first(pred, first, lst): """Evaluate `first`; if predicate `pred` succeeds on the result of `first`, return the result; otherwise recur on the first element of `lst`. :param pred: a predicate. :param first: a promise. :param lst: a list of quoted promises. :return: the first element for which predicate is true.""" if pred(first): return first elif lst: return s_find_first(pred, unquote(lst[0]), lst[1:]) else: return None
python
def s_find_first(pred, first, lst): """Evaluate `first`; if predicate `pred` succeeds on the result of `first`, return the result; otherwise recur on the first element of `lst`. :param pred: a predicate. :param first: a promise. :param lst: a list of quoted promises. :return: the first element for which predicate is true.""" if pred(first): return first elif lst: return s_find_first(pred, unquote(lst[0]), lst[1:]) else: return None
[ "def", "s_find_first", "(", "pred", ",", "first", ",", "lst", ")", ":", "if", "pred", "(", "first", ")", ":", "return", "first", "elif", "lst", ":", "return", "s_find_first", "(", "pred", ",", "unquote", "(", "lst", "[", "0", "]", ")", ",", "lst", ...
Evaluate `first`; if predicate `pred` succeeds on the result of `first`, return the result; otherwise recur on the first element of `lst`. :param pred: a predicate. :param first: a promise. :param lst: a list of quoted promises. :return: the first element for which predicate is true.
[ "Evaluate", "first", ";", "if", "predicate", "pred", "succeeds", "on", "the", "result", "of", "first", "return", "the", "result", ";", "otherwise", "recur", "on", "the", "first", "element", "of", "lst", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/patterns/find_first.py#L24-L37
train
30,906
NLeSC/noodles
noodles/pilot_job.py
run_online_mode
def run_online_mode(args): """Run jobs. :param args: arguments resulting from program ArgumentParser. :return: None This reads messages containing job descriptions from standard input, and writes messages to standard output containing the result. Messages can be encoded as either JSON or MessagePack. """ print("\033[47;30m Netherlands\033[48;2;0;174;239;37m▌" "\033[38;2;255;255;255me\u20d2Science\u20d2\033[37m▐" "\033[47;30mcenter \033[m Noodles worker", file=sys.stderr) if args.n == 1: registry = look_up(args.registry)() finish = None input_stream = JSONObjectReader( registry, sys.stdin, deref=True) output_stream = JSONObjectWriter( registry, sys.stdout, host=args.name) sys.stdout.flush() # run the init function if it is given if args.init: with redirect_stdout(sys.stderr): look_up(args.init)() if args.finish: finish = look_up(args.finish) for msg in input_stream: if isinstance(msg, JobMessage): key, job = msg elif msg is EndOfWork: print("received EndOfWork, bye", file=sys.stderr) sys.exit(0) elif isinstance(msg, tuple): key, job = msg elif msg is None: continue else: raise RuntimeError("Unknown message received: {}".format(msg)) if args.jobdirs: # make a directory os.mkdir("noodles-{0}".format(key.hex)) # enter it os.chdir("noodles-{0}".format(key.hex)) if args.verbose: print("worker: ", job.foo.__name__, job.bound_args.args, job.bound_args.kwargs, file=sys.stderr, flush=True) with redirect_stdout(sys.stderr): result = run_job(key, job) if args.verbose: print("result: ", result.value, file=sys.stderr, flush=True) if args.jobdirs: # parent directory os.chdir("..") output_stream.send(result) if finish: finish() time.sleep(0.1) sys.stdout.flush() sys.stderr.flush()
python
def run_online_mode(args): """Run jobs. :param args: arguments resulting from program ArgumentParser. :return: None This reads messages containing job descriptions from standard input, and writes messages to standard output containing the result. Messages can be encoded as either JSON or MessagePack. """ print("\033[47;30m Netherlands\033[48;2;0;174;239;37m▌" "\033[38;2;255;255;255me\u20d2Science\u20d2\033[37m▐" "\033[47;30mcenter \033[m Noodles worker", file=sys.stderr) if args.n == 1: registry = look_up(args.registry)() finish = None input_stream = JSONObjectReader( registry, sys.stdin, deref=True) output_stream = JSONObjectWriter( registry, sys.stdout, host=args.name) sys.stdout.flush() # run the init function if it is given if args.init: with redirect_stdout(sys.stderr): look_up(args.init)() if args.finish: finish = look_up(args.finish) for msg in input_stream: if isinstance(msg, JobMessage): key, job = msg elif msg is EndOfWork: print("received EndOfWork, bye", file=sys.stderr) sys.exit(0) elif isinstance(msg, tuple): key, job = msg elif msg is None: continue else: raise RuntimeError("Unknown message received: {}".format(msg)) if args.jobdirs: # make a directory os.mkdir("noodles-{0}".format(key.hex)) # enter it os.chdir("noodles-{0}".format(key.hex)) if args.verbose: print("worker: ", job.foo.__name__, job.bound_args.args, job.bound_args.kwargs, file=sys.stderr, flush=True) with redirect_stdout(sys.stderr): result = run_job(key, job) if args.verbose: print("result: ", result.value, file=sys.stderr, flush=True) if args.jobdirs: # parent directory os.chdir("..") output_stream.send(result) if finish: finish() time.sleep(0.1) sys.stdout.flush() sys.stderr.flush()
[ "def", "run_online_mode", "(", "args", ")", ":", "print", "(", "\"\\033[47;30m Netherlands\\033[48;2;0;174;239;37m▌\"", "\"\\033[38;2;255;255;255me\\u20d2Science\\u20d2\\033[37m▐\"", "\"\\033[47;30mcenter \\033[m Noodles worker\"", ",", "file", "=", "sys", ".", "stderr", ")", "if...
Run jobs. :param args: arguments resulting from program ArgumentParser. :return: None This reads messages containing job descriptions from standard input, and writes messages to standard output containing the result. Messages can be encoded as either JSON or MessagePack.
[ "Run", "jobs", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/pilot_job.py#L38-L114
train
30,907
NLeSC/noodles
noodles/tutorial.py
_format_arg_list
def _format_arg_list(args, variadic=False): """Format a list of arguments for pretty printing. :param a: list of arguments. :type a: list :param v: tell if the function accepts variadic arguments :type v: bool """ def sugar(s): """Shorten strings that are too long for decency.""" s = s.replace("{", "{{").replace("}", "}}") if len(s) > 50: return s[:20] + " ... " + s[-20:] else: return s def arg_to_str(arg): """Convert argument to a string.""" if isinstance(arg, str): return sugar(repr(arg)) elif arg is Parameter.empty: return '\u2014' else: return sugar(str(arg)) if not args: if variadic: return "(\u2026)" else: return "()" return "(" + ", ".join(map(arg_to_str, args)) + ")"
python
def _format_arg_list(args, variadic=False): """Format a list of arguments for pretty printing. :param a: list of arguments. :type a: list :param v: tell if the function accepts variadic arguments :type v: bool """ def sugar(s): """Shorten strings that are too long for decency.""" s = s.replace("{", "{{").replace("}", "}}") if len(s) > 50: return s[:20] + " ... " + s[-20:] else: return s def arg_to_str(arg): """Convert argument to a string.""" if isinstance(arg, str): return sugar(repr(arg)) elif arg is Parameter.empty: return '\u2014' else: return sugar(str(arg)) if not args: if variadic: return "(\u2026)" else: return "()" return "(" + ", ".join(map(arg_to_str, args)) + ")"
[ "def", "_format_arg_list", "(", "args", ",", "variadic", "=", "False", ")", ":", "def", "sugar", "(", "s", ")", ":", "\"\"\"Shorten strings that are too long for decency.\"\"\"", "s", "=", "s", ".", "replace", "(", "\"{\"", ",", "\"{{\"", ")", ".", "replace", ...
Format a list of arguments for pretty printing. :param a: list of arguments. :type a: list :param v: tell if the function accepts variadic arguments :type v: bool
[ "Format", "a", "list", "of", "arguments", "for", "pretty", "printing", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/tutorial.py#L49-L81
train
30,908
NLeSC/noodles
noodles/tutorial.py
get_workflow_graph
def get_workflow_graph(promise): """Get a graph of a promise.""" workflow = get_workflow(promise) dot = Digraph() for i, n in workflow.nodes.items(): dot.node(str(i), label="{0} \n {1}".format( n.foo.__name__, _format_arg_list(n.bound_args.args))) for i in workflow.links: for j in workflow.links[i]: dot.edge(str(i), str(j[0]), label=str(j[1].name)) return dot
python
def get_workflow_graph(promise): """Get a graph of a promise.""" workflow = get_workflow(promise) dot = Digraph() for i, n in workflow.nodes.items(): dot.node(str(i), label="{0} \n {1}".format( n.foo.__name__, _format_arg_list(n.bound_args.args))) for i in workflow.links: for j in workflow.links[i]: dot.edge(str(i), str(j[0]), label=str(j[1].name)) return dot
[ "def", "get_workflow_graph", "(", "promise", ")", ":", "workflow", "=", "get_workflow", "(", "promise", ")", "dot", "=", "Digraph", "(", ")", "for", "i", ",", "n", "in", "workflow", ".", "nodes", ".", "items", "(", ")", ":", "dot", ".", "node", "(", ...
Get a graph of a promise.
[ "Get", "a", "graph", "of", "a", "promise", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/tutorial.py#L84-L98
train
30,909
NLeSC/noodles
noodles/tutorial.py
display_workflows
def display_workflows(prefix, **kwargs): """Display workflows in a table. This generates SVG files. Use this in a Jupyter notebook and ship the images :param prefix: name prefix for svg files generated. :param kwargs: keyword arguments containing a workflow each. """ from IPython.display import display, Markdown def create_svg(name, workflow): """Create an SVG file with rendered graph from a workflow.""" name = name.replace('_', '-') filename = '{}-{}.svg'.format(prefix, name) dot = get_workflow_graph(workflow) dot.attr('graph', bgcolor='transparent') with open(filename, 'bw') as file: file.write(dot.pipe(format='svg')) return name, filename svg_files = {name: svg for name, svg in (create_svg(name, workflow) for name, workflow in kwargs.items())} markdown_table = \ '| ' + ' | '.join(svg_files.keys()) + ' |\n' + \ '| ' + ' | '.join('---' for _ in svg_files) + ' |\n' + \ '| ' + ' | '.join('![workflow {}]({})'.format(name, svg) for name, svg in svg_files.items()) + ' |' display(Markdown(markdown_table))
python
def display_workflows(prefix, **kwargs): """Display workflows in a table. This generates SVG files. Use this in a Jupyter notebook and ship the images :param prefix: name prefix for svg files generated. :param kwargs: keyword arguments containing a workflow each. """ from IPython.display import display, Markdown def create_svg(name, workflow): """Create an SVG file with rendered graph from a workflow.""" name = name.replace('_', '-') filename = '{}-{}.svg'.format(prefix, name) dot = get_workflow_graph(workflow) dot.attr('graph', bgcolor='transparent') with open(filename, 'bw') as file: file.write(dot.pipe(format='svg')) return name, filename svg_files = {name: svg for name, svg in (create_svg(name, workflow) for name, workflow in kwargs.items())} markdown_table = \ '| ' + ' | '.join(svg_files.keys()) + ' |\n' + \ '| ' + ' | '.join('---' for _ in svg_files) + ' |\n' + \ '| ' + ' | '.join('![workflow {}]({})'.format(name, svg) for name, svg in svg_files.items()) + ' |' display(Markdown(markdown_table))
[ "def", "display_workflows", "(", "prefix", ",", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "display", "import", "display", ",", "Markdown", "def", "create_svg", "(", "name", ",", "workflow", ")", ":", "\"\"\"Create an SVG file with rendered graph from a...
Display workflows in a table. This generates SVG files. Use this in a Jupyter notebook and ship the images :param prefix: name prefix for svg files generated. :param kwargs: keyword arguments containing a workflow each.
[ "Display", "workflows", "in", "a", "table", ".", "This", "generates", "SVG", "files", ".", "Use", "this", "in", "a", "Jupyter", "notebook", "and", "ship", "the", "images" ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/tutorial.py#L101-L129
train
30,910
NLeSC/noodles
noodles/tutorial.py
snip_line
def snip_line(line, max_width, split_at): """Shorten a line to a maximum length.""" if len(line) < max_width: return line return line[:split_at] + " … " \ + line[-(max_width - split_at - 3):]
python
def snip_line(line, max_width, split_at): """Shorten a line to a maximum length.""" if len(line) < max_width: return line return line[:split_at] + " … " \ + line[-(max_width - split_at - 3):]
[ "def", "snip_line", "(", "line", ",", "max_width", ",", "split_at", ")", ":", "if", "len", "(", "line", ")", "<", "max_width", ":", "return", "line", "return", "line", "[", ":", "split_at", "]", "+", "\" … \" \\", "+", "line", "[", "-", "(", "max_wid...
Shorten a line to a maximum length.
[ "Shorten", "a", "line", "to", "a", "maximum", "length", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/tutorial.py#L132-L137
train
30,911
NLeSC/noodles
noodles/tutorial.py
run_and_print_log
def run_and_print_log(workflow, highlight=None): """Run workflow on multi-threaded worker cached with Sqlite3. :param workflow: workflow to evaluate. :param highlight: highlight these lines. """ from noodles.run.threading.sqlite3 import run_parallel from noodles import serial import io import logging log = io.StringIO() log_handler = logging.StreamHandler(log) formatter = logging.Formatter('%(asctime)s - %(message)s') log_handler.setFormatter(formatter) logger = logging.getLogger('noodles') logger.setLevel(logging.INFO) logger.handlers = [log_handler] result = run_parallel( workflow, n_threads=4, registry=serial.base, db_file='tutorial.db', always_cache=True, echo_log=False) display_text(log.getvalue(), highlight or [], split_at=40) return result
python
def run_and_print_log(workflow, highlight=None): """Run workflow on multi-threaded worker cached with Sqlite3. :param workflow: workflow to evaluate. :param highlight: highlight these lines. """ from noodles.run.threading.sqlite3 import run_parallel from noodles import serial import io import logging log = io.StringIO() log_handler = logging.StreamHandler(log) formatter = logging.Formatter('%(asctime)s - %(message)s') log_handler.setFormatter(formatter) logger = logging.getLogger('noodles') logger.setLevel(logging.INFO) logger.handlers = [log_handler] result = run_parallel( workflow, n_threads=4, registry=serial.base, db_file='tutorial.db', always_cache=True, echo_log=False) display_text(log.getvalue(), highlight or [], split_at=40) return result
[ "def", "run_and_print_log", "(", "workflow", ",", "highlight", "=", "None", ")", ":", "from", "noodles", ".", "run", ".", "threading", ".", "sqlite3", "import", "run_parallel", "from", "noodles", "import", "serial", "import", "io", "import", "logging", "log", ...
Run workflow on multi-threaded worker cached with Sqlite3. :param workflow: workflow to evaluate. :param highlight: highlight these lines.
[ "Run", "workflow", "on", "multi", "-", "threaded", "worker", "cached", "with", "Sqlite3", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/tutorial.py#L167-L192
train
30,912
NLeSC/noodles
noodles/run/runners.py
run_single_with_display
def run_single_with_display(wf, display): """Adds a display to the single runner. Everything still runs in a single thread. Every time a job is pulled by the worker, a message goes to the display routine; when the job is finished the result is sent to the display routine.""" S = Scheduler(error_handler=display.error_handler) W = Queue() \ >> branch(log_job_start.to(sink_map(display))) \ >> worker \ >> branch(sink_map(display)) return S.run(W, get_workflow(wf))
python
def run_single_with_display(wf, display): """Adds a display to the single runner. Everything still runs in a single thread. Every time a job is pulled by the worker, a message goes to the display routine; when the job is finished the result is sent to the display routine.""" S = Scheduler(error_handler=display.error_handler) W = Queue() \ >> branch(log_job_start.to(sink_map(display))) \ >> worker \ >> branch(sink_map(display)) return S.run(W, get_workflow(wf))
[ "def", "run_single_with_display", "(", "wf", ",", "display", ")", ":", "S", "=", "Scheduler", "(", "error_handler", "=", "display", ".", "error_handler", ")", "W", "=", "Queue", "(", ")", ">>", "branch", "(", "log_job_start", ".", "to", "(", "sink_map", ...
Adds a display to the single runner. Everything still runs in a single thread. Every time a job is pulled by the worker, a message goes to the display routine; when the job is finished the result is sent to the display routine.
[ "Adds", "a", "display", "to", "the", "single", "runner", ".", "Everything", "still", "runs", "in", "a", "single", "thread", ".", "Every", "time", "a", "job", "is", "pulled", "by", "the", "worker", "a", "message", "goes", "to", "the", "display", "routine"...
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/runners.py#L44-L55
train
30,913
NLeSC/noodles
noodles/run/runners.py
run_parallel_with_display
def run_parallel_with_display(wf, n_threads, display): """Adds a display to the parallel runner. Because messages come in asynchronously now, we start an extra thread just for the display routine.""" LogQ = Queue() S = Scheduler(error_handler=display.error_handler) threading.Thread( target=patch, args=(LogQ.source, sink_map(display)), daemon=True).start() W = Queue() \ >> branch(log_job_start >> LogQ.sink) \ >> thread_pool(*repeat(worker, n_threads)) \ >> branch(LogQ.sink) result = S.run(W, get_workflow(wf)) LogQ.wait() return result
python
def run_parallel_with_display(wf, n_threads, display): """Adds a display to the parallel runner. Because messages come in asynchronously now, we start an extra thread just for the display routine.""" LogQ = Queue() S = Scheduler(error_handler=display.error_handler) threading.Thread( target=patch, args=(LogQ.source, sink_map(display)), daemon=True).start() W = Queue() \ >> branch(log_job_start >> LogQ.sink) \ >> thread_pool(*repeat(worker, n_threads)) \ >> branch(LogQ.sink) result = S.run(W, get_workflow(wf)) LogQ.wait() return result
[ "def", "run_parallel_with_display", "(", "wf", ",", "n_threads", ",", "display", ")", ":", "LogQ", "=", "Queue", "(", ")", "S", "=", "Scheduler", "(", "error_handler", "=", "display", ".", "error_handler", ")", "threading", ".", "Thread", "(", "target", "=...
Adds a display to the parallel runner. Because messages come in asynchronously now, we start an extra thread just for the display routine.
[ "Adds", "a", "display", "to", "the", "parallel", "runner", ".", "Because", "messages", "come", "in", "asynchronously", "now", "we", "start", "an", "extra", "thread", "just", "for", "the", "display", "routine", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/runners.py#L58-L79
train
30,914
NLeSC/noodles
noodles/lib/decorator.py
decorator
def decorator(f): """Creates a paramatric decorator from a function. The resulting decorator will optionally take keyword arguments.""" @functools.wraps(f) def decoratored_function(*args, **kwargs): if args and len(args) == 1: return f(*args, **kwargs) if args: raise TypeError( "This decorator only accepts extra keyword arguments.") return lambda g: f(g, **kwargs) return decoratored_function
python
def decorator(f): """Creates a paramatric decorator from a function. The resulting decorator will optionally take keyword arguments.""" @functools.wraps(f) def decoratored_function(*args, **kwargs): if args and len(args) == 1: return f(*args, **kwargs) if args: raise TypeError( "This decorator only accepts extra keyword arguments.") return lambda g: f(g, **kwargs) return decoratored_function
[ "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "decoratored_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "len", "(", "args", ")", "==", "1", ":", "return", "f"...
Creates a paramatric decorator from a function. The resulting decorator will optionally take keyword arguments.
[ "Creates", "a", "paramatric", "decorator", "from", "a", "function", ".", "The", "resulting", "decorator", "will", "optionally", "take", "keyword", "arguments", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/decorator.py#L4-L18
train
30,915
NLeSC/noodles
noodles/run/scheduler.py
Scheduler.run
def run(self, connection: Connection, master: Workflow): """Run a workflow. :param connection: A connection giving a sink to the job-queue and a source yielding results. :type connection: Connection :param master: The workflow. :type master: Workflow """ # initiate worker slave army and take up reins ... source, sink = connection.setup() # schedule work self.add_workflow(master, master, master.root, sink) graceful_exit = False errors = [] # process results for job_key, status, result, err_msg in source: wf, n = self.jobs[job_key] if status == 'error': graceful_exit = True errors.append(err_msg) try: sink.send(FlushQueue) except StopIteration: pass print("Uncaught error running job: {}, {}".format(n, err_msg), file=sys.stderr) print("Flushing queue and waiting for threads to close.", file=sys.stderr, flush=True) if status == 'aborted': print("Job {} got aborted: {}".format(n, err_msg), file=sys.stderr) print("Flushing queue and waiting for threads to close.", file=sys.stderr, flush=True) graceful_exit = True errors.append(err_msg) try: sink.send(FlushQueue) except StopIteration: pass if self.verbose: print("sched result [{0}]: ".format(self.key_map[job_key]), result, file=sys.stderr, flush=True) del self.jobs[job_key] if len(self.jobs) == 0 and graceful_exit: for error in errors: print("Exception of type", type(error), ":") print(error) raise errors[0] # if this result is the root of a workflow, pop to parent # we do this before scheduling a child workflow, as to # achieve tail-call elimination. while n == wf.root and wf is not master: child = id(wf) _, wf, n = self.dynamic_links[child] del self.dynamic_links[child] # if we retrieve a workflow, push a child if is_workflow(result) and not graceful_exit: child_wf = get_workflow(result) self.add_workflow(child_wf, wf, n, sink) continue # insert the result in the nodes that need it wf.nodes[n].result = result for (tgt, address) in wf.links[n]: insert_result(wf.nodes[tgt], address, result) if is_node_ready(wf.nodes[tgt]) and not graceful_exit: self.schedule(Job(workflow=wf, node_id=tgt), sink) # see if we're done if wf == master and n == master.root: try: sink.send(EndOfQueue) except StopIteration: pass return result
python
def run(self, connection: Connection, master: Workflow): """Run a workflow. :param connection: A connection giving a sink to the job-queue and a source yielding results. :type connection: Connection :param master: The workflow. :type master: Workflow """ # initiate worker slave army and take up reins ... source, sink = connection.setup() # schedule work self.add_workflow(master, master, master.root, sink) graceful_exit = False errors = [] # process results for job_key, status, result, err_msg in source: wf, n = self.jobs[job_key] if status == 'error': graceful_exit = True errors.append(err_msg) try: sink.send(FlushQueue) except StopIteration: pass print("Uncaught error running job: {}, {}".format(n, err_msg), file=sys.stderr) print("Flushing queue and waiting for threads to close.", file=sys.stderr, flush=True) if status == 'aborted': print("Job {} got aborted: {}".format(n, err_msg), file=sys.stderr) print("Flushing queue and waiting for threads to close.", file=sys.stderr, flush=True) graceful_exit = True errors.append(err_msg) try: sink.send(FlushQueue) except StopIteration: pass if self.verbose: print("sched result [{0}]: ".format(self.key_map[job_key]), result, file=sys.stderr, flush=True) del self.jobs[job_key] if len(self.jobs) == 0 and graceful_exit: for error in errors: print("Exception of type", type(error), ":") print(error) raise errors[0] # if this result is the root of a workflow, pop to parent # we do this before scheduling a child workflow, as to # achieve tail-call elimination. while n == wf.root and wf is not master: child = id(wf) _, wf, n = self.dynamic_links[child] del self.dynamic_links[child] # if we retrieve a workflow, push a child if is_workflow(result) and not graceful_exit: child_wf = get_workflow(result) self.add_workflow(child_wf, wf, n, sink) continue # insert the result in the nodes that need it wf.nodes[n].result = result for (tgt, address) in wf.links[n]: insert_result(wf.nodes[tgt], address, result) if is_node_ready(wf.nodes[tgt]) and not graceful_exit: self.schedule(Job(workflow=wf, node_id=tgt), sink) # see if we're done if wf == master and n == master.root: try: sink.send(EndOfQueue) except StopIteration: pass return result
[ "def", "run", "(", "self", ",", "connection", ":", "Connection", ",", "master", ":", "Workflow", ")", ":", "# initiate worker slave army and take up reins ...", "source", ",", "sink", "=", "connection", ".", "setup", "(", ")", "# schedule work", "self", ".", "ad...
Run a workflow. :param connection: A connection giving a sink to the job-queue and a source yielding results. :type connection: Connection :param master: The workflow. :type master: Workflow
[ "Run", "a", "workflow", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/scheduler.py#L70-L159
train
30,916
NLeSC/noodles
noodles/workflow/arguments.py
ref_argument
def ref_argument(bound_args, address): """ Taking a bound_args object, and an ArgumentAddress, retrieves the data currently stored in bound_args for this particular address.""" if address.kind == ArgumentKind.regular: return bound_args.arguments[address.name] return bound_args.arguments[address.name][address.key]
python
def ref_argument(bound_args, address): """ Taking a bound_args object, and an ArgumentAddress, retrieves the data currently stored in bound_args for this particular address.""" if address.kind == ArgumentKind.regular: return bound_args.arguments[address.name] return bound_args.arguments[address.name][address.key]
[ "def", "ref_argument", "(", "bound_args", ",", "address", ")", ":", "if", "address", ".", "kind", "==", "ArgumentKind", ".", "regular", ":", "return", "bound_args", ".", "arguments", "[", "address", ".", "name", "]", "return", "bound_args", ".", "arguments",...
Taking a bound_args object, and an ArgumentAddress, retrieves the data currently stored in bound_args for this particular address.
[ "Taking", "a", "bound_args", "object", "and", "an", "ArgumentAddress", "retrieves", "the", "data", "currently", "stored", "in", "bound_args", "for", "this", "particular", "address", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/workflow/arguments.py#L66-L72
train
30,917
NLeSC/noodles
noodles/workflow/arguments.py
set_argument
def set_argument(bound_args, address, value): """ Taking a bound_args object, and an |ArgumentAddress| and a value, sets the value pointed to by the address to `value`.""" if address.kind == ArgumentKind.regular: bound_args.arguments[address.name] = value return if address.kind == ArgumentKind.variadic: if address.name not in bound_args.arguments: bound_args.arguments[address.name] = [] n_args = len(bound_args.arguments[address.name]) if address.key >= n_args: bound_args.arguments[address.name].extend( repeat(Empty, address.key - n_args + 1)) if address.kind == ArgumentKind.keyword: if address.name not in bound_args.arguments: bound_args.arguments[address.name] = {} bound_args.arguments[address.name][address.key] = value
python
def set_argument(bound_args, address, value): """ Taking a bound_args object, and an |ArgumentAddress| and a value, sets the value pointed to by the address to `value`.""" if address.kind == ArgumentKind.regular: bound_args.arguments[address.name] = value return if address.kind == ArgumentKind.variadic: if address.name not in bound_args.arguments: bound_args.arguments[address.name] = [] n_args = len(bound_args.arguments[address.name]) if address.key >= n_args: bound_args.arguments[address.name].extend( repeat(Empty, address.key - n_args + 1)) if address.kind == ArgumentKind.keyword: if address.name not in bound_args.arguments: bound_args.arguments[address.name] = {} bound_args.arguments[address.name][address.key] = value
[ "def", "set_argument", "(", "bound_args", ",", "address", ",", "value", ")", ":", "if", "address", ".", "kind", "==", "ArgumentKind", ".", "regular", ":", "bound_args", ".", "arguments", "[", "address", ".", "name", "]", "=", "value", "return", "if", "ad...
Taking a bound_args object, and an |ArgumentAddress| and a value, sets the value pointed to by the address to `value`.
[ "Taking", "a", "bound_args", "object", "and", "an", "|ArgumentAddress|", "and", "a", "value", "sets", "the", "value", "pointed", "to", "by", "the", "address", "to", "value", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/workflow/arguments.py#L75-L95
train
30,918
NLeSC/noodles
noodles/workflow/arguments.py
format_address
def format_address(address): """Formats an ArgumentAddress for human reading.""" if address.kind == ArgumentKind.regular: return address.name return "{0}[{1}]".format(address.name, address.key)
python
def format_address(address): """Formats an ArgumentAddress for human reading.""" if address.kind == ArgumentKind.regular: return address.name return "{0}[{1}]".format(address.name, address.key)
[ "def", "format_address", "(", "address", ")", ":", "if", "address", ".", "kind", "==", "ArgumentKind", ".", "regular", ":", "return", "address", ".", "name", "return", "\"{0}[{1}]\"", ".", "format", "(", "address", ".", "name", ",", "address", ".", "key", ...
Formats an ArgumentAddress for human reading.
[ "Formats", "an", "ArgumentAddress", "for", "human", "reading", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/workflow/arguments.py#L98-L103
train
30,919
NLeSC/noodles
noodles/run/threading/vanilla.py
run_parallel
def run_parallel(workflow, n_threads): """Run a workflow in parallel threads. :param workflow: Workflow or PromisedObject to evaluate. :param n_threads: number of threads to use (in addition to the scheduler). :returns: evaluated workflow. """ scheduler = Scheduler() threaded_worker = Queue() >> thread_pool( *repeat(worker, n_threads)) return scheduler.run(threaded_worker, get_workflow(workflow))
python
def run_parallel(workflow, n_threads): """Run a workflow in parallel threads. :param workflow: Workflow or PromisedObject to evaluate. :param n_threads: number of threads to use (in addition to the scheduler). :returns: evaluated workflow. """ scheduler = Scheduler() threaded_worker = Queue() >> thread_pool( *repeat(worker, n_threads)) return scheduler.run(threaded_worker, get_workflow(workflow))
[ "def", "run_parallel", "(", "workflow", ",", "n_threads", ")", ":", "scheduler", "=", "Scheduler", "(", ")", "threaded_worker", "=", "Queue", "(", ")", ">>", "thread_pool", "(", "*", "repeat", "(", "worker", ",", "n_threads", ")", ")", "return", "scheduler...
Run a workflow in parallel threads. :param workflow: Workflow or PromisedObject to evaluate. :param n_threads: number of threads to use (in addition to the scheduler). :returns: evaluated workflow.
[ "Run", "a", "workflow", "in", "parallel", "threads", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/threading/vanilla.py#L9-L20
train
30,920
NLeSC/noodles
noodles/lib/thread_pool.py
thread_counter
def thread_counter(finalize): """Modifies a thread target function, such that the number of active threads is counted. If the count reaches zero, a finalizer is called.""" n_threads = 0 lock = threading.Lock() def target_modifier(target): @functools.wraps(target) def modified_target(*args, **kwargs): nonlocal n_threads, lock with lock: n_threads += 1 return_value = target(*args, **kwargs) with lock: n_threads -= 1 if n_threads == 0: finalize() return return_value return modified_target return target_modifier
python
def thread_counter(finalize): """Modifies a thread target function, such that the number of active threads is counted. If the count reaches zero, a finalizer is called.""" n_threads = 0 lock = threading.Lock() def target_modifier(target): @functools.wraps(target) def modified_target(*args, **kwargs): nonlocal n_threads, lock with lock: n_threads += 1 return_value = target(*args, **kwargs) with lock: n_threads -= 1 if n_threads == 0: finalize() return return_value return modified_target return target_modifier
[ "def", "thread_counter", "(", "finalize", ")", ":", "n_threads", "=", "0", "lock", "=", "threading", ".", "Lock", "(", ")", "def", "target_modifier", "(", "target", ")", ":", "@", "functools", ".", "wraps", "(", "target", ")", "def", "modified_target", "...
Modifies a thread target function, such that the number of active threads is counted. If the count reaches zero, a finalizer is called.
[ "Modifies", "a", "thread", "target", "function", "such", "that", "the", "number", "of", "active", "threads", "is", "counted", ".", "If", "the", "count", "reaches", "zero", "a", "finalizer", "is", "called", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/thread_pool.py#L7-L32
train
30,921
NLeSC/noodles
noodles/lib/thread_pool.py
thread_pool
def thread_pool(*workers, results=None, end_of_queue=EndOfQueue): """Returns a |pull| object, call it ``r``, starting a thread for each given worker. Each thread pulls from the source that ``r`` is connected to, and the returned results are pushed to a |Queue|. ``r`` yields from the other end of the same |Queue|. The target function for each thread is |patch|, which can be stopped by exhausting the source. If all threads have ended, the result queue receives end-of-queue. :param results: If results should go somewhere else than a newly constructed |Queue|, a different |Connection| object can be given. :type results: |Connection| :param end_of_queue: end-of-queue signal object passed on to the creation of the |Queue| object. :rtype: |pull| """ if results is None: results = Queue(end_of_queue=end_of_queue) count = thread_counter(results.close) @pull def thread_pool_results(source): for worker in workers: t = threading.Thread( target=count(patch), args=(pull(source) >> worker, results.sink), daemon=True) t.start() yield from results.source() return thread_pool_results
python
def thread_pool(*workers, results=None, end_of_queue=EndOfQueue): """Returns a |pull| object, call it ``r``, starting a thread for each given worker. Each thread pulls from the source that ``r`` is connected to, and the returned results are pushed to a |Queue|. ``r`` yields from the other end of the same |Queue|. The target function for each thread is |patch|, which can be stopped by exhausting the source. If all threads have ended, the result queue receives end-of-queue. :param results: If results should go somewhere else than a newly constructed |Queue|, a different |Connection| object can be given. :type results: |Connection| :param end_of_queue: end-of-queue signal object passed on to the creation of the |Queue| object. :rtype: |pull| """ if results is None: results = Queue(end_of_queue=end_of_queue) count = thread_counter(results.close) @pull def thread_pool_results(source): for worker in workers: t = threading.Thread( target=count(patch), args=(pull(source) >> worker, results.sink), daemon=True) t.start() yield from results.source() return thread_pool_results
[ "def", "thread_pool", "(", "*", "workers", ",", "results", "=", "None", ",", "end_of_queue", "=", "EndOfQueue", ")", ":", "if", "results", "is", "None", ":", "results", "=", "Queue", "(", "end_of_queue", "=", "end_of_queue", ")", "count", "=", "thread_coun...
Returns a |pull| object, call it ``r``, starting a thread for each given worker. Each thread pulls from the source that ``r`` is connected to, and the returned results are pushed to a |Queue|. ``r`` yields from the other end of the same |Queue|. The target function for each thread is |patch|, which can be stopped by exhausting the source. If all threads have ended, the result queue receives end-of-queue. :param results: If results should go somewhere else than a newly constructed |Queue|, a different |Connection| object can be given. :type results: |Connection| :param end_of_queue: end-of-queue signal object passed on to the creation of the |Queue| object. :rtype: |pull|
[ "Returns", "a", "|pull|", "object", "call", "it", "r", "starting", "a", "thread", "for", "each", "given", "worker", ".", "Each", "thread", "pulls", "from", "the", "source", "that", "r", "is", "connected", "to", "and", "the", "returned", "results", "are", ...
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/thread_pool.py#L35-L71
train
30,922
NLeSC/noodles
examples/soba/soba.py
run
def run(wf, *, display, n_threads=1): """Run the workflow using the dynamic-exclusion worker.""" worker = dynamic_exclusion_worker(display, n_threads) return noodles.Scheduler(error_handler=display.error_handler)\ .run(worker, get_workflow(wf))
python
def run(wf, *, display, n_threads=1): """Run the workflow using the dynamic-exclusion worker.""" worker = dynamic_exclusion_worker(display, n_threads) return noodles.Scheduler(error_handler=display.error_handler)\ .run(worker, get_workflow(wf))
[ "def", "run", "(", "wf", ",", "*", ",", "display", ",", "n_threads", "=", "1", ")", ":", "worker", "=", "dynamic_exclusion_worker", "(", "display", ",", "n_threads", ")", "return", "noodles", ".", "Scheduler", "(", "error_handler", "=", "display", ".", "...
Run the workflow using the dynamic-exclusion worker.
[ "Run", "the", "workflow", "using", "the", "dynamic", "-", "exclusion", "worker", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/examples/soba/soba.py#L128-L132
train
30,923
NLeSC/noodles
noodles/interface/functions.py
create_object
def create_object(cls, members): """Promise an object of class `cls` with content `members`.""" obj = cls.__new__(cls) obj.__dict__ = members return obj
python
def create_object(cls, members): """Promise an object of class `cls` with content `members`.""" obj = cls.__new__(cls) obj.__dict__ = members return obj
[ "def", "create_object", "(", "cls", ",", "members", ")", ":", "obj", "=", "cls", ".", "__new__", "(", "cls", ")", "obj", ".", "__dict__", "=", "members", "return", "obj" ]
Promise an object of class `cls` with content `members`.
[ "Promise", "an", "object", "of", "class", "cls", "with", "content", "members", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/interface/functions.py#L83-L87
train
30,924
NLeSC/noodles
noodles/interface/functions.py
lift
def lift(obj, memo=None): """Make a promise out of object `obj`, where `obj` may contain promises internally. :param obj: Any object. :param memo: used for internal caching (similar to :func:`deepcopy`). If the object is a :class:`PromisedObject`, or *pass-by-value* (:class:`str`, :class:`int`, :class:`float`, :class:`complex`) it is returned as is. If the object's `id` has an entry in `memo`, the value from `memo` is returned. If the object has a method `__lift__`, it is used to get the promise. `__lift__` should take one additional argument for the `memo` dictionary, entirely analogous to :func:`deepcopy`. If the object is an instance of one of the basic container types (list, dictionary, tuple and set), we use the analogous function (:func:`make_list`, :func:`make_dict`, :func:`make_tuple`, and :func:`make_set`) to promise their counterparts should these objects contain any promises. First, we map all items in the container through :func:`lift`, then check the result for any promises. Note that in the case of dictionaries, we lift all the items (i.e. the list of key/value tuples) and then construct a new dictionary. If the object is an instance of a subclass of any of the basic container types, the `__dict__` of the object is lifted as well as the object cast to its base type. We then use :func:`set_dict` to set the `__dict__` of the new promise. Again, if the object did not contain any promises, we return it without change. Otherwise, we lift the `__dict__` and create a promise of a new object of the same class as the input, using :func:`create_object`. This works fine for what we call *reasonable* objects. Since calling :func:`lift` is an explicit action, we do not require reasonable objects to be derived from :class:`Reasonable` as we do with serialisation, where such a default behaviour could lead to unexplicable bugs.""" if memo is None: memo = {} if isinstance(obj, (PromisedObject, str, int, float, complex)): return obj if id(obj) in memo: return memo[id(obj)] if hasattr(obj, '__lift__'): rv = obj.__lift__(memo) memo[id(obj)] = rv return rv actions = { list: (lambda x: x, make_list), dict: (lambda x: list(x.items()), make_dict), tuple: (lambda x: x, make_tuple), set: (lambda x: x, make_set) } if obj.__class__ in actions: items, construct = actions[obj.__class__] tmp = [lift(a, memo) for a in items(obj)] if any(isinstance(a, PromisedObject) for a in tmp): rv = construct(*tmp) memo[id(obj)] = rv return rv else: memo[id(obj)] = obj return obj subclass = next(filter( lambda x: issubclass(obj.__class__, x), actions.keys()), None) if subclass: members = lift(obj.__dict__, memo) internal = lift(subclass(obj), memo) if isinstance(internal, PromisedObject): internal = construct_object(obj.__class__, internal) rv = set_dict(internal, members) elif isinstance(members, PromisedObject): rv = set_dict(obj.__class__(internal), members) else: rv = obj memo[id(obj)] = rv return rv try: members = lift(obj.__dict__, memo) if isinstance(members, PromisedObject): rv = create_object(obj.__class__, members) else: rv = obj except AttributeError: memo[id(obj)] = obj return obj memo[id(obj)] = rv return rv
python
def lift(obj, memo=None): """Make a promise out of object `obj`, where `obj` may contain promises internally. :param obj: Any object. :param memo: used for internal caching (similar to :func:`deepcopy`). If the object is a :class:`PromisedObject`, or *pass-by-value* (:class:`str`, :class:`int`, :class:`float`, :class:`complex`) it is returned as is. If the object's `id` has an entry in `memo`, the value from `memo` is returned. If the object has a method `__lift__`, it is used to get the promise. `__lift__` should take one additional argument for the `memo` dictionary, entirely analogous to :func:`deepcopy`. If the object is an instance of one of the basic container types (list, dictionary, tuple and set), we use the analogous function (:func:`make_list`, :func:`make_dict`, :func:`make_tuple`, and :func:`make_set`) to promise their counterparts should these objects contain any promises. First, we map all items in the container through :func:`lift`, then check the result for any promises. Note that in the case of dictionaries, we lift all the items (i.e. the list of key/value tuples) and then construct a new dictionary. If the object is an instance of a subclass of any of the basic container types, the `__dict__` of the object is lifted as well as the object cast to its base type. We then use :func:`set_dict` to set the `__dict__` of the new promise. Again, if the object did not contain any promises, we return it without change. Otherwise, we lift the `__dict__` and create a promise of a new object of the same class as the input, using :func:`create_object`. This works fine for what we call *reasonable* objects. Since calling :func:`lift` is an explicit action, we do not require reasonable objects to be derived from :class:`Reasonable` as we do with serialisation, where such a default behaviour could lead to unexplicable bugs.""" if memo is None: memo = {} if isinstance(obj, (PromisedObject, str, int, float, complex)): return obj if id(obj) in memo: return memo[id(obj)] if hasattr(obj, '__lift__'): rv = obj.__lift__(memo) memo[id(obj)] = rv return rv actions = { list: (lambda x: x, make_list), dict: (lambda x: list(x.items()), make_dict), tuple: (lambda x: x, make_tuple), set: (lambda x: x, make_set) } if obj.__class__ in actions: items, construct = actions[obj.__class__] tmp = [lift(a, memo) for a in items(obj)] if any(isinstance(a, PromisedObject) for a in tmp): rv = construct(*tmp) memo[id(obj)] = rv return rv else: memo[id(obj)] = obj return obj subclass = next(filter( lambda x: issubclass(obj.__class__, x), actions.keys()), None) if subclass: members = lift(obj.__dict__, memo) internal = lift(subclass(obj), memo) if isinstance(internal, PromisedObject): internal = construct_object(obj.__class__, internal) rv = set_dict(internal, members) elif isinstance(members, PromisedObject): rv = set_dict(obj.__class__(internal), members) else: rv = obj memo[id(obj)] = rv return rv try: members = lift(obj.__dict__, memo) if isinstance(members, PromisedObject): rv = create_object(obj.__class__, members) else: rv = obj except AttributeError: memo[id(obj)] = obj return obj memo[id(obj)] = rv return rv
[ "def", "lift", "(", "obj", ",", "memo", "=", "None", ")", ":", "if", "memo", "is", "None", ":", "memo", "=", "{", "}", "if", "isinstance", "(", "obj", ",", "(", "PromisedObject", ",", "str", ",", "int", ",", "float", ",", "complex", ")", ")", "...
Make a promise out of object `obj`, where `obj` may contain promises internally. :param obj: Any object. :param memo: used for internal caching (similar to :func:`deepcopy`). If the object is a :class:`PromisedObject`, or *pass-by-value* (:class:`str`, :class:`int`, :class:`float`, :class:`complex`) it is returned as is. If the object's `id` has an entry in `memo`, the value from `memo` is returned. If the object has a method `__lift__`, it is used to get the promise. `__lift__` should take one additional argument for the `memo` dictionary, entirely analogous to :func:`deepcopy`. If the object is an instance of one of the basic container types (list, dictionary, tuple and set), we use the analogous function (:func:`make_list`, :func:`make_dict`, :func:`make_tuple`, and :func:`make_set`) to promise their counterparts should these objects contain any promises. First, we map all items in the container through :func:`lift`, then check the result for any promises. Note that in the case of dictionaries, we lift all the items (i.e. the list of key/value tuples) and then construct a new dictionary. If the object is an instance of a subclass of any of the basic container types, the `__dict__` of the object is lifted as well as the object cast to its base type. We then use :func:`set_dict` to set the `__dict__` of the new promise. Again, if the object did not contain any promises, we return it without change. Otherwise, we lift the `__dict__` and create a promise of a new object of the same class as the input, using :func:`create_object`. This works fine for what we call *reasonable* objects. Since calling :func:`lift` is an explicit action, we do not require reasonable objects to be derived from :class:`Reasonable` as we do with serialisation, where such a default behaviour could lead to unexplicable bugs.
[ "Make", "a", "promise", "out", "of", "object", "obj", "where", "obj", "may", "contain", "promises", "internally", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/interface/functions.py#L152-L253
train
30,925
NLeSC/noodles
noodles/lib/streams.py
branch
def branch(*sinks_): """The |branch| decorator creates a |pull| object that pulls from a single source and then sends to all the sinks given. After all the sinks received the message, it is yielded. .. |branch| replace:: :py:func:`branch` """ @pull def junction(source): sinks = [s() for s in sinks_] for msg in source(): for s in sinks: s.send(msg) yield msg return junction
python
def branch(*sinks_): """The |branch| decorator creates a |pull| object that pulls from a single source and then sends to all the sinks given. After all the sinks received the message, it is yielded. .. |branch| replace:: :py:func:`branch` """ @pull def junction(source): sinks = [s() for s in sinks_] for msg in source(): for s in sinks: s.send(msg) yield msg return junction
[ "def", "branch", "(", "*", "sinks_", ")", ":", "@", "pull", "def", "junction", "(", "source", ")", ":", "sinks", "=", "[", "s", "(", ")", "for", "s", "in", "sinks_", "]", "for", "msg", "in", "source", "(", ")", ":", "for", "s", "in", "sinks", ...
The |branch| decorator creates a |pull| object that pulls from a single source and then sends to all the sinks given. After all the sinks received the message, it is yielded. .. |branch| replace:: :py:func:`branch`
[ "The", "|branch|", "decorator", "creates", "a", "|pull|", "object", "that", "pulls", "from", "a", "single", "source", "and", "then", "sends", "to", "all", "the", "sinks", "given", ".", "After", "all", "the", "sinks", "received", "the", "message", "it", "is...
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/streams.py#L193-L209
train
30,926
NLeSC/noodles
noodles/lib/streams.py
broadcast
def broadcast(*sinks_): """The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast` """ @push def bc(): sinks = [s() for s in sinks_] while True: msg = yield for s in sinks: s.send(msg) return bc
python
def broadcast(*sinks_): """The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast` """ @push def bc(): sinks = [s() for s in sinks_] while True: msg = yield for s in sinks: s.send(msg) return bc
[ "def", "broadcast", "(", "*", "sinks_", ")", ":", "@", "push", "def", "bc", "(", ")", ":", "sinks", "=", "[", "s", "(", ")", "for", "s", "in", "sinks_", "]", "while", "True", ":", "msg", "=", "yield", "for", "s", "in", "sinks", ":", "s", ".",...
The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast`
[ "The", "|broadcast|", "decorator", "creates", "a", "|push|", "object", "that", "receives", "a", "message", "by", "yield", "and", "then", "sends", "this", "message", "on", "to", "all", "the", "given", "sinks", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/streams.py#L212-L226
train
30,927
NLeSC/noodles
noodles/lib/streams.py
push_from
def push_from(iterable): """Creates a |push| object from an iterable. The resulting function is not a coroutine, but can be chained to another |push|. :param iterable: an iterable object. :type iterable: :py:class:`~collections.abc.Iterable` :rtype: |push| """ def p(sink): sink = sink() for x in iterable: sink.send(x) return push(p, dont_wrap=True)
python
def push_from(iterable): """Creates a |push| object from an iterable. The resulting function is not a coroutine, but can be chained to another |push|. :param iterable: an iterable object. :type iterable: :py:class:`~collections.abc.Iterable` :rtype: |push| """ def p(sink): sink = sink() for x in iterable: sink.send(x) return push(p, dont_wrap=True)
[ "def", "push_from", "(", "iterable", ")", ":", "def", "p", "(", "sink", ")", ":", "sink", "=", "sink", "(", ")", "for", "x", "in", "iterable", ":", "sink", ".", "send", "(", "x", ")", "return", "push", "(", "p", ",", "dont_wrap", "=", "True", "...
Creates a |push| object from an iterable. The resulting function is not a coroutine, but can be chained to another |push|. :param iterable: an iterable object. :type iterable: :py:class:`~collections.abc.Iterable` :rtype: |push|
[ "Creates", "a", "|push|", "object", "from", "an", "iterable", ".", "The", "resulting", "function", "is", "not", "a", "coroutine", "but", "can", "be", "chained", "to", "another", "|push|", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/streams.py#L243-L256
train
30,928
NLeSC/noodles
noodles/lib/streams.py
patch
def patch(source, sink): """Create a direct link between a source and a sink. Implementation:: sink = sink() for value in source(): sink.send(value) .. |patch| replace:: :py:func:`patch` """ sink = sink() for v in source(): try: sink.send(v) except StopIteration: return
python
def patch(source, sink): """Create a direct link between a source and a sink. Implementation:: sink = sink() for value in source(): sink.send(value) .. |patch| replace:: :py:func:`patch` """ sink = sink() for v in source(): try: sink.send(v) except StopIteration: return
[ "def", "patch", "(", "source", ",", "sink", ")", ":", "sink", "=", "sink", "(", ")", "for", "v", "in", "source", "(", ")", ":", "try", ":", "sink", ".", "send", "(", "v", ")", "except", "StopIteration", ":", "return" ]
Create a direct link between a source and a sink. Implementation:: sink = sink() for value in source(): sink.send(value) .. |patch| replace:: :py:func:`patch`
[ "Create", "a", "direct", "link", "between", "a", "source", "and", "a", "sink", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/streams.py#L259-L275
train
30,929
NLeSC/noodles
noodles/patterns/control_flow_statements.py
conditional
def conditional( b: bool, branch_true: Any, branch_false: Any=None) -> Any: """ Control statement to follow a branch in workflow. Equivalent to the `if` statement in standard Python. The quote function delay the evaluation of the branches until the boolean is evaluated. :param b: promised boolean value. :param branch_true: statement to execute in case of a true predicate. :param branch_false: default operation to execute in case of a false predicate. :returns: :py:class:`PromisedObject` """ return schedule_branches(b, quote(branch_true), quote(branch_false))
python
def conditional( b: bool, branch_true: Any, branch_false: Any=None) -> Any: """ Control statement to follow a branch in workflow. Equivalent to the `if` statement in standard Python. The quote function delay the evaluation of the branches until the boolean is evaluated. :param b: promised boolean value. :param branch_true: statement to execute in case of a true predicate. :param branch_false: default operation to execute in case of a false predicate. :returns: :py:class:`PromisedObject` """ return schedule_branches(b, quote(branch_true), quote(branch_false))
[ "def", "conditional", "(", "b", ":", "bool", ",", "branch_true", ":", "Any", ",", "branch_false", ":", "Any", "=", "None", ")", "->", "Any", ":", "return", "schedule_branches", "(", "b", ",", "quote", "(", "branch_true", ")", ",", "quote", "(", "branch...
Control statement to follow a branch in workflow. Equivalent to the `if` statement in standard Python. The quote function delay the evaluation of the branches until the boolean is evaluated. :param b: promised boolean value. :param branch_true: statement to execute in case of a true predicate. :param branch_false: default operation to execute in case of a false predicate. :returns: :py:class:`PromisedObject`
[ "Control", "statement", "to", "follow", "a", "branch", "in", "workflow", ".", "Equivalent", "to", "the", "if", "statement", "in", "standard", "Python", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/patterns/control_flow_statements.py#L5-L25
train
30,930
NLeSC/noodles
noodles/patterns/control_flow_statements.py
schedule_branches
def schedule_branches(b: bool, quoted_true, quoted_false): """ Helper function to choose which workflow to execute based on the boolean `b`. :param b: promised boolean value :param quoted_true: quoted workflow to eval if the boolean is true. :param quoted_true: quoted workflow to eval if the boolean is false. """ if b: return unquote(quoted_true) else: return unquote(quoted_false)
python
def schedule_branches(b: bool, quoted_true, quoted_false): """ Helper function to choose which workflow to execute based on the boolean `b`. :param b: promised boolean value :param quoted_true: quoted workflow to eval if the boolean is true. :param quoted_true: quoted workflow to eval if the boolean is false. """ if b: return unquote(quoted_true) else: return unquote(quoted_false)
[ "def", "schedule_branches", "(", "b", ":", "bool", ",", "quoted_true", ",", "quoted_false", ")", ":", "if", "b", ":", "return", "unquote", "(", "quoted_true", ")", "else", ":", "return", "unquote", "(", "quoted_false", ")" ]
Helper function to choose which workflow to execute based on the boolean `b`. :param b: promised boolean value :param quoted_true: quoted workflow to eval if the boolean is true. :param quoted_true: quoted workflow to eval if the boolean is false.
[ "Helper", "function", "to", "choose", "which", "workflow", "to", "execute", "based", "on", "the", "boolean", "b", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/patterns/control_flow_statements.py#L29-L44
train
30,931
NLeSC/noodles
noodles/serial/numpy.py
array_sha256
def array_sha256(a): """Create a SHA256 hash from a Numpy array.""" dtype = str(a.dtype).encode() shape = numpy.array(a.shape) sha = hashlib.sha256() sha.update(dtype) sha.update(shape) sha.update(a.tobytes()) return sha.hexdigest()
python
def array_sha256(a): """Create a SHA256 hash from a Numpy array.""" dtype = str(a.dtype).encode() shape = numpy.array(a.shape) sha = hashlib.sha256() sha.update(dtype) sha.update(shape) sha.update(a.tobytes()) return sha.hexdigest()
[ "def", "array_sha256", "(", "a", ")", ":", "dtype", "=", "str", "(", "a", ".", "dtype", ")", ".", "encode", "(", ")", "shape", "=", "numpy", ".", "array", "(", "a", ".", "shape", ")", "sha", "=", "hashlib", ".", "sha256", "(", ")", "sha", ".", ...
Create a SHA256 hash from a Numpy array.
[ "Create", "a", "SHA256", "hash", "from", "a", "Numpy", "array", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/numpy.py#L62-L70
train
30,932
NLeSC/noodles
noodles/serial/numpy.py
arrays_to_file
def arrays_to_file(file_prefix=None): """Returns a serialisation registry for serialising NumPy data and as well as any UFuncs that have no normal way of retrieving qualified names.""" return Registry( types={ numpy.ndarray: SerNumpyArrayToFile(file_prefix) }, hooks={ '<ufunc>': SerUFunc() }, hook_fn=_numpy_hook )
python
def arrays_to_file(file_prefix=None): """Returns a serialisation registry for serialising NumPy data and as well as any UFuncs that have no normal way of retrieving qualified names.""" return Registry( types={ numpy.ndarray: SerNumpyArrayToFile(file_prefix) }, hooks={ '<ufunc>': SerUFunc() }, hook_fn=_numpy_hook )
[ "def", "arrays_to_file", "(", "file_prefix", "=", "None", ")", ":", "return", "Registry", "(", "types", "=", "{", "numpy", ".", "ndarray", ":", "SerNumpyArrayToFile", "(", "file_prefix", ")", "}", ",", "hooks", "=", "{", "'<ufunc>'", ":", "SerUFunc", "(", ...
Returns a serialisation registry for serialising NumPy data and as well as any UFuncs that have no normal way of retrieving qualified names.
[ "Returns", "a", "serialisation", "registry", "for", "serialising", "NumPy", "data", "and", "as", "well", "as", "any", "UFuncs", "that", "have", "no", "normal", "way", "of", "retrieving", "qualified", "names", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/numpy.py#L129-L141
train
30,933
NLeSC/noodles
noodles/serial/numpy.py
arrays_to_string
def arrays_to_string(file_prefix=None): """Returns registry for serialising arrays as a Base64 string.""" return Registry( types={ numpy.ndarray: SerNumpyArray(), numpy.floating: SerNumpyScalar() }, hooks={ '<ufunc>': SerUFunc() }, hook_fn=_numpy_hook )
python
def arrays_to_string(file_prefix=None): """Returns registry for serialising arrays as a Base64 string.""" return Registry( types={ numpy.ndarray: SerNumpyArray(), numpy.floating: SerNumpyScalar() }, hooks={ '<ufunc>': SerUFunc() }, hook_fn=_numpy_hook )
[ "def", "arrays_to_string", "(", "file_prefix", "=", "None", ")", ":", "return", "Registry", "(", "types", "=", "{", "numpy", ".", "ndarray", ":", "SerNumpyArray", "(", ")", ",", "numpy", ".", "floating", ":", "SerNumpyScalar", "(", ")", "}", ",", "hooks"...
Returns registry for serialising arrays as a Base64 string.
[ "Returns", "registry", "for", "serialising", "arrays", "as", "a", "Base64", "string", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/numpy.py#L144-L155
train
30,934
NLeSC/noodles
noodles/serial/numpy.py
arrays_to_hdf5
def arrays_to_hdf5(filename="cache.hdf5"): """Returns registry for serialising arrays to a HDF5 reference.""" return Registry( types={ numpy.ndarray: SerNumpyArrayToHDF5(filename, "cache.lock") }, hooks={ '<ufunc>': SerUFunc() }, hook_fn=_numpy_hook )
python
def arrays_to_hdf5(filename="cache.hdf5"): """Returns registry for serialising arrays to a HDF5 reference.""" return Registry( types={ numpy.ndarray: SerNumpyArrayToHDF5(filename, "cache.lock") }, hooks={ '<ufunc>': SerUFunc() }, hook_fn=_numpy_hook )
[ "def", "arrays_to_hdf5", "(", "filename", "=", "\"cache.hdf5\"", ")", ":", "return", "Registry", "(", "types", "=", "{", "numpy", ".", "ndarray", ":", "SerNumpyArrayToHDF5", "(", "filename", ",", "\"cache.lock\"", ")", "}", ",", "hooks", "=", "{", "'<ufunc>'...
Returns registry for serialising arrays to a HDF5 reference.
[ "Returns", "registry", "for", "serialising", "arrays", "to", "a", "HDF5", "reference", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/numpy.py#L158-L168
train
30,935
NLeSC/noodles
noodles/run/xenon/runner.py
run_xenon_simple
def run_xenon_simple(workflow, machine, worker_config): """Run a workflow using a single Xenon remote worker. :param workflow: |Workflow| or |PromisedObject| to evaluate. :param machine: |Machine| instance. :param worker_config: Configuration for the pilot job.""" scheduler = Scheduler() return scheduler.run( xenon_interactive_worker(machine, worker_config), get_workflow(workflow) )
python
def run_xenon_simple(workflow, machine, worker_config): """Run a workflow using a single Xenon remote worker. :param workflow: |Workflow| or |PromisedObject| to evaluate. :param machine: |Machine| instance. :param worker_config: Configuration for the pilot job.""" scheduler = Scheduler() return scheduler.run( xenon_interactive_worker(machine, worker_config), get_workflow(workflow) )
[ "def", "run_xenon_simple", "(", "workflow", ",", "machine", ",", "worker_config", ")", ":", "scheduler", "=", "Scheduler", "(", ")", "return", "scheduler", ".", "run", "(", "xenon_interactive_worker", "(", "machine", ",", "worker_config", ")", ",", "get_workflow...
Run a workflow using a single Xenon remote worker. :param workflow: |Workflow| or |PromisedObject| to evaluate. :param machine: |Machine| instance. :param worker_config: Configuration for the pilot job.
[ "Run", "a", "workflow", "using", "a", "single", "Xenon", "remote", "worker", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/xenon/runner.py#L10-L21
train
30,936
NLeSC/noodles
noodles/run/xenon/runner.py
run_xenon
def run_xenon( workflow, *, machine, worker_config, n_processes, deref=False, verbose=False): """Run the workflow using a number of online Xenon workers. :param workflow: |Workflow| or |PromisedObject| to evaluate. :param machine: The |Machine| instance. :param worker_config: Configuration of the pilot job :param n_processes: Number of pilot jobs to start. :param deref: Set this to True to pass the result through one more encoding and decoding step with object dereferencing turned on. :returns: the result of evaluating the workflow """ dynamic_pool = DynamicPool(machine) for i in range(n_processes): cfg = copy(worker_config) cfg.name = 'xenon-{0:02}'.format(i) dynamic_pool.add_xenon_worker(cfg) job_keeper = JobKeeper() S = Scheduler(job_keeper=job_keeper, verbose=verbose) result = S.run( dynamic_pool, get_workflow(workflow) ) dynamic_pool.close_all() if deref: return worker_config.registry().dereference(result, host='scheduler') else: return result
python
def run_xenon( workflow, *, machine, worker_config, n_processes, deref=False, verbose=False): """Run the workflow using a number of online Xenon workers. :param workflow: |Workflow| or |PromisedObject| to evaluate. :param machine: The |Machine| instance. :param worker_config: Configuration of the pilot job :param n_processes: Number of pilot jobs to start. :param deref: Set this to True to pass the result through one more encoding and decoding step with object dereferencing turned on. :returns: the result of evaluating the workflow """ dynamic_pool = DynamicPool(machine) for i in range(n_processes): cfg = copy(worker_config) cfg.name = 'xenon-{0:02}'.format(i) dynamic_pool.add_xenon_worker(cfg) job_keeper = JobKeeper() S = Scheduler(job_keeper=job_keeper, verbose=verbose) result = S.run( dynamic_pool, get_workflow(workflow) ) dynamic_pool.close_all() if deref: return worker_config.registry().dereference(result, host='scheduler') else: return result
[ "def", "run_xenon", "(", "workflow", ",", "*", ",", "machine", ",", "worker_config", ",", "n_processes", ",", "deref", "=", "False", ",", "verbose", "=", "False", ")", ":", "dynamic_pool", "=", "DynamicPool", "(", "machine", ")", "for", "i", "in", "range...
Run the workflow using a number of online Xenon workers. :param workflow: |Workflow| or |PromisedObject| to evaluate. :param machine: The |Machine| instance. :param worker_config: Configuration of the pilot job :param n_processes: Number of pilot jobs to start. :param deref: Set this to True to pass the result through one more encoding and decoding step with object dereferencing turned on. :returns: the result of evaluating the workflow
[ "Run", "the", "workflow", "using", "a", "number", "of", "online", "Xenon", "workers", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/xenon/runner.py#L24-L57
train
30,937
NLeSC/noodles
noodles/run/threading/sqlite3.py
pass_job
def pass_job(db: JobDB, result_queue: Queue, always_cache=False): """Create a pull stream that receives jobs and passes them on to the database. If the job already has a result, that result is pushed onto the `result_queue`. """ @pull def pass_job_stream(job_source): """Pull stream instance created by `pass_job`.""" result_sink = result_queue.sink() for message in job_source(): if message is EndOfQueue: return key, job = message if always_cache or ('store' in job.hints): status, retrieved_result = db.add_job_to_db(key, job) if status == 'retrieved': result_sink.send(retrieved_result) continue elif status == 'attached': continue yield message return pass_job_stream
python
def pass_job(db: JobDB, result_queue: Queue, always_cache=False): """Create a pull stream that receives jobs and passes them on to the database. If the job already has a result, that result is pushed onto the `result_queue`. """ @pull def pass_job_stream(job_source): """Pull stream instance created by `pass_job`.""" result_sink = result_queue.sink() for message in job_source(): if message is EndOfQueue: return key, job = message if always_cache or ('store' in job.hints): status, retrieved_result = db.add_job_to_db(key, job) if status == 'retrieved': result_sink.send(retrieved_result) continue elif status == 'attached': continue yield message return pass_job_stream
[ "def", "pass_job", "(", "db", ":", "JobDB", ",", "result_queue", ":", "Queue", ",", "always_cache", "=", "False", ")", ":", "@", "pull", "def", "pass_job_stream", "(", "job_source", ")", ":", "\"\"\"Pull stream instance created by `pass_job`.\"\"\"", "result_sink", ...
Create a pull stream that receives jobs and passes them on to the database. If the job already has a result, that result is pushed onto the `result_queue`.
[ "Create", "a", "pull", "stream", "that", "receives", "jobs", "and", "passes", "them", "on", "to", "the", "database", ".", "If", "the", "job", "already", "has", "a", "result", "that", "result", "is", "pushed", "onto", "the", "result_queue", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/threading/sqlite3.py#L20-L47
train
30,938
NLeSC/noodles
noodles/run/threading/sqlite3.py
pass_result
def pass_result(db: JobDB, always_cache=False): """Creates a pull stream receiving results, storing them in the database, then sending them on. At this stage, the database may return a list of attached jobs which also need to be sent on to the scheduler.""" @pull def pass_result_stream(worker_source): """Pull stream instance created by `pass_result`.""" for result in worker_source(): if result is EndOfQueue: return attached = db.store_result_in_db( result, always_cache=always_cache) yield result yield from (ResultMessage(key, 'attached', result.value, None) for key in attached) return pass_result_stream
python
def pass_result(db: JobDB, always_cache=False): """Creates a pull stream receiving results, storing them in the database, then sending them on. At this stage, the database may return a list of attached jobs which also need to be sent on to the scheduler.""" @pull def pass_result_stream(worker_source): """Pull stream instance created by `pass_result`.""" for result in worker_source(): if result is EndOfQueue: return attached = db.store_result_in_db( result, always_cache=always_cache) yield result yield from (ResultMessage(key, 'attached', result.value, None) for key in attached) return pass_result_stream
[ "def", "pass_result", "(", "db", ":", "JobDB", ",", "always_cache", "=", "False", ")", ":", "@", "pull", "def", "pass_result_stream", "(", "worker_source", ")", ":", "\"\"\"Pull stream instance created by `pass_result`.\"\"\"", "for", "result", "in", "worker_source", ...
Creates a pull stream receiving results, storing them in the database, then sending them on. At this stage, the database may return a list of attached jobs which also need to be sent on to the scheduler.
[ "Creates", "a", "pull", "stream", "receiving", "results", "storing", "them", "in", "the", "database", "then", "sending", "them", "on", ".", "At", "this", "stage", "the", "database", "may", "return", "a", "list", "of", "attached", "jobs", "which", "also", "...
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/threading/sqlite3.py#L50-L68
train
30,939
NLeSC/noodles
noodles/run/threading/sqlite3.py
run_parallel
def run_parallel( workflow, *, n_threads, registry, db_file, echo_log=True, always_cache=False): """Run a workflow in parallel threads, storing results in a Sqlite3 database. :param workflow: Workflow or PromisedObject to evaluate. :param n_threads: number of threads to use (in addition to the scheduler). :param registry: serialization Registry function. :param db_file: filename of Sqlite3 database, give `':memory:'` to keep the database in memory only. :param echo_log: set log-level high enough :param always_cache: enable caching by schedule hint. :return: Evaluated result. """ if echo_log: logging.getLogger('noodles').setLevel(logging.DEBUG) logging.debug("--- start log ---") with JobDB(db_file, registry) as db: job_queue = Queue() result_queue = Queue() job_logger = make_logger("worker", push_map, db) result_logger = make_logger("worker", pull_map, db) worker_pool = job_queue.source \ >> pass_job(db, result_queue, always_cache) \ >> thread_pool(*repeat(worker, n_threads), results=result_queue) job_front_end = job_logger >> job_queue.sink result_front_end = worker_pool \ >> pass_result(db, always_cache) \ >> result_logger scheduler = Scheduler(job_keeper=db) parallel_sqlite_worker = Connection(result_front_end, job_front_end) result = scheduler.run(parallel_sqlite_worker, get_workflow(workflow)) return registry().dereference(result)
python
def run_parallel( workflow, *, n_threads, registry, db_file, echo_log=True, always_cache=False): """Run a workflow in parallel threads, storing results in a Sqlite3 database. :param workflow: Workflow or PromisedObject to evaluate. :param n_threads: number of threads to use (in addition to the scheduler). :param registry: serialization Registry function. :param db_file: filename of Sqlite3 database, give `':memory:'` to keep the database in memory only. :param echo_log: set log-level high enough :param always_cache: enable caching by schedule hint. :return: Evaluated result. """ if echo_log: logging.getLogger('noodles').setLevel(logging.DEBUG) logging.debug("--- start log ---") with JobDB(db_file, registry) as db: job_queue = Queue() result_queue = Queue() job_logger = make_logger("worker", push_map, db) result_logger = make_logger("worker", pull_map, db) worker_pool = job_queue.source \ >> pass_job(db, result_queue, always_cache) \ >> thread_pool(*repeat(worker, n_threads), results=result_queue) job_front_end = job_logger >> job_queue.sink result_front_end = worker_pool \ >> pass_result(db, always_cache) \ >> result_logger scheduler = Scheduler(job_keeper=db) parallel_sqlite_worker = Connection(result_front_end, job_front_end) result = scheduler.run(parallel_sqlite_worker, get_workflow(workflow)) return registry().dereference(result)
[ "def", "run_parallel", "(", "workflow", ",", "*", ",", "n_threads", ",", "registry", ",", "db_file", ",", "echo_log", "=", "True", ",", "always_cache", "=", "False", ")", ":", "if", "echo_log", ":", "logging", ".", "getLogger", "(", "'noodles'", ")", "."...
Run a workflow in parallel threads, storing results in a Sqlite3 database. :param workflow: Workflow or PromisedObject to evaluate. :param n_threads: number of threads to use (in addition to the scheduler). :param registry: serialization Registry function. :param db_file: filename of Sqlite3 database, give `':memory:'` to keep the database in memory only. :param echo_log: set log-level high enough :param always_cache: enable caching by schedule hint. :return: Evaluated result.
[ "Run", "a", "workflow", "in", "parallel", "threads", "storing", "results", "in", "a", "Sqlite3", "database", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/threading/sqlite3.py#L71-L110
train
30,940
NLeSC/noodles
noodles/lib/utility.py
is_unwrapped
def is_unwrapped(f): """If `f` was imported and then unwrapped, this function might return True. .. |is_unwrapped| replace:: :py:func:`is_unwrapped`""" try: g = look_up(object_name(f)) return g != f and unwrap(g) == f except (AttributeError, TypeError, ImportError): return False
python
def is_unwrapped(f): """If `f` was imported and then unwrapped, this function might return True. .. |is_unwrapped| replace:: :py:func:`is_unwrapped`""" try: g = look_up(object_name(f)) return g != f and unwrap(g) == f except (AttributeError, TypeError, ImportError): return False
[ "def", "is_unwrapped", "(", "f", ")", ":", "try", ":", "g", "=", "look_up", "(", "object_name", "(", "f", ")", ")", "return", "g", "!=", "f", "and", "unwrap", "(", "g", ")", "==", "f", "except", "(", "AttributeError", ",", "TypeError", ",", "Import...
If `f` was imported and then unwrapped, this function might return True. .. |is_unwrapped| replace:: :py:func:`is_unwrapped`
[ "If", "f", "was", "imported", "and", "then", "unwrapped", "this", "function", "might", "return", "True", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/utility.py#L78-L87
train
30,941
NLeSC/noodles
noodles/lib/utility.py
inverse_deep_map
def inverse_deep_map(f, root): """Sibling to |deep_map|. Recursively maps objects in a nested structure of ``list`` and ``dict`` objects. Where |deep_map| starts at the top, |inverse_deep_map| starts at the bottom. First, if `root` is a ``list`` or ``dict``, its contents are |inverse_deep_map|ed. Then at the end, the entire object is passed through `f`. This function was created with decoding from JSON compatible data in mind. .. |inverse_deep_map| replace:: :py:func:`inverse_deep_map`""" if isinstance(root, dict): r = {k: inverse_deep_map(f, v) for k, v in root.items()} elif isinstance(root, list): r = [inverse_deep_map(f, v) for v in root] else: r = root return f(r)
python
def inverse_deep_map(f, root): """Sibling to |deep_map|. Recursively maps objects in a nested structure of ``list`` and ``dict`` objects. Where |deep_map| starts at the top, |inverse_deep_map| starts at the bottom. First, if `root` is a ``list`` or ``dict``, its contents are |inverse_deep_map|ed. Then at the end, the entire object is passed through `f`. This function was created with decoding from JSON compatible data in mind. .. |inverse_deep_map| replace:: :py:func:`inverse_deep_map`""" if isinstance(root, dict): r = {k: inverse_deep_map(f, v) for k, v in root.items()} elif isinstance(root, list): r = [inverse_deep_map(f, v) for v in root] else: r = root return f(r)
[ "def", "inverse_deep_map", "(", "f", ",", "root", ")", ":", "if", "isinstance", "(", "root", ",", "dict", ")", ":", "r", "=", "{", "k", ":", "inverse_deep_map", "(", "f", ",", "v", ")", "for", "k", ",", "v", "in", "root", ".", "items", "(", ")"...
Sibling to |deep_map|. Recursively maps objects in a nested structure of ``list`` and ``dict`` objects. Where |deep_map| starts at the top, |inverse_deep_map| starts at the bottom. First, if `root` is a ``list`` or ``dict``, its contents are |inverse_deep_map|ed. Then at the end, the entire object is passed through `f`. This function was created with decoding from JSON compatible data in mind. .. |inverse_deep_map| replace:: :py:func:`inverse_deep_map`
[ "Sibling", "to", "|deep_map|", ".", "Recursively", "maps", "objects", "in", "a", "nested", "structure", "of", "list", "and", "dict", "objects", ".", "Where", "|deep_map|", "starts", "at", "the", "top", "|inverse_deep_map|", "starts", "at", "the", "bottom", "."...
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/lib/utility.py#L111-L128
train
30,942
NLeSC/noodles
noodles/serial/registry.py
Registry.decode
def decode(self, rec, deref=False): """Decode a record to return an object that could be considered equivalent to the original. The record is not touched if `_noodles` is not an item in the record. :param rec: A dictionary record to be decoded. :type rec: dict :param deref: Wether to decode a RefObject. If the encoder wrote files on a remote host, reading this file will be slow and result in an error if the file is not present. :type deref: bool""" if not isinstance(rec, dict): return rec if '_noodles' not in rec: return rec # if not deref: if rec.get('ref', False) and not deref: return RefObject(rec) typename = rec['type'] classname = rec['class'] try: cls = look_up(classname) if classname else None except (AttributeError, ImportError): cls = None if typename == '<object>': assert cls is not None, \ "could not lookup class '{}', decoding '{}'".format( classname, rec) return self[cls].decode(cls, rec['data']) else: return self._sers[typename].decode(cls, rec['data'])
python
def decode(self, rec, deref=False): """Decode a record to return an object that could be considered equivalent to the original. The record is not touched if `_noodles` is not an item in the record. :param rec: A dictionary record to be decoded. :type rec: dict :param deref: Wether to decode a RefObject. If the encoder wrote files on a remote host, reading this file will be slow and result in an error if the file is not present. :type deref: bool""" if not isinstance(rec, dict): return rec if '_noodles' not in rec: return rec # if not deref: if rec.get('ref', False) and not deref: return RefObject(rec) typename = rec['type'] classname = rec['class'] try: cls = look_up(classname) if classname else None except (AttributeError, ImportError): cls = None if typename == '<object>': assert cls is not None, \ "could not lookup class '{}', decoding '{}'".format( classname, rec) return self[cls].decode(cls, rec['data']) else: return self._sers[typename].decode(cls, rec['data'])
[ "def", "decode", "(", "self", ",", "rec", ",", "deref", "=", "False", ")", ":", "if", "not", "isinstance", "(", "rec", ",", "dict", ")", ":", "return", "rec", "if", "'_noodles'", "not", "in", "rec", ":", "return", "rec", "# if not deref:", "if", "rec...
Decode a record to return an object that could be considered equivalent to the original. The record is not touched if `_noodles` is not an item in the record. :param rec: A dictionary record to be decoded. :type rec: dict :param deref: Wether to decode a RefObject. If the encoder wrote files on a remote host, reading this file will be slow and result in an error if the file is not present. :type deref: bool
[ "Decode", "a", "record", "to", "return", "an", "object", "that", "could", "be", "considered", "equivalent", "to", "the", "original", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/registry.py#L190-L228
train
30,943
NLeSC/noodles
noodles/serial/registry.py
Registry.to_json
def to_json(self, obj, host=None, indent=None): """Recursively encode `obj` and convert it to a JSON string. :param obj: Object to encode. :param host: hostname where this object is being encoded. :type host: str""" if indent: return json.dumps(deep_map(lambda o: self.encode(o, host), obj), indent=indent) else: return json.dumps(deep_map(lambda o: self.encode(o, host), obj))
python
def to_json(self, obj, host=None, indent=None): """Recursively encode `obj` and convert it to a JSON string. :param obj: Object to encode. :param host: hostname where this object is being encoded. :type host: str""" if indent: return json.dumps(deep_map(lambda o: self.encode(o, host), obj), indent=indent) else: return json.dumps(deep_map(lambda o: self.encode(o, host), obj))
[ "def", "to_json", "(", "self", ",", "obj", ",", "host", "=", "None", ",", "indent", "=", "None", ")", ":", "if", "indent", ":", "return", "json", ".", "dumps", "(", "deep_map", "(", "lambda", "o", ":", "self", ".", "encode", "(", "o", ",", "host"...
Recursively encode `obj` and convert it to a JSON string. :param obj: Object to encode. :param host: hostname where this object is being encoded. :type host: str
[ "Recursively", "encode", "obj", "and", "convert", "it", "to", "a", "JSON", "string", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/registry.py#L236-L249
train
30,944
NLeSC/noodles
noodles/serial/registry.py
Registry.from_json
def from_json(self, data, deref=False): """Decode the string from JSON to return the original object (if `deref` is true. Uses the `json.loads` function with `self.decode` as object_hook. :param data: JSON encoded string. :type data: str :param deref: Whether to decode records that gave `ref=True` at encoding. :type deref: bool""" return self.deep_decode(json.loads(data), deref)
python
def from_json(self, data, deref=False): """Decode the string from JSON to return the original object (if `deref` is true. Uses the `json.loads` function with `self.decode` as object_hook. :param data: JSON encoded string. :type data: str :param deref: Whether to decode records that gave `ref=True` at encoding. :type deref: bool""" return self.deep_decode(json.loads(data), deref)
[ "def", "from_json", "(", "self", ",", "data", ",", "deref", "=", "False", ")", ":", "return", "self", ".", "deep_decode", "(", "json", ".", "loads", "(", "data", ")", ",", "deref", ")" ]
Decode the string from JSON to return the original object (if `deref` is true. Uses the `json.loads` function with `self.decode` as object_hook. :param data: JSON encoded string. :type data: str :param deref: Whether to decode records that gave `ref=True` at encoding. :type deref: bool
[ "Decode", "the", "string", "from", "JSON", "to", "return", "the", "original", "object", "(", "if", "deref", "is", "true", ".", "Uses", "the", "json", ".", "loads", "function", "with", "self", ".", "decode", "as", "object_hook", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/registry.py#L251-L263
train
30,945
NLeSC/noodles
noodles/serial/registry.py
Registry.dereference
def dereference(self, data, host=None): """Dereferences RefObjects stuck in the hierarchy. This is a bit of an ugly hack.""" return self.deep_decode(self.deep_encode(data, host), deref=True)
python
def dereference(self, data, host=None): """Dereferences RefObjects stuck in the hierarchy. This is a bit of an ugly hack.""" return self.deep_decode(self.deep_encode(data, host), deref=True)
[ "def", "dereference", "(", "self", ",", "data", ",", "host", "=", "None", ")", ":", "return", "self", ".", "deep_decode", "(", "self", ".", "deep_encode", "(", "data", ",", "host", ")", ",", "deref", "=", "True", ")" ]
Dereferences RefObjects stuck in the hierarchy. This is a bit of an ugly hack.
[ "Dereferences", "RefObjects", "stuck", "in", "the", "hierarchy", ".", "This", "is", "a", "bit", "of", "an", "ugly", "hack", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/registry.py#L266-L269
train
30,946
NLeSC/noodles
noodles/run/single/sqlite3.py
run_single
def run_single(workflow, *, registry, db_file, always_cache=True): """"Run workflow in a single thread, storing results in a Sqlite3 database. :param workflow: Workflow or PromisedObject to be evaluated. :param registry: serialization Registry function. :param db_file: filename of Sqlite3 database, give `':memory:'` to keep the database in memory only. :param always_cache: Currently ignored. always_cache is true. :return: Evaluated result. """ with JobDB(db_file, registry) as db: job_logger = make_logger("worker", push_map, db) result_logger = make_logger("worker", pull_map, db) @pull def pass_job(source): """Receives jobs from source, passes back results.""" for msg in source(): key, job = msg status, retrieved_result = db.add_job_to_db(key, job) if status == 'retrieved': yield retrieved_result continue elif status == 'attached': continue result = run_job(key, job) attached = db.store_result_in_db(result, always_cache=True) yield result yield from (ResultMessage(key, 'attached', result.value, None) for key in attached) scheduler = Scheduler(job_keeper=db) queue = Queue() job_front_end = job_logger >> queue.sink result_front_end = queue.source >> pass_job >> result_logger single_worker = Connection(result_front_end, job_front_end) return scheduler.run(single_worker, get_workflow(workflow))
python
def run_single(workflow, *, registry, db_file, always_cache=True): """"Run workflow in a single thread, storing results in a Sqlite3 database. :param workflow: Workflow or PromisedObject to be evaluated. :param registry: serialization Registry function. :param db_file: filename of Sqlite3 database, give `':memory:'` to keep the database in memory only. :param always_cache: Currently ignored. always_cache is true. :return: Evaluated result. """ with JobDB(db_file, registry) as db: job_logger = make_logger("worker", push_map, db) result_logger = make_logger("worker", pull_map, db) @pull def pass_job(source): """Receives jobs from source, passes back results.""" for msg in source(): key, job = msg status, retrieved_result = db.add_job_to_db(key, job) if status == 'retrieved': yield retrieved_result continue elif status == 'attached': continue result = run_job(key, job) attached = db.store_result_in_db(result, always_cache=True) yield result yield from (ResultMessage(key, 'attached', result.value, None) for key in attached) scheduler = Scheduler(job_keeper=db) queue = Queue() job_front_end = job_logger >> queue.sink result_front_end = queue.source >> pass_job >> result_logger single_worker = Connection(result_front_end, job_front_end) return scheduler.run(single_worker, get_workflow(workflow))
[ "def", "run_single", "(", "workflow", ",", "*", ",", "registry", ",", "db_file", ",", "always_cache", "=", "True", ")", ":", "with", "JobDB", "(", "db_file", ",", "registry", ")", "as", "db", ":", "job_logger", "=", "make_logger", "(", "\"worker\"", ",",...
Run workflow in a single thread, storing results in a Sqlite3 database. :param workflow: Workflow or PromisedObject to be evaluated. :param registry: serialization Registry function. :param db_file: filename of Sqlite3 database, give `':memory:'` to keep the database in memory only. :param always_cache: Currently ignored. always_cache is true. :return: Evaluated result.
[ "Run", "workflow", "in", "a", "single", "thread", "storing", "results", "in", "a", "Sqlite3", "database", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/single/sqlite3.py#L15-L57
train
30,947
NLeSC/noodles
noodles/run/xenon/xenon.py
Machine.scheduler
def scheduler(self): """Returns the scheduler object.""" if self._scheduler is None: self._scheduler = xenon.Scheduler.create(**self.scheduler_args) return self._scheduler
python
def scheduler(self): """Returns the scheduler object.""" if self._scheduler is None: self._scheduler = xenon.Scheduler.create(**self.scheduler_args) return self._scheduler
[ "def", "scheduler", "(", "self", ")", ":", "if", "self", ".", "_scheduler", "is", "None", ":", "self", ".", "_scheduler", "=", "xenon", ".", "Scheduler", ".", "create", "(", "*", "*", "self", ".", "scheduler_args", ")", "return", "self", ".", "_schedul...
Returns the scheduler object.
[ "Returns", "the", "scheduler", "object", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/xenon/xenon.py#L88-L93
train
30,948
NLeSC/noodles
noodles/run/xenon/xenon.py
Machine.file_system
def file_system(self): """Gets the filesystem corresponding to the open scheduler.""" if self._file_system is None: self._file_system = self.scheduler.get_file_system() return self._file_system
python
def file_system(self): """Gets the filesystem corresponding to the open scheduler.""" if self._file_system is None: self._file_system = self.scheduler.get_file_system() return self._file_system
[ "def", "file_system", "(", "self", ")", ":", "if", "self", ".", "_file_system", "is", "None", ":", "self", ".", "_file_system", "=", "self", ".", "scheduler", ".", "get_file_system", "(", ")", "return", "self", ".", "_file_system" ]
Gets the filesystem corresponding to the open scheduler.
[ "Gets", "the", "filesystem", "corresponding", "to", "the", "open", "scheduler", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/xenon/xenon.py#L96-L101
train
30,949
NLeSC/noodles
noodles/serial/base.py
registry
def registry(): """Returns the Noodles base serialisation registry.""" return Registry( types={ dict: SerDict(), tuple: SerSequence(tuple), set: SerSequence(set), bytes: SerBytes(), slice: SerSlice(), complex: SerByMembers(complex, ['real', 'imag']), Reasonable: SerReasonableObject(Reasonable), ArgumentKind: SerEnum(ArgumentKind), FunctionNode: SerNode(), ArgumentAddress: SerNamedTuple(ArgumentAddress), Workflow: SerWorkflow(), PromisedObject: SerPromisedObject(), Quote: SerReasonableObject(Quote), Path: SerPath(), Fail: SerReasonableObject(Fail) }, hooks={ '<method>': SerMethod(), '<boundmethod>': SerBoundMethod(), '<importable>': SerImportable(), '<automagic>': SerAuto(), '<unwrapped>': SerUnwrapped() }, hook_fn=_noodles_hook, default=SerUnknown(), )
python
def registry(): """Returns the Noodles base serialisation registry.""" return Registry( types={ dict: SerDict(), tuple: SerSequence(tuple), set: SerSequence(set), bytes: SerBytes(), slice: SerSlice(), complex: SerByMembers(complex, ['real', 'imag']), Reasonable: SerReasonableObject(Reasonable), ArgumentKind: SerEnum(ArgumentKind), FunctionNode: SerNode(), ArgumentAddress: SerNamedTuple(ArgumentAddress), Workflow: SerWorkflow(), PromisedObject: SerPromisedObject(), Quote: SerReasonableObject(Quote), Path: SerPath(), Fail: SerReasonableObject(Fail) }, hooks={ '<method>': SerMethod(), '<boundmethod>': SerBoundMethod(), '<importable>': SerImportable(), '<automagic>': SerAuto(), '<unwrapped>': SerUnwrapped() }, hook_fn=_noodles_hook, default=SerUnknown(), )
[ "def", "registry", "(", ")", ":", "return", "Registry", "(", "types", "=", "{", "dict", ":", "SerDict", "(", ")", ",", "tuple", ":", "SerSequence", "(", "tuple", ")", ",", "set", ":", "SerSequence", "(", "set", ")", ",", "bytes", ":", "SerBytes", "...
Returns the Noodles base serialisation registry.
[ "Returns", "the", "Noodles", "base", "serialisation", "registry", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/base.py#L228-L257
train
30,950
NLeSC/noodles
noodles/interface/decorator.py
scheduled_function
def scheduled_function(f, hints=None): """The Noodles schedule function decorator. The decorated function will return a workflow in stead of being applied immediately. This workflow can then be passed to a job scheduler in order to be run on any architecture supporting the current python environment.""" if hints is None: hints = {} if 'version' not in hints: try: source_bytes = inspect.getsource(f).encode() except Exception: pass else: m = hashlib.md5() m.update(source_bytes) hints['version'] = m.hexdigest() @wraps(f) def wrapped(*args, **kwargs): return PromisedObject(from_call( f, args, kwargs, deepcopy(hints), call_by_value=config['call_by_value'])) # add *(scheduled)* to the beginning of the docstring. if hasattr(wrapped, '__doc__') and wrapped.__doc__ is not None: wrapped.__doc__ = "*(scheduled)* " + wrapped.__doc__ return wrapped
python
def scheduled_function(f, hints=None): """The Noodles schedule function decorator. The decorated function will return a workflow in stead of being applied immediately. This workflow can then be passed to a job scheduler in order to be run on any architecture supporting the current python environment.""" if hints is None: hints = {} if 'version' not in hints: try: source_bytes = inspect.getsource(f).encode() except Exception: pass else: m = hashlib.md5() m.update(source_bytes) hints['version'] = m.hexdigest() @wraps(f) def wrapped(*args, **kwargs): return PromisedObject(from_call( f, args, kwargs, deepcopy(hints), call_by_value=config['call_by_value'])) # add *(scheduled)* to the beginning of the docstring. if hasattr(wrapped, '__doc__') and wrapped.__doc__ is not None: wrapped.__doc__ = "*(scheduled)* " + wrapped.__doc__ return wrapped
[ "def", "scheduled_function", "(", "f", ",", "hints", "=", "None", ")", ":", "if", "hints", "is", "None", ":", "hints", "=", "{", "}", "if", "'version'", "not", "in", "hints", ":", "try", ":", "source_bytes", "=", "inspect", ".", "getsource", "(", "f"...
The Noodles schedule function decorator. The decorated function will return a workflow in stead of being applied immediately. This workflow can then be passed to a job scheduler in order to be run on any architecture supporting the current python environment.
[ "The", "Noodles", "schedule", "function", "decorator", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/interface/decorator.py#L13-L43
train
30,951
NLeSC/noodles
noodles/run/worker.py
worker
def worker(job): """Primary |worker| coroutine. This is a |pull| object that pulls jobs from a source and yield evaluated results. Input should be of type |JobMessage|, output of type |ResultMessage|. .. |worker| replace:: :py:func::`worker`""" if job is EndOfQueue: return if not isinstance(job, JobMessage): print("Warning: Job should be communicated using `JobMessage`.", file=sys.stderr) key, node = job return run_job(key, node)
python
def worker(job): """Primary |worker| coroutine. This is a |pull| object that pulls jobs from a source and yield evaluated results. Input should be of type |JobMessage|, output of type |ResultMessage|. .. |worker| replace:: :py:func::`worker`""" if job is EndOfQueue: return if not isinstance(job, JobMessage): print("Warning: Job should be communicated using `JobMessage`.", file=sys.stderr) key, node = job return run_job(key, node)
[ "def", "worker", "(", "job", ")", ":", "if", "job", "is", "EndOfQueue", ":", "return", "if", "not", "isinstance", "(", "job", ",", "JobMessage", ")", ":", "print", "(", "\"Warning: Job should be communicated using `JobMessage`.\"", ",", "file", "=", "sys", "."...
Primary |worker| coroutine. This is a |pull| object that pulls jobs from a source and yield evaluated results. Input should be of type |JobMessage|, output of type |ResultMessage|. .. |worker| replace:: :py:func::`worker`
[ "Primary", "|worker|", "coroutine", ".", "This", "is", "a", "|pull|", "object", "that", "pulls", "jobs", "from", "a", "source", "and", "yield", "evaluated", "results", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/worker.py#L7-L22
train
30,952
NLeSC/noodles
noodles/run/worker.py
run_job
def run_job(key, node): """Run a job. This applies the function node, and returns a |ResultMessage| when complete. If an exception is raised in the job, the |ResultMessage| will have ``'error'`` status. .. |run_job| replace:: :py:func:`run_job`""" try: result = node.apply() return ResultMessage(key, 'done', result, None) except Exception as exc: return ResultMessage(key, 'error', None, exc)
python
def run_job(key, node): """Run a job. This applies the function node, and returns a |ResultMessage| when complete. If an exception is raised in the job, the |ResultMessage| will have ``'error'`` status. .. |run_job| replace:: :py:func:`run_job`""" try: result = node.apply() return ResultMessage(key, 'done', result, None) except Exception as exc: return ResultMessage(key, 'error', None, exc)
[ "def", "run_job", "(", "key", ",", "node", ")", ":", "try", ":", "result", "=", "node", ".", "apply", "(", ")", "return", "ResultMessage", "(", "key", ",", "'done'", ",", "result", ",", "None", ")", "except", "Exception", "as", "exc", ":", "return", ...
Run a job. This applies the function node, and returns a |ResultMessage| when complete. If an exception is raised in the job, the |ResultMessage| will have ``'error'`` status. .. |run_job| replace:: :py:func:`run_job`
[ "Run", "a", "job", ".", "This", "applies", "the", "function", "node", "and", "returns", "a", "|ResultMessage|", "when", "complete", ".", "If", "an", "exception", "is", "raised", "in", "the", "job", "the", "|ResultMessage|", "will", "have", "error", "status",...
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/worker.py#L25-L36
train
30,953
NLeSC/noodles
noodles/run/hybrid.py
hybrid_coroutine_worker
def hybrid_coroutine_worker(selector, workers): """Runs a set of workers, all of them in the main thread. This runner is here for testing purposes. :param selector: A function returning a worker key, given a job. :type selector: function :param workers: A dict of workers. :type workers: dict """ jobs = Queue() worker_source = {} worker_sink = {} for k, w in workers.items(): worker_source[k], worker_sink[k] = w.setup() def get_result(): source = jobs.source() for msg in source: key, job = msg worker = selector(job) if worker is None: yield run_job(key, job) else: # send the worker a job and wait for it to return worker_sink[worker].send(msg) result = next(worker_source[worker]) yield result return Connection(get_result, jobs.sink)
python
def hybrid_coroutine_worker(selector, workers): """Runs a set of workers, all of them in the main thread. This runner is here for testing purposes. :param selector: A function returning a worker key, given a job. :type selector: function :param workers: A dict of workers. :type workers: dict """ jobs = Queue() worker_source = {} worker_sink = {} for k, w in workers.items(): worker_source[k], worker_sink[k] = w.setup() def get_result(): source = jobs.source() for msg in source: key, job = msg worker = selector(job) if worker is None: yield run_job(key, job) else: # send the worker a job and wait for it to return worker_sink[worker].send(msg) result = next(worker_source[worker]) yield result return Connection(get_result, jobs.sink)
[ "def", "hybrid_coroutine_worker", "(", "selector", ",", "workers", ")", ":", "jobs", "=", "Queue", "(", ")", "worker_source", "=", "{", "}", "worker_sink", "=", "{", "}", "for", "k", ",", "w", "in", "workers", ".", "items", "(", ")", ":", "worker_sourc...
Runs a set of workers, all of them in the main thread. This runner is here for testing purposes. :param selector: A function returning a worker key, given a job. :type selector: function :param workers: A dict of workers. :type workers: dict
[ "Runs", "a", "set", "of", "workers", "all", "of", "them", "in", "the", "main", "thread", ".", "This", "runner", "is", "here", "for", "testing", "purposes", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/hybrid.py#L9-L43
train
30,954
NLeSC/noodles
noodles/run/hybrid.py
hybrid_threaded_worker
def hybrid_threaded_worker(selector, workers): """Runs a set of workers, each in a separate thread. :param selector: A function that takes a hints-tuple and returns a key indexing a worker in the `workers` dictionary. :param workers: A dictionary of workers. :returns: A connection for the scheduler. :rtype: Connection The hybrid worker dispatches jobs to the different workers based on the information contained in the hints. If no hints were given, the job is run in the main thread. Dispatching is done in the main thread. Retrieving results is done in a separate thread for each worker. In this design it is assumed that dispatching a job takes little time, while waiting for one to return a result may take a long time. """ result_queue = Queue() job_sink = {k: w.sink() for k, w in workers.items()} @push def dispatch_job(): default_sink = result_queue.sink() while True: msg = yield if msg is EndOfQueue: for k in workers.keys(): try: job_sink[k].send(EndOfQueue) except StopIteration: pass return if msg is FlushQueue: for k in workers.keys(): try: job_sink[k].send(FlushQueue) except StopIteration: pass return worker = selector(msg.node) if worker: job_sink[worker].send(msg) else: default_sink.send(run_job(*msg)) for key, worker in workers.items(): t = threading.Thread( target=patch, args=(worker.source, result_queue.sink)) t.daemon = True t.start() return Connection(result_queue.source, dispatch_job)
python
def hybrid_threaded_worker(selector, workers): """Runs a set of workers, each in a separate thread. :param selector: A function that takes a hints-tuple and returns a key indexing a worker in the `workers` dictionary. :param workers: A dictionary of workers. :returns: A connection for the scheduler. :rtype: Connection The hybrid worker dispatches jobs to the different workers based on the information contained in the hints. If no hints were given, the job is run in the main thread. Dispatching is done in the main thread. Retrieving results is done in a separate thread for each worker. In this design it is assumed that dispatching a job takes little time, while waiting for one to return a result may take a long time. """ result_queue = Queue() job_sink = {k: w.sink() for k, w in workers.items()} @push def dispatch_job(): default_sink = result_queue.sink() while True: msg = yield if msg is EndOfQueue: for k in workers.keys(): try: job_sink[k].send(EndOfQueue) except StopIteration: pass return if msg is FlushQueue: for k in workers.keys(): try: job_sink[k].send(FlushQueue) except StopIteration: pass return worker = selector(msg.node) if worker: job_sink[worker].send(msg) else: default_sink.send(run_job(*msg)) for key, worker in workers.items(): t = threading.Thread( target=patch, args=(worker.source, result_queue.sink)) t.daemon = True t.start() return Connection(result_queue.source, dispatch_job)
[ "def", "hybrid_threaded_worker", "(", "selector", ",", "workers", ")", ":", "result_queue", "=", "Queue", "(", ")", "job_sink", "=", "{", "k", ":", "w", ".", "sink", "(", ")", "for", "k", ",", "w", "in", "workers", ".", "items", "(", ")", "}", "@",...
Runs a set of workers, each in a separate thread. :param selector: A function that takes a hints-tuple and returns a key indexing a worker in the `workers` dictionary. :param workers: A dictionary of workers. :returns: A connection for the scheduler. :rtype: Connection The hybrid worker dispatches jobs to the different workers based on the information contained in the hints. If no hints were given, the job is run in the main thread. Dispatching is done in the main thread. Retrieving results is done in a separate thread for each worker. In this design it is assumed that dispatching a job takes little time, while waiting for one to return a result may take a long time.
[ "Runs", "a", "set", "of", "workers", "each", "in", "a", "separate", "thread", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/hybrid.py#L46-L108
train
30,955
NLeSC/noodles
noodles/run/hybrid.py
run_hybrid
def run_hybrid(wf, selector, workers): """ Returns the result of evaluating the workflow; runs through several supplied workers in as many threads. :param wf: Workflow to compute :type wf: :py:class:`Workflow` or :py:class:`PromisedObject` :param selector: A function selecting the worker that should be run, given a hint. :param workers: A dictionary of workers :returns: result of running the workflow """ worker = hybrid_threaded_worker(selector, workers) return Scheduler().run(worker, get_workflow(wf))
python
def run_hybrid(wf, selector, workers): """ Returns the result of evaluating the workflow; runs through several supplied workers in as many threads. :param wf: Workflow to compute :type wf: :py:class:`Workflow` or :py:class:`PromisedObject` :param selector: A function selecting the worker that should be run, given a hint. :param workers: A dictionary of workers :returns: result of running the workflow """ worker = hybrid_threaded_worker(selector, workers) return Scheduler().run(worker, get_workflow(wf))
[ "def", "run_hybrid", "(", "wf", ",", "selector", ",", "workers", ")", ":", "worker", "=", "hybrid_threaded_worker", "(", "selector", ",", "workers", ")", "return", "Scheduler", "(", ")", ".", "run", "(", "worker", ",", "get_workflow", "(", "wf", ")", ")"...
Returns the result of evaluating the workflow; runs through several supplied workers in as many threads. :param wf: Workflow to compute :type wf: :py:class:`Workflow` or :py:class:`PromisedObject` :param selector: A function selecting the worker that should be run, given a hint. :param workers: A dictionary of workers :returns: result of running the workflow
[ "Returns", "the", "result", "of", "evaluating", "the", "workflow", ";", "runs", "through", "several", "supplied", "workers", "in", "as", "many", "threads", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/hybrid.py#L111-L129
train
30,956
NLeSC/noodles
noodles/prov/key.py
prov_key
def prov_key(job_msg, extra=None): """Retrieves a MD5 sum from a function call. This takes into account the name of the function, the arguments and possibly a version number of the function, if that is given in the hints. This version can also be auto-generated by generating an MD5 hash from the function source. However, the source-code may not always be reachable, or the result may depend on an external process which has its own versioning.""" m = hashlib.md5() update_object_hash(m, job_msg['data']['function']) update_object_hash(m, job_msg['data']['arguments']) if 'version' in job_msg['data']['hints']: update_object_hash(m, job_msg['data']['hints']['version']) if extra is not None: update_object_hash(m, extra) return m.hexdigest()
python
def prov_key(job_msg, extra=None): """Retrieves a MD5 sum from a function call. This takes into account the name of the function, the arguments and possibly a version number of the function, if that is given in the hints. This version can also be auto-generated by generating an MD5 hash from the function source. However, the source-code may not always be reachable, or the result may depend on an external process which has its own versioning.""" m = hashlib.md5() update_object_hash(m, job_msg['data']['function']) update_object_hash(m, job_msg['data']['arguments']) if 'version' in job_msg['data']['hints']: update_object_hash(m, job_msg['data']['hints']['version']) if extra is not None: update_object_hash(m, extra) return m.hexdigest()
[ "def", "prov_key", "(", "job_msg", ",", "extra", "=", "None", ")", ":", "m", "=", "hashlib", ".", "md5", "(", ")", "update_object_hash", "(", "m", ",", "job_msg", "[", "'data'", "]", "[", "'function'", "]", ")", "update_object_hash", "(", "m", ",", "...
Retrieves a MD5 sum from a function call. This takes into account the name of the function, the arguments and possibly a version number of the function, if that is given in the hints. This version can also be auto-generated by generating an MD5 hash from the function source. However, the source-code may not always be reachable, or the result may depend on an external process which has its own versioning.
[ "Retrieves", "a", "MD5", "sum", "from", "a", "function", "call", ".", "This", "takes", "into", "account", "the", "name", "of", "the", "function", "the", "arguments", "and", "possibly", "a", "version", "number", "of", "the", "function", "if", "that", "is", ...
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/prov/key.py#L15-L33
train
30,957
NLeSC/noodles
noodles/run/remote/io.py
JSONObjectReader
def JSONObjectReader(registry, fi, deref=False): """Stream objects from a JSON file. :param registry: serialisation registry. :param fi: input file :param deref: flag, if True, objects will be dereferenced on decoding, otherwise we are lazy about decoding a JSON string. """ for line in fi: yield registry.from_json(line, deref=deref)
python
def JSONObjectReader(registry, fi, deref=False): """Stream objects from a JSON file. :param registry: serialisation registry. :param fi: input file :param deref: flag, if True, objects will be dereferenced on decoding, otherwise we are lazy about decoding a JSON string. """ for line in fi: yield registry.from_json(line, deref=deref)
[ "def", "JSONObjectReader", "(", "registry", ",", "fi", ",", "deref", "=", "False", ")", ":", "for", "line", "in", "fi", ":", "yield", "registry", ".", "from_json", "(", "line", ",", "deref", "=", "deref", ")" ]
Stream objects from a JSON file. :param registry: serialisation registry. :param fi: input file :param deref: flag, if True, objects will be dereferenced on decoding, otherwise we are lazy about decoding a JSON string.
[ "Stream", "objects", "from", "a", "JSON", "file", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/remote/io.py#L9-L18
train
30,958
NLeSC/noodles
noodles/run/remote/io.py
JSONObjectWriter
def JSONObjectWriter(registry, fo, host=None): """Sink; writes object as JSON to a file. :param registry: serialisation registry. :param fo: output file. :param host: name of the host that encodes the JSON. This is relevant if the encoded data refers to external files for mass storage. In normal use, it may occur that the pipe to which we write is broken, for instance when the remote process shuts down. In that case, this coroutine exits. """ while True: obj = yield try: print(registry.to_json(obj, host=host), file=fo, flush=True) except BrokenPipeError: return
python
def JSONObjectWriter(registry, fo, host=None): """Sink; writes object as JSON to a file. :param registry: serialisation registry. :param fo: output file. :param host: name of the host that encodes the JSON. This is relevant if the encoded data refers to external files for mass storage. In normal use, it may occur that the pipe to which we write is broken, for instance when the remote process shuts down. In that case, this coroutine exits. """ while True: obj = yield try: print(registry.to_json(obj, host=host), file=fo, flush=True) except BrokenPipeError: return
[ "def", "JSONObjectWriter", "(", "registry", ",", "fo", ",", "host", "=", "None", ")", ":", "while", "True", ":", "obj", "=", "yield", "try", ":", "print", "(", "registry", ".", "to_json", "(", "obj", ",", "host", "=", "host", ")", ",", "file", "=",...
Sink; writes object as JSON to a file. :param registry: serialisation registry. :param fo: output file. :param host: name of the host that encodes the JSON. This is relevant if the encoded data refers to external files for mass storage. In normal use, it may occur that the pipe to which we write is broken, for instance when the remote process shuts down. In that case, this coroutine exits.
[ "Sink", ";", "writes", "object", "as", "JSON", "to", "a", "file", "." ]
3759e24e6e54a3a1a364431309dbb1061f617c04
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/remote/io.py#L22-L39
train
30,959
scikit-hep/root_numpy
root_numpy/_matrix.py
matrix
def matrix(mat): """Convert a ROOT TMatrix into a NumPy matrix. Parameters ---------- mat : ROOT TMatrixT A ROOT TMatrixD or TMatrixF Returns ------- mat : numpy.matrix A NumPy matrix Examples -------- >>> from root_numpy import matrix >>> from ROOT import TMatrixD >>> a = TMatrixD(4, 4) >>> a[1][2] = 2 >>> matrix(a) matrix([[ 0., 0., 0., 0.], [ 0., 0., 2., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) """ import ROOT if isinstance(mat, (ROOT.TMatrixD, ROOT.TMatrixDSym)): return _librootnumpy.matrix_d(ROOT.AsCObject(mat)) elif isinstance(mat, (ROOT.TMatrixF, ROOT.TMatrixFSym)): return _librootnumpy.matrix_f(ROOT.AsCObject(mat)) raise TypeError( "unable to convert object of type {0} " "into a numpy matrix".format(type(mat)))
python
def matrix(mat): """Convert a ROOT TMatrix into a NumPy matrix. Parameters ---------- mat : ROOT TMatrixT A ROOT TMatrixD or TMatrixF Returns ------- mat : numpy.matrix A NumPy matrix Examples -------- >>> from root_numpy import matrix >>> from ROOT import TMatrixD >>> a = TMatrixD(4, 4) >>> a[1][2] = 2 >>> matrix(a) matrix([[ 0., 0., 0., 0.], [ 0., 0., 2., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) """ import ROOT if isinstance(mat, (ROOT.TMatrixD, ROOT.TMatrixDSym)): return _librootnumpy.matrix_d(ROOT.AsCObject(mat)) elif isinstance(mat, (ROOT.TMatrixF, ROOT.TMatrixFSym)): return _librootnumpy.matrix_f(ROOT.AsCObject(mat)) raise TypeError( "unable to convert object of type {0} " "into a numpy matrix".format(type(mat)))
[ "def", "matrix", "(", "mat", ")", ":", "import", "ROOT", "if", "isinstance", "(", "mat", ",", "(", "ROOT", ".", "TMatrixD", ",", "ROOT", ".", "TMatrixDSym", ")", ")", ":", "return", "_librootnumpy", ".", "matrix_d", "(", "ROOT", ".", "AsCObject", "(", ...
Convert a ROOT TMatrix into a NumPy matrix. Parameters ---------- mat : ROOT TMatrixT A ROOT TMatrixD or TMatrixF Returns ------- mat : numpy.matrix A NumPy matrix Examples -------- >>> from root_numpy import matrix >>> from ROOT import TMatrixD >>> a = TMatrixD(4, 4) >>> a[1][2] = 2 >>> matrix(a) matrix([[ 0., 0., 0., 0.], [ 0., 0., 2., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])
[ "Convert", "a", "ROOT", "TMatrix", "into", "a", "NumPy", "matrix", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_matrix.py#L9-L42
train
30,960
scikit-hep/root_numpy
root_numpy/_graph.py
fill_graph
def fill_graph(graph, array): """Fill a ROOT graph with a NumPy array. Parameters ---------- graph : a ROOT TGraph or TGraph2D The ROOT graph to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the graph with. The number of columns must match the dimensionality of the graph. """ import ROOT array = np.asarray(array, dtype=np.double) if isinstance(graph, ROOT.TGraph): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 2: raise ValueError( "length of the second dimension must equal " "the dimension of the graph") return _librootnumpy.fill_g1( ROOT.AsCObject(graph), array) elif isinstance(graph, ROOT.TGraph2D): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 3: raise ValueError( "length of the second dimension must equal " "the dimension of the graph") return _librootnumpy.fill_g2( ROOT.AsCObject(graph), array) else: raise TypeError( "hist must be an instance of ROOT.TGraph or ROOT.TGraph2D")
python
def fill_graph(graph, array): """Fill a ROOT graph with a NumPy array. Parameters ---------- graph : a ROOT TGraph or TGraph2D The ROOT graph to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the graph with. The number of columns must match the dimensionality of the graph. """ import ROOT array = np.asarray(array, dtype=np.double) if isinstance(graph, ROOT.TGraph): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 2: raise ValueError( "length of the second dimension must equal " "the dimension of the graph") return _librootnumpy.fill_g1( ROOT.AsCObject(graph), array) elif isinstance(graph, ROOT.TGraph2D): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 3: raise ValueError( "length of the second dimension must equal " "the dimension of the graph") return _librootnumpy.fill_g2( ROOT.AsCObject(graph), array) else: raise TypeError( "hist must be an instance of ROOT.TGraph or ROOT.TGraph2D")
[ "def", "fill_graph", "(", "graph", ",", "array", ")", ":", "import", "ROOT", "array", "=", "np", ".", "asarray", "(", "array", ",", "dtype", "=", "np", ".", "double", ")", "if", "isinstance", "(", "graph", ",", "ROOT", ".", "TGraph", ")", ":", "if"...
Fill a ROOT graph with a NumPy array. Parameters ---------- graph : a ROOT TGraph or TGraph2D The ROOT graph to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the graph with. The number of columns must match the dimensionality of the graph.
[ "Fill", "a", "ROOT", "graph", "with", "a", "NumPy", "array", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_graph.py#L10-L44
train
30,961
scikit-hep/root_numpy
root_numpy/_sample.py
random_sample
def random_sample(obj, n_samples, seed=None): """Create a random array by sampling a ROOT function or histogram. Parameters ---------- obj : TH[1|2|3] or TF[1|2|3] The ROOT function or histogram to sample. n_samples : positive int The number of random samples to generate. seed : None, positive int or 0, optional (default=None) The random seed, set via ROOT.gRandom.SetSeed(seed): http://root.cern.ch/root/html/TRandom3.html#TRandom3:SetSeed If 0, the seed will be random. If None (the default), ROOT.gRandom will not be touched and the current seed will be used. Returns ------- array : a numpy array A numpy array with a shape corresponding to the dimensionality of the function or histogram. A flat array is returned when sampling TF1 or TH1. An array with shape [n_samples, n_dimensions] is returned when sampling TF2, TF3, TH2, or TH3. Examples -------- >>> from root_numpy import random_sample >>> from ROOT import TF1, TF2, TF3 >>> random_sample(TF1("f1", "TMath::DiLog(x)"), 10000, seed=1) array([ 0.68307934, 0.9988919 , 0.87198158, ..., 0.50331049, 0.53895257, 0.57576984]) >>> random_sample(TF2("f2", "sin(x)*sin(y)/(x*y)"), 10000, seed=1) array([[ 0.93425084, 0.39990616], [ 0.00819315, 0.73108525], [ 0.00307176, 0.00427081], ..., [ 0.66931215, 0.0421913 ], [ 0.06469985, 0.10253632], [ 0.31059832, 0.75892702]]) >>> random_sample(TF3("f3", "sin(x)*sin(y)*sin(z)/(x*y*z)"), 10000, seed=1) array([[ 0.03323949, 0.95734415, 0.39775191], [ 0.07093748, 0.01007775, 0.03330135], [ 0.80786963, 0.13641129, 0.14655269], ..., [ 0.96223632, 0.43916482, 0.05542078], [ 0.06631163, 0.0015063 , 0.46550416], [ 0.88154752, 0.24332142, 0.66746564]]) """ import ROOT if n_samples <= 0: raise ValueError("n_samples must be greater than 0") if seed is not None: if seed < 0: raise ValueError("seed must be positive or 0") ROOT.gRandom.SetSeed(seed) # functions if isinstance(obj, ROOT.TF1): if isinstance(obj, ROOT.TF3): return _librootnumpy.sample_f3( ROOT.AsCObject(obj), n_samples) elif isinstance(obj, ROOT.TF2): return _librootnumpy.sample_f2( ROOT.AsCObject(obj), n_samples) return _librootnumpy.sample_f1(ROOT.AsCObject(obj), n_samples) # histograms elif isinstance(obj, ROOT.TH1): if isinstance(obj, ROOT.TH3): return _librootnumpy.sample_h3( ROOT.AsCObject(obj), n_samples) elif isinstance(obj, ROOT.TH2): return _librootnumpy.sample_h2( ROOT.AsCObject(obj), n_samples) return _librootnumpy.sample_h1(ROOT.AsCObject(obj), n_samples) raise TypeError( "obj must be a ROOT function or histogram")
python
def random_sample(obj, n_samples, seed=None): """Create a random array by sampling a ROOT function or histogram. Parameters ---------- obj : TH[1|2|3] or TF[1|2|3] The ROOT function or histogram to sample. n_samples : positive int The number of random samples to generate. seed : None, positive int or 0, optional (default=None) The random seed, set via ROOT.gRandom.SetSeed(seed): http://root.cern.ch/root/html/TRandom3.html#TRandom3:SetSeed If 0, the seed will be random. If None (the default), ROOT.gRandom will not be touched and the current seed will be used. Returns ------- array : a numpy array A numpy array with a shape corresponding to the dimensionality of the function or histogram. A flat array is returned when sampling TF1 or TH1. An array with shape [n_samples, n_dimensions] is returned when sampling TF2, TF3, TH2, or TH3. Examples -------- >>> from root_numpy import random_sample >>> from ROOT import TF1, TF2, TF3 >>> random_sample(TF1("f1", "TMath::DiLog(x)"), 10000, seed=1) array([ 0.68307934, 0.9988919 , 0.87198158, ..., 0.50331049, 0.53895257, 0.57576984]) >>> random_sample(TF2("f2", "sin(x)*sin(y)/(x*y)"), 10000, seed=1) array([[ 0.93425084, 0.39990616], [ 0.00819315, 0.73108525], [ 0.00307176, 0.00427081], ..., [ 0.66931215, 0.0421913 ], [ 0.06469985, 0.10253632], [ 0.31059832, 0.75892702]]) >>> random_sample(TF3("f3", "sin(x)*sin(y)*sin(z)/(x*y*z)"), 10000, seed=1) array([[ 0.03323949, 0.95734415, 0.39775191], [ 0.07093748, 0.01007775, 0.03330135], [ 0.80786963, 0.13641129, 0.14655269], ..., [ 0.96223632, 0.43916482, 0.05542078], [ 0.06631163, 0.0015063 , 0.46550416], [ 0.88154752, 0.24332142, 0.66746564]]) """ import ROOT if n_samples <= 0: raise ValueError("n_samples must be greater than 0") if seed is not None: if seed < 0: raise ValueError("seed must be positive or 0") ROOT.gRandom.SetSeed(seed) # functions if isinstance(obj, ROOT.TF1): if isinstance(obj, ROOT.TF3): return _librootnumpy.sample_f3( ROOT.AsCObject(obj), n_samples) elif isinstance(obj, ROOT.TF2): return _librootnumpy.sample_f2( ROOT.AsCObject(obj), n_samples) return _librootnumpy.sample_f1(ROOT.AsCObject(obj), n_samples) # histograms elif isinstance(obj, ROOT.TH1): if isinstance(obj, ROOT.TH3): return _librootnumpy.sample_h3( ROOT.AsCObject(obj), n_samples) elif isinstance(obj, ROOT.TH2): return _librootnumpy.sample_h2( ROOT.AsCObject(obj), n_samples) return _librootnumpy.sample_h1(ROOT.AsCObject(obj), n_samples) raise TypeError( "obj must be a ROOT function or histogram")
[ "def", "random_sample", "(", "obj", ",", "n_samples", ",", "seed", "=", "None", ")", ":", "import", "ROOT", "if", "n_samples", "<=", "0", ":", "raise", "ValueError", "(", "\"n_samples must be greater than 0\"", ")", "if", "seed", "is", "not", "None", ":", ...
Create a random array by sampling a ROOT function or histogram. Parameters ---------- obj : TH[1|2|3] or TF[1|2|3] The ROOT function or histogram to sample. n_samples : positive int The number of random samples to generate. seed : None, positive int or 0, optional (default=None) The random seed, set via ROOT.gRandom.SetSeed(seed): http://root.cern.ch/root/html/TRandom3.html#TRandom3:SetSeed If 0, the seed will be random. If None (the default), ROOT.gRandom will not be touched and the current seed will be used. Returns ------- array : a numpy array A numpy array with a shape corresponding to the dimensionality of the function or histogram. A flat array is returned when sampling TF1 or TH1. An array with shape [n_samples, n_dimensions] is returned when sampling TF2, TF3, TH2, or TH3. Examples -------- >>> from root_numpy import random_sample >>> from ROOT import TF1, TF2, TF3 >>> random_sample(TF1("f1", "TMath::DiLog(x)"), 10000, seed=1) array([ 0.68307934, 0.9988919 , 0.87198158, ..., 0.50331049, 0.53895257, 0.57576984]) >>> random_sample(TF2("f2", "sin(x)*sin(y)/(x*y)"), 10000, seed=1) array([[ 0.93425084, 0.39990616], [ 0.00819315, 0.73108525], [ 0.00307176, 0.00427081], ..., [ 0.66931215, 0.0421913 ], [ 0.06469985, 0.10253632], [ 0.31059832, 0.75892702]]) >>> random_sample(TF3("f3", "sin(x)*sin(y)*sin(z)/(x*y*z)"), 10000, seed=1) array([[ 0.03323949, 0.95734415, 0.39775191], [ 0.07093748, 0.01007775, 0.03330135], [ 0.80786963, 0.13641129, 0.14655269], ..., [ 0.96223632, 0.43916482, 0.05542078], [ 0.06631163, 0.0015063 , 0.46550416], [ 0.88154752, 0.24332142, 0.66746564]])
[ "Create", "a", "random", "array", "by", "sampling", "a", "ROOT", "function", "or", "histogram", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_sample.py#L9-L83
train
30,962
scikit-hep/root_numpy
root_numpy/_tree.py
_glob
def _glob(filenames): """Glob a filename or list of filenames but always return the original string if the glob didn't match anything so URLs for remote file access are not clobbered. """ if isinstance(filenames, string_types): filenames = [filenames] matches = [] for name in filenames: matched_names = glob(name) if not matched_names: # use the original string matches.append(name) else: matches.extend(matched_names) return matches
python
def _glob(filenames): """Glob a filename or list of filenames but always return the original string if the glob didn't match anything so URLs for remote file access are not clobbered. """ if isinstance(filenames, string_types): filenames = [filenames] matches = [] for name in filenames: matched_names = glob(name) if not matched_names: # use the original string matches.append(name) else: matches.extend(matched_names) return matches
[ "def", "_glob", "(", "filenames", ")", ":", "if", "isinstance", "(", "filenames", ",", "string_types", ")", ":", "filenames", "=", "[", "filenames", "]", "matches", "=", "[", "]", "for", "name", "in", "filenames", ":", "matched_names", "=", "glob", "(", ...
Glob a filename or list of filenames but always return the original string if the glob didn't match anything so URLs for remote file access are not clobbered.
[ "Glob", "a", "filename", "or", "list", "of", "filenames", "but", "always", "return", "the", "original", "string", "if", "the", "glob", "didn", "t", "match", "anything", "so", "URLs", "for", "remote", "file", "access", "are", "not", "clobbered", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_tree.py#L23-L38
train
30,963
scikit-hep/root_numpy
root_numpy/_tree.py
list_structures
def list_structures(filename, treename=None): """Get a dictionary mapping branch names to leaf structures. .. warning:: ``list_structures`` is deprecated and will be removed in release 5.0.0. Parameters ---------- filename : str Path to ROOT file. treename : str, optional (default=None) Name of tree in the ROOT file (optional if the ROOT file has only one tree). Returns ------- structures : OrderedDict An ordered dictionary mapping branch names to leaf structures. """ warnings.warn("list_structures is deprecated and will be " "removed in 5.0.0.", DeprecationWarning) return _librootnumpy.list_structures(filename, treename)
python
def list_structures(filename, treename=None): """Get a dictionary mapping branch names to leaf structures. .. warning:: ``list_structures`` is deprecated and will be removed in release 5.0.0. Parameters ---------- filename : str Path to ROOT file. treename : str, optional (default=None) Name of tree in the ROOT file (optional if the ROOT file has only one tree). Returns ------- structures : OrderedDict An ordered dictionary mapping branch names to leaf structures. """ warnings.warn("list_structures is deprecated and will be " "removed in 5.0.0.", DeprecationWarning) return _librootnumpy.list_structures(filename, treename)
[ "def", "list_structures", "(", "filename", ",", "treename", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"list_structures is deprecated and will be \"", "\"removed in 5.0.0.\"", ",", "DeprecationWarning", ")", "return", "_librootnumpy", ".", "list_structures", ...
Get a dictionary mapping branch names to leaf structures. .. warning:: ``list_structures`` is deprecated and will be removed in release 5.0.0. Parameters ---------- filename : str Path to ROOT file. treename : str, optional (default=None) Name of tree in the ROOT file (optional if the ROOT file has only one tree). Returns ------- structures : OrderedDict An ordered dictionary mapping branch names to leaf structures.
[ "Get", "a", "dictionary", "mapping", "branch", "names", "to", "leaf", "structures", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_tree.py#L95-L117
train
30,964
scikit-hep/root_numpy
root_numpy/_tree.py
root2array
def root2array(filenames, treename=None, branches=None, selection=None, object_selection=None, start=None, stop=None, step=None, include_weight=False, weight_name='weight', cache_size=-1, warn_missing_tree=False): """Convert trees in ROOT files into a numpy structured array. Refer to the documentation of :func:`tree2array`. Parameters ---------- filenames : str or list ROOT file name pattern or list of patterns. Wildcarding is supported by Python globbing. treename : str, optional (default=None) Name of the tree to convert (optional if each file contains exactly one tree). branches : list of strings and tuples or a string or tuple, optional (default=None) List of branches and expressions to include as columns of the array or a single branch or expression in which case a nonstructured array is returned. If None then include all branches that can be converted. Branches or expressions that result in variable-length subarrays can be truncated at a fixed length by using the tuple ``(branch_or_expression, fill_value, length)`` or converted into a single value with ``(branch_or_expression, fill_value)`` where ``length==1`` is implied. ``fill_value`` is used when the original array is shorter than ``length``. This truncation is after any object selection performed with the ``object_selection`` argument. selection : str, optional (default=None) Only include entries fulfilling this condition. If the condition evaluates to multiple values per tree entry (e.g. conditions on array branches) then an entry will be included if the condition evaluates to true for at least one array element. object_selection : dict, optional (default=None) A dictionary mapping selection strings to branch names or lists of branch names. Only array elements passing the selection strings will be included in the output array per entry in the tree. The branches specified must be variable-length array-type branches and the length of the selection and branches it acts on must match for each tree entry. For example ``object_selection={'a > 0': ['a', 'b']}`` will include all elements of 'a' and corresponding elements of 'b' where 'a > 0' for each tree entry. 'a' and 'b' must have the same length in every tree entry. start, stop, step: int, optional (default=None) The meaning of the ``start``, ``stop`` and ``step`` parameters is the same as for Python slices. If a range is supplied (by setting some of the ``start``, ``stop`` or ``step`` parameters), only the entries in that range and fulfilling the ``selection`` condition (if defined) are used. include_weight : bool, optional (default=False) Include a column containing the tree weight ``TTree::GetWeight()``. Note that this will be the same value for all entries unless the tree is actually a TChain containing multiple trees with different weights. weight_name : str, optional (default='weight') The field name for the weight column if ``include_weight=True``. cache_size : int, optional (default=-1) Set the size (in bytes) of the TTreeCache used while reading a TTree. A value of -1 uses ROOT's default cache size. A value of 0 disables the cache. warn_missing_tree : bool, optional (default=False) If True, then warn when a tree is missing from an input file instead of raising an IOError. Notes ----- * Refer to the :ref:`type conversion table <conversion_table>`. See Also -------- tree2array array2tree array2root """ filenames = _glob(filenames) if not filenames: raise ValueError("specify at least one filename") if treename is None: trees = list_trees(filenames[0]) if len(trees) > 1: raise ValueError( "treename must be specified if the file " "contains more than one tree") elif not trees: raise IOError( "no trees present in {0}".format(filenames[0])) treename = trees[0] if isinstance(branches, string_types): # single branch selected flatten = branches branches = [branches] elif isinstance(branches, tuple): if len(branches) not in (2, 3): raise ValueError( "invalid branch tuple: {0}. " "A branch tuple must contain two elements " "(branch_name, fill_value) or three elements " "(branch_name, fill_value, length) " "to yield a single value or truncate, respectively".format(branches)) flatten = branches[0] branches = [branches] else: flatten = False arr = _librootnumpy.root2array_fromfile( filenames, treename, branches, selection, object_selection, start, stop, step, include_weight, weight_name, cache_size, warn_missing_tree) if flatten: # select single column return arr[flatten] return arr
python
def root2array(filenames, treename=None, branches=None, selection=None, object_selection=None, start=None, stop=None, step=None, include_weight=False, weight_name='weight', cache_size=-1, warn_missing_tree=False): """Convert trees in ROOT files into a numpy structured array. Refer to the documentation of :func:`tree2array`. Parameters ---------- filenames : str or list ROOT file name pattern or list of patterns. Wildcarding is supported by Python globbing. treename : str, optional (default=None) Name of the tree to convert (optional if each file contains exactly one tree). branches : list of strings and tuples or a string or tuple, optional (default=None) List of branches and expressions to include as columns of the array or a single branch or expression in which case a nonstructured array is returned. If None then include all branches that can be converted. Branches or expressions that result in variable-length subarrays can be truncated at a fixed length by using the tuple ``(branch_or_expression, fill_value, length)`` or converted into a single value with ``(branch_or_expression, fill_value)`` where ``length==1`` is implied. ``fill_value`` is used when the original array is shorter than ``length``. This truncation is after any object selection performed with the ``object_selection`` argument. selection : str, optional (default=None) Only include entries fulfilling this condition. If the condition evaluates to multiple values per tree entry (e.g. conditions on array branches) then an entry will be included if the condition evaluates to true for at least one array element. object_selection : dict, optional (default=None) A dictionary mapping selection strings to branch names or lists of branch names. Only array elements passing the selection strings will be included in the output array per entry in the tree. The branches specified must be variable-length array-type branches and the length of the selection and branches it acts on must match for each tree entry. For example ``object_selection={'a > 0': ['a', 'b']}`` will include all elements of 'a' and corresponding elements of 'b' where 'a > 0' for each tree entry. 'a' and 'b' must have the same length in every tree entry. start, stop, step: int, optional (default=None) The meaning of the ``start``, ``stop`` and ``step`` parameters is the same as for Python slices. If a range is supplied (by setting some of the ``start``, ``stop`` or ``step`` parameters), only the entries in that range and fulfilling the ``selection`` condition (if defined) are used. include_weight : bool, optional (default=False) Include a column containing the tree weight ``TTree::GetWeight()``. Note that this will be the same value for all entries unless the tree is actually a TChain containing multiple trees with different weights. weight_name : str, optional (default='weight') The field name for the weight column if ``include_weight=True``. cache_size : int, optional (default=-1) Set the size (in bytes) of the TTreeCache used while reading a TTree. A value of -1 uses ROOT's default cache size. A value of 0 disables the cache. warn_missing_tree : bool, optional (default=False) If True, then warn when a tree is missing from an input file instead of raising an IOError. Notes ----- * Refer to the :ref:`type conversion table <conversion_table>`. See Also -------- tree2array array2tree array2root """ filenames = _glob(filenames) if not filenames: raise ValueError("specify at least one filename") if treename is None: trees = list_trees(filenames[0]) if len(trees) > 1: raise ValueError( "treename must be specified if the file " "contains more than one tree") elif not trees: raise IOError( "no trees present in {0}".format(filenames[0])) treename = trees[0] if isinstance(branches, string_types): # single branch selected flatten = branches branches = [branches] elif isinstance(branches, tuple): if len(branches) not in (2, 3): raise ValueError( "invalid branch tuple: {0}. " "A branch tuple must contain two elements " "(branch_name, fill_value) or three elements " "(branch_name, fill_value, length) " "to yield a single value or truncate, respectively".format(branches)) flatten = branches[0] branches = [branches] else: flatten = False arr = _librootnumpy.root2array_fromfile( filenames, treename, branches, selection, object_selection, start, stop, step, include_weight, weight_name, cache_size, warn_missing_tree) if flatten: # select single column return arr[flatten] return arr
[ "def", "root2array", "(", "filenames", ",", "treename", "=", "None", ",", "branches", "=", "None", ",", "selection", "=", "None", ",", "object_selection", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ",", ...
Convert trees in ROOT files into a numpy structured array. Refer to the documentation of :func:`tree2array`. Parameters ---------- filenames : str or list ROOT file name pattern or list of patterns. Wildcarding is supported by Python globbing. treename : str, optional (default=None) Name of the tree to convert (optional if each file contains exactly one tree). branches : list of strings and tuples or a string or tuple, optional (default=None) List of branches and expressions to include as columns of the array or a single branch or expression in which case a nonstructured array is returned. If None then include all branches that can be converted. Branches or expressions that result in variable-length subarrays can be truncated at a fixed length by using the tuple ``(branch_or_expression, fill_value, length)`` or converted into a single value with ``(branch_or_expression, fill_value)`` where ``length==1`` is implied. ``fill_value`` is used when the original array is shorter than ``length``. This truncation is after any object selection performed with the ``object_selection`` argument. selection : str, optional (default=None) Only include entries fulfilling this condition. If the condition evaluates to multiple values per tree entry (e.g. conditions on array branches) then an entry will be included if the condition evaluates to true for at least one array element. object_selection : dict, optional (default=None) A dictionary mapping selection strings to branch names or lists of branch names. Only array elements passing the selection strings will be included in the output array per entry in the tree. The branches specified must be variable-length array-type branches and the length of the selection and branches it acts on must match for each tree entry. For example ``object_selection={'a > 0': ['a', 'b']}`` will include all elements of 'a' and corresponding elements of 'b' where 'a > 0' for each tree entry. 'a' and 'b' must have the same length in every tree entry. start, stop, step: int, optional (default=None) The meaning of the ``start``, ``stop`` and ``step`` parameters is the same as for Python slices. If a range is supplied (by setting some of the ``start``, ``stop`` or ``step`` parameters), only the entries in that range and fulfilling the ``selection`` condition (if defined) are used. include_weight : bool, optional (default=False) Include a column containing the tree weight ``TTree::GetWeight()``. Note that this will be the same value for all entries unless the tree is actually a TChain containing multiple trees with different weights. weight_name : str, optional (default='weight') The field name for the weight column if ``include_weight=True``. cache_size : int, optional (default=-1) Set the size (in bytes) of the TTreeCache used while reading a TTree. A value of -1 uses ROOT's default cache size. A value of 0 disables the cache. warn_missing_tree : bool, optional (default=False) If True, then warn when a tree is missing from an input file instead of raising an IOError. Notes ----- * Refer to the :ref:`type conversion table <conversion_table>`. See Also -------- tree2array array2tree array2root
[ "Convert", "trees", "in", "ROOT", "files", "into", "a", "numpy", "structured", "array", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_tree.py#L120-L246
train
30,965
scikit-hep/root_numpy
root_numpy/_tree.py
tree2array
def tree2array(tree, branches=None, selection=None, object_selection=None, start=None, stop=None, step=None, include_weight=False, weight_name='weight', cache_size=-1): """Convert a tree into a numpy structured array. Convert branches of strings and basic types such as bool, int, float, double, etc. as well as variable-length and fixed-length multidimensional arrays and 1D or 2D vectors of basic types and strings. ``tree2array`` can also create columns in the output array that are expressions involving the TTree branches (i.e. ``'vect.Pt() / 1000'``) similar to ``TTree::Draw()``. See the notes below for important details. Parameters ---------- tree : ROOT TTree instance The ROOT TTree to convert into an array. branches : list of strings and tuples or a string or tuple, optional (default=None) List of branches and expressions to include as columns of the array or a single branch or expression in which case a nonstructured array is returned. If None then include all branches that can be converted. Branches or expressions that result in variable-length subarrays can be truncated at a fixed length by using the tuple ``(branch_or_expression, fill_value, length)`` or converted into a single value with ``(branch_or_expression, fill_value)`` where ``length==1`` is implied. ``fill_value`` is used when the original array is shorter than ``length``. This truncation is after any object selection performed with the ``object_selection`` argument. selection : str, optional (default=None) Only include entries fulfilling this condition. If the condition evaluates to multiple values per tree entry (e.g. conditions on array branches) then an entry will be included if the condition evaluates to true for at least one array element. object_selection : dict, optional (default=None) A dictionary mapping selection strings to branch names or lists of branch names. Only array elements passing the selection strings will be included in the output array per entry in the tree. The branches specified must be variable-length array-type branches and the length of the selection and branches it acts on must match for each tree entry. For example ``object_selection={'a > 0': ['a', 'b']}`` will include all elements of 'a' and corresponding elements of 'b' where 'a > 0' for each tree entry. 'a' and 'b' must have the same length in every tree entry. start, stop, step: int, optional (default=None) The meaning of the ``start``, ``stop`` and ``step`` parameters is the same as for Python slices. If a range is supplied (by setting some of the ``start``, ``stop`` or ``step`` parameters), only the entries in that range and fulfilling the ``selection`` condition (if defined) are used. include_weight : bool, optional (default=False) Include a column containing the tree weight ``TTree::GetWeight()``. Note that this will be the same value for all entries unless the tree is actually a TChain containing multiple trees with different weights. weight_name : str, optional (default='weight') The field name for the weight column if ``include_weight=True``. cache_size : int, optional (default=-1) Set the size (in bytes) of the TTreeCache used while reading a TTree. A value of -1 uses ROOT's default cache size. A value of 0 disables the cache. Notes ----- Types are converted according to the following table: .. _conversion_table: ======================== =============================== ROOT NumPy ======================== =============================== ``Bool_t`` ``np.bool`` ``Char_t`` ``np.int8`` ``UChar_t`` ``np.uint8`` ``Short_t`` ``np.int16`` ``UShort_t`` ``np.uint16`` ``Int_t`` ``np.int32`` ``UInt_t`` ``np.uint32`` ``Float_t`` ``np.float32`` ``Double_t`` ``np.float64`` ``Long64_t`` ``np.int64`` ``ULong64_t`` ``np.uint64`` ``<type>[2][3]...`` ``(<nptype>, (2, 3, ...))`` ``<type>[nx][2]...`` ``np.object`` ``string`` ``np.object`` ``vector<t>`` ``np.object`` ``vector<vector<t> >`` ``np.object`` ======================== =============================== * Variable-length arrays (such as ``x[nx][2]``) and vectors (such as ``vector<int>``) are converted to NumPy arrays of the corresponding types. * Fixed-length arrays are converted to fixed-length NumPy array fields. **Branches with different lengths:** Note that when converting trees that have branches of different lengths into numpy arrays, the shorter branches will be extended to match the length of the longest branch by repeating their last values. If all requested branches are shorter than the longest branch in the tree, this will result in a "read failure" since beyond the end of the longest requested branch no additional bytes will be read from the file and root_numpy is unable to distinguish this from other ROOT errors that result in no bytes being read. In this case, explicitly set the ``stop`` argument to the length of the longest requested branch. See Also -------- root2array array2root array2tree """ import ROOT if not isinstance(tree, ROOT.TTree): raise TypeError("tree must be a ROOT.TTree") cobj = ROOT.AsCObject(tree) if isinstance(branches, string_types): # single branch selected flatten = branches branches = [branches] elif isinstance(branches, tuple): if len(branches) not in (2, 3): raise ValueError( "invalid branch tuple: {0}. " "A branch tuple must contain two elements " "(branch_name, fill_value) or three elements " "(branch_name, fill_value, length) " "to yield a single value or truncate, respectively".format(branches)) flatten = branches[0] branches = [branches] else: flatten = False arr = _librootnumpy.root2array_fromtree( cobj, branches, selection, object_selection, start, stop, step, include_weight, weight_name, cache_size) if flatten: # select single column return arr[flatten] return arr
python
def tree2array(tree, branches=None, selection=None, object_selection=None, start=None, stop=None, step=None, include_weight=False, weight_name='weight', cache_size=-1): """Convert a tree into a numpy structured array. Convert branches of strings and basic types such as bool, int, float, double, etc. as well as variable-length and fixed-length multidimensional arrays and 1D or 2D vectors of basic types and strings. ``tree2array`` can also create columns in the output array that are expressions involving the TTree branches (i.e. ``'vect.Pt() / 1000'``) similar to ``TTree::Draw()``. See the notes below for important details. Parameters ---------- tree : ROOT TTree instance The ROOT TTree to convert into an array. branches : list of strings and tuples or a string or tuple, optional (default=None) List of branches and expressions to include as columns of the array or a single branch or expression in which case a nonstructured array is returned. If None then include all branches that can be converted. Branches or expressions that result in variable-length subarrays can be truncated at a fixed length by using the tuple ``(branch_or_expression, fill_value, length)`` or converted into a single value with ``(branch_or_expression, fill_value)`` where ``length==1`` is implied. ``fill_value`` is used when the original array is shorter than ``length``. This truncation is after any object selection performed with the ``object_selection`` argument. selection : str, optional (default=None) Only include entries fulfilling this condition. If the condition evaluates to multiple values per tree entry (e.g. conditions on array branches) then an entry will be included if the condition evaluates to true for at least one array element. object_selection : dict, optional (default=None) A dictionary mapping selection strings to branch names or lists of branch names. Only array elements passing the selection strings will be included in the output array per entry in the tree. The branches specified must be variable-length array-type branches and the length of the selection and branches it acts on must match for each tree entry. For example ``object_selection={'a > 0': ['a', 'b']}`` will include all elements of 'a' and corresponding elements of 'b' where 'a > 0' for each tree entry. 'a' and 'b' must have the same length in every tree entry. start, stop, step: int, optional (default=None) The meaning of the ``start``, ``stop`` and ``step`` parameters is the same as for Python slices. If a range is supplied (by setting some of the ``start``, ``stop`` or ``step`` parameters), only the entries in that range and fulfilling the ``selection`` condition (if defined) are used. include_weight : bool, optional (default=False) Include a column containing the tree weight ``TTree::GetWeight()``. Note that this will be the same value for all entries unless the tree is actually a TChain containing multiple trees with different weights. weight_name : str, optional (default='weight') The field name for the weight column if ``include_weight=True``. cache_size : int, optional (default=-1) Set the size (in bytes) of the TTreeCache used while reading a TTree. A value of -1 uses ROOT's default cache size. A value of 0 disables the cache. Notes ----- Types are converted according to the following table: .. _conversion_table: ======================== =============================== ROOT NumPy ======================== =============================== ``Bool_t`` ``np.bool`` ``Char_t`` ``np.int8`` ``UChar_t`` ``np.uint8`` ``Short_t`` ``np.int16`` ``UShort_t`` ``np.uint16`` ``Int_t`` ``np.int32`` ``UInt_t`` ``np.uint32`` ``Float_t`` ``np.float32`` ``Double_t`` ``np.float64`` ``Long64_t`` ``np.int64`` ``ULong64_t`` ``np.uint64`` ``<type>[2][3]...`` ``(<nptype>, (2, 3, ...))`` ``<type>[nx][2]...`` ``np.object`` ``string`` ``np.object`` ``vector<t>`` ``np.object`` ``vector<vector<t> >`` ``np.object`` ======================== =============================== * Variable-length arrays (such as ``x[nx][2]``) and vectors (such as ``vector<int>``) are converted to NumPy arrays of the corresponding types. * Fixed-length arrays are converted to fixed-length NumPy array fields. **Branches with different lengths:** Note that when converting trees that have branches of different lengths into numpy arrays, the shorter branches will be extended to match the length of the longest branch by repeating their last values. If all requested branches are shorter than the longest branch in the tree, this will result in a "read failure" since beyond the end of the longest requested branch no additional bytes will be read from the file and root_numpy is unable to distinguish this from other ROOT errors that result in no bytes being read. In this case, explicitly set the ``stop`` argument to the length of the longest requested branch. See Also -------- root2array array2root array2tree """ import ROOT if not isinstance(tree, ROOT.TTree): raise TypeError("tree must be a ROOT.TTree") cobj = ROOT.AsCObject(tree) if isinstance(branches, string_types): # single branch selected flatten = branches branches = [branches] elif isinstance(branches, tuple): if len(branches) not in (2, 3): raise ValueError( "invalid branch tuple: {0}. " "A branch tuple must contain two elements " "(branch_name, fill_value) or three elements " "(branch_name, fill_value, length) " "to yield a single value or truncate, respectively".format(branches)) flatten = branches[0] branches = [branches] else: flatten = False arr = _librootnumpy.root2array_fromtree( cobj, branches, selection, object_selection, start, stop, step, include_weight, weight_name, cache_size) if flatten: # select single column return arr[flatten] return arr
[ "def", "tree2array", "(", "tree", ",", "branches", "=", "None", ",", "selection", "=", "None", ",", "object_selection", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ",", "include_weight", "=", "False", ","...
Convert a tree into a numpy structured array. Convert branches of strings and basic types such as bool, int, float, double, etc. as well as variable-length and fixed-length multidimensional arrays and 1D or 2D vectors of basic types and strings. ``tree2array`` can also create columns in the output array that are expressions involving the TTree branches (i.e. ``'vect.Pt() / 1000'``) similar to ``TTree::Draw()``. See the notes below for important details. Parameters ---------- tree : ROOT TTree instance The ROOT TTree to convert into an array. branches : list of strings and tuples or a string or tuple, optional (default=None) List of branches and expressions to include as columns of the array or a single branch or expression in which case a nonstructured array is returned. If None then include all branches that can be converted. Branches or expressions that result in variable-length subarrays can be truncated at a fixed length by using the tuple ``(branch_or_expression, fill_value, length)`` or converted into a single value with ``(branch_or_expression, fill_value)`` where ``length==1`` is implied. ``fill_value`` is used when the original array is shorter than ``length``. This truncation is after any object selection performed with the ``object_selection`` argument. selection : str, optional (default=None) Only include entries fulfilling this condition. If the condition evaluates to multiple values per tree entry (e.g. conditions on array branches) then an entry will be included if the condition evaluates to true for at least one array element. object_selection : dict, optional (default=None) A dictionary mapping selection strings to branch names or lists of branch names. Only array elements passing the selection strings will be included in the output array per entry in the tree. The branches specified must be variable-length array-type branches and the length of the selection and branches it acts on must match for each tree entry. For example ``object_selection={'a > 0': ['a', 'b']}`` will include all elements of 'a' and corresponding elements of 'b' where 'a > 0' for each tree entry. 'a' and 'b' must have the same length in every tree entry. start, stop, step: int, optional (default=None) The meaning of the ``start``, ``stop`` and ``step`` parameters is the same as for Python slices. If a range is supplied (by setting some of the ``start``, ``stop`` or ``step`` parameters), only the entries in that range and fulfilling the ``selection`` condition (if defined) are used. include_weight : bool, optional (default=False) Include a column containing the tree weight ``TTree::GetWeight()``. Note that this will be the same value for all entries unless the tree is actually a TChain containing multiple trees with different weights. weight_name : str, optional (default='weight') The field name for the weight column if ``include_weight=True``. cache_size : int, optional (default=-1) Set the size (in bytes) of the TTreeCache used while reading a TTree. A value of -1 uses ROOT's default cache size. A value of 0 disables the cache. Notes ----- Types are converted according to the following table: .. _conversion_table: ======================== =============================== ROOT NumPy ======================== =============================== ``Bool_t`` ``np.bool`` ``Char_t`` ``np.int8`` ``UChar_t`` ``np.uint8`` ``Short_t`` ``np.int16`` ``UShort_t`` ``np.uint16`` ``Int_t`` ``np.int32`` ``UInt_t`` ``np.uint32`` ``Float_t`` ``np.float32`` ``Double_t`` ``np.float64`` ``Long64_t`` ``np.int64`` ``ULong64_t`` ``np.uint64`` ``<type>[2][3]...`` ``(<nptype>, (2, 3, ...))`` ``<type>[nx][2]...`` ``np.object`` ``string`` ``np.object`` ``vector<t>`` ``np.object`` ``vector<vector<t> >`` ``np.object`` ======================== =============================== * Variable-length arrays (such as ``x[nx][2]``) and vectors (such as ``vector<int>``) are converted to NumPy arrays of the corresponding types. * Fixed-length arrays are converted to fixed-length NumPy array fields. **Branches with different lengths:** Note that when converting trees that have branches of different lengths into numpy arrays, the shorter branches will be extended to match the length of the longest branch by repeating their last values. If all requested branches are shorter than the longest branch in the tree, this will result in a "read failure" since beyond the end of the longest requested branch no additional bytes will be read from the file and root_numpy is unable to distinguish this from other ROOT errors that result in no bytes being read. In this case, explicitly set the ``stop`` argument to the length of the longest requested branch. See Also -------- root2array array2root array2tree
[ "Convert", "a", "tree", "into", "a", "numpy", "structured", "array", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_tree.py#L291-L442
train
30,966
scikit-hep/root_numpy
root_numpy/_tree.py
array2tree
def array2tree(arr, name='tree', tree=None): """Convert a numpy structured array into a ROOT TTree. Fields of basic types, strings, and fixed-size subarrays of basic types are supported. ``np.object`` and ``np.float16`` are currently not supported. Parameters ---------- arr : array A numpy structured array name : str (optional, default='tree') Name of the created ROOT TTree if ``tree`` is None. tree : ROOT TTree (optional, default=None) An existing ROOT TTree to be extended by the numpy array. Any branch with the same name as a field in the numpy array will be extended as long as the types are compatible, otherwise a TypeError is raised. New branches will be created and filled for all new fields. Returns ------- root_tree : a ROOT TTree Notes ----- When using the ``tree`` argument to extend and/or add new branches to an existing tree, note that it is possible to create branches of different lengths. This will result in a warning from ROOT when root_numpy calls the tree's ``SetEntries()`` method. Beyond that, the tree should still be usable. While it might not be generally recommended to create branches with differing lengths, this behaviour could be required in certain situations. root_numpy makes no attempt to prevent such behaviour as this would be more strict than ROOT itself. Also see the note about converting trees that have branches of different lengths into numpy arrays in the documentation of :func:`tree2array`. See Also -------- array2root root2array tree2array Examples -------- Convert a numpy array into a tree: >>> from root_numpy import array2tree >>> import numpy as np >>> >>> a = np.array([(1, 2.5, 3.4), ... (4, 5, 6.8)], ... dtype=[('a', np.int32), ... ('b', np.float32), ... ('c', np.float64)]) >>> tree = array2tree(a) >>> tree.Scan() ************************************************ * Row * a * b * c * ************************************************ * 0 * 1 * 2.5 * 3.4 * * 1 * 4 * 5 * 6.8 * ************************************************ Add new branches to an existing tree (continuing from the example above): >>> b = np.array([(4, 10), ... (3, 5)], ... dtype=[('d', np.int32), ... ('e', np.int32)]) >>> array2tree(b, tree=tree) <ROOT.TTree object ("tree") at 0x1449970> >>> tree.Scan() ************************************************************************ * Row * a * b * c * d * e * ************************************************************************ * 0 * 1 * 2.5 * 3.4 * 4 * 10 * * 1 * 4 * 5 * 6.8 * 3 * 5 * ************************************************************************ """ import ROOT if tree is not None: if not isinstance(tree, ROOT.TTree): raise TypeError("tree must be a ROOT.TTree") incobj = ROOT.AsCObject(tree) else: incobj = None cobj = _librootnumpy.array2tree_toCObj(arr, name=name, tree=incobj) return ROOT.BindObject(cobj, 'TTree')
python
def array2tree(arr, name='tree', tree=None): """Convert a numpy structured array into a ROOT TTree. Fields of basic types, strings, and fixed-size subarrays of basic types are supported. ``np.object`` and ``np.float16`` are currently not supported. Parameters ---------- arr : array A numpy structured array name : str (optional, default='tree') Name of the created ROOT TTree if ``tree`` is None. tree : ROOT TTree (optional, default=None) An existing ROOT TTree to be extended by the numpy array. Any branch with the same name as a field in the numpy array will be extended as long as the types are compatible, otherwise a TypeError is raised. New branches will be created and filled for all new fields. Returns ------- root_tree : a ROOT TTree Notes ----- When using the ``tree`` argument to extend and/or add new branches to an existing tree, note that it is possible to create branches of different lengths. This will result in a warning from ROOT when root_numpy calls the tree's ``SetEntries()`` method. Beyond that, the tree should still be usable. While it might not be generally recommended to create branches with differing lengths, this behaviour could be required in certain situations. root_numpy makes no attempt to prevent such behaviour as this would be more strict than ROOT itself. Also see the note about converting trees that have branches of different lengths into numpy arrays in the documentation of :func:`tree2array`. See Also -------- array2root root2array tree2array Examples -------- Convert a numpy array into a tree: >>> from root_numpy import array2tree >>> import numpy as np >>> >>> a = np.array([(1, 2.5, 3.4), ... (4, 5, 6.8)], ... dtype=[('a', np.int32), ... ('b', np.float32), ... ('c', np.float64)]) >>> tree = array2tree(a) >>> tree.Scan() ************************************************ * Row * a * b * c * ************************************************ * 0 * 1 * 2.5 * 3.4 * * 1 * 4 * 5 * 6.8 * ************************************************ Add new branches to an existing tree (continuing from the example above): >>> b = np.array([(4, 10), ... (3, 5)], ... dtype=[('d', np.int32), ... ('e', np.int32)]) >>> array2tree(b, tree=tree) <ROOT.TTree object ("tree") at 0x1449970> >>> tree.Scan() ************************************************************************ * Row * a * b * c * d * e * ************************************************************************ * 0 * 1 * 2.5 * 3.4 * 4 * 10 * * 1 * 4 * 5 * 6.8 * 3 * 5 * ************************************************************************ """ import ROOT if tree is not None: if not isinstance(tree, ROOT.TTree): raise TypeError("tree must be a ROOT.TTree") incobj = ROOT.AsCObject(tree) else: incobj = None cobj = _librootnumpy.array2tree_toCObj(arr, name=name, tree=incobj) return ROOT.BindObject(cobj, 'TTree')
[ "def", "array2tree", "(", "arr", ",", "name", "=", "'tree'", ",", "tree", "=", "None", ")", ":", "import", "ROOT", "if", "tree", "is", "not", "None", ":", "if", "not", "isinstance", "(", "tree", ",", "ROOT", ".", "TTree", ")", ":", "raise", "TypeEr...
Convert a numpy structured array into a ROOT TTree. Fields of basic types, strings, and fixed-size subarrays of basic types are supported. ``np.object`` and ``np.float16`` are currently not supported. Parameters ---------- arr : array A numpy structured array name : str (optional, default='tree') Name of the created ROOT TTree if ``tree`` is None. tree : ROOT TTree (optional, default=None) An existing ROOT TTree to be extended by the numpy array. Any branch with the same name as a field in the numpy array will be extended as long as the types are compatible, otherwise a TypeError is raised. New branches will be created and filled for all new fields. Returns ------- root_tree : a ROOT TTree Notes ----- When using the ``tree`` argument to extend and/or add new branches to an existing tree, note that it is possible to create branches of different lengths. This will result in a warning from ROOT when root_numpy calls the tree's ``SetEntries()`` method. Beyond that, the tree should still be usable. While it might not be generally recommended to create branches with differing lengths, this behaviour could be required in certain situations. root_numpy makes no attempt to prevent such behaviour as this would be more strict than ROOT itself. Also see the note about converting trees that have branches of different lengths into numpy arrays in the documentation of :func:`tree2array`. See Also -------- array2root root2array tree2array Examples -------- Convert a numpy array into a tree: >>> from root_numpy import array2tree >>> import numpy as np >>> >>> a = np.array([(1, 2.5, 3.4), ... (4, 5, 6.8)], ... dtype=[('a', np.int32), ... ('b', np.float32), ... ('c', np.float64)]) >>> tree = array2tree(a) >>> tree.Scan() ************************************************ * Row * a * b * c * ************************************************ * 0 * 1 * 2.5 * 3.4 * * 1 * 4 * 5 * 6.8 * ************************************************ Add new branches to an existing tree (continuing from the example above): >>> b = np.array([(4, 10), ... (3, 5)], ... dtype=[('d', np.int32), ... ('e', np.int32)]) >>> array2tree(b, tree=tree) <ROOT.TTree object ("tree") at 0x1449970> >>> tree.Scan() ************************************************************************ * Row * a * b * c * d * e * ************************************************************************ * 0 * 1 * 2.5 * 3.4 * 4 * 10 * * 1 * 4 * 5 * 6.8 * 3 * 5 * ************************************************************************
[ "Convert", "a", "numpy", "structured", "array", "into", "a", "ROOT", "TTree", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_tree.py#L488-L576
train
30,967
scikit-hep/root_numpy
root_numpy/_tree.py
array2root
def array2root(arr, filename, treename='tree', mode='update'): """Convert a numpy array into a ROOT TTree and save it in a ROOT TFile. Fields of basic types, strings, and fixed-size subarrays of basic types are supported. ``np.object`` and ``np.float16`` are currently not supported. Parameters ---------- arr : array A numpy structured array filename : str Name of the output ROOT TFile. A new file will be created if it doesn't already exist. treename : str (optional, default='tree') Name of the ROOT TTree that will be created. If a TTree with the same name already exists in the TFile, it will be extended as documented in :func:`array2tree`. mode : str (optional, default='update') Mode used to open the ROOT TFile ('update' or 'recreate'). See Also -------- array2tree tree2array root2array Examples -------- >>> from root_numpy import array2root, root2array >>> import numpy as np >>> >>> a = np.array([(1, 2.5, 3.4), ... (4, 5, 6.8)], ... dtype=[('a', np.int32), ... ('b', np.float32), ... ('c', np.float64)]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([(1, 2.5, 3.4), (4, 5.0, 6.8)], dtype=[('a', '<i4'), ('b', '<f4'), ('c', '<f8')]) >>> >>> a = np.array(['', 'a', 'ab', 'abc', 'xyz', ''], ... dtype=[('string', 'S3')]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([('',), ('a',), ('ab',), ('abc',), ('xyz',), ('',)], dtype=[('string', 'S3')]) >>> >>> a = np.array([([1, 2, 3],), ... ([4, 5, 6],)], ... dtype=[('array', np.int32, (3,))]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([([1, 2, 3],), ([4, 5, 6],)], dtype=[('array', '<i4', (3,))]) """ _librootnumpy.array2root(arr, filename, treename, mode)
python
def array2root(arr, filename, treename='tree', mode='update'): """Convert a numpy array into a ROOT TTree and save it in a ROOT TFile. Fields of basic types, strings, and fixed-size subarrays of basic types are supported. ``np.object`` and ``np.float16`` are currently not supported. Parameters ---------- arr : array A numpy structured array filename : str Name of the output ROOT TFile. A new file will be created if it doesn't already exist. treename : str (optional, default='tree') Name of the ROOT TTree that will be created. If a TTree with the same name already exists in the TFile, it will be extended as documented in :func:`array2tree`. mode : str (optional, default='update') Mode used to open the ROOT TFile ('update' or 'recreate'). See Also -------- array2tree tree2array root2array Examples -------- >>> from root_numpy import array2root, root2array >>> import numpy as np >>> >>> a = np.array([(1, 2.5, 3.4), ... (4, 5, 6.8)], ... dtype=[('a', np.int32), ... ('b', np.float32), ... ('c', np.float64)]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([(1, 2.5, 3.4), (4, 5.0, 6.8)], dtype=[('a', '<i4'), ('b', '<f4'), ('c', '<f8')]) >>> >>> a = np.array(['', 'a', 'ab', 'abc', 'xyz', ''], ... dtype=[('string', 'S3')]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([('',), ('a',), ('ab',), ('abc',), ('xyz',), ('',)], dtype=[('string', 'S3')]) >>> >>> a = np.array([([1, 2, 3],), ... ([4, 5, 6],)], ... dtype=[('array', np.int32, (3,))]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([([1, 2, 3],), ([4, 5, 6],)], dtype=[('array', '<i4', (3,))]) """ _librootnumpy.array2root(arr, filename, treename, mode)
[ "def", "array2root", "(", "arr", ",", "filename", ",", "treename", "=", "'tree'", ",", "mode", "=", "'update'", ")", ":", "_librootnumpy", ".", "array2root", "(", "arr", ",", "filename", ",", "treename", ",", "mode", ")" ]
Convert a numpy array into a ROOT TTree and save it in a ROOT TFile. Fields of basic types, strings, and fixed-size subarrays of basic types are supported. ``np.object`` and ``np.float16`` are currently not supported. Parameters ---------- arr : array A numpy structured array filename : str Name of the output ROOT TFile. A new file will be created if it doesn't already exist. treename : str (optional, default='tree') Name of the ROOT TTree that will be created. If a TTree with the same name already exists in the TFile, it will be extended as documented in :func:`array2tree`. mode : str (optional, default='update') Mode used to open the ROOT TFile ('update' or 'recreate'). See Also -------- array2tree tree2array root2array Examples -------- >>> from root_numpy import array2root, root2array >>> import numpy as np >>> >>> a = np.array([(1, 2.5, 3.4), ... (4, 5, 6.8)], ... dtype=[('a', np.int32), ... ('b', np.float32), ... ('c', np.float64)]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([(1, 2.5, 3.4), (4, 5.0, 6.8)], dtype=[('a', '<i4'), ('b', '<f4'), ('c', '<f8')]) >>> >>> a = np.array(['', 'a', 'ab', 'abc', 'xyz', ''], ... dtype=[('string', 'S3')]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([('',), ('a',), ('ab',), ('abc',), ('xyz',), ('',)], dtype=[('string', 'S3')]) >>> >>> a = np.array([([1, 2, 3],), ... ([4, 5, 6],)], ... dtype=[('array', np.int32, (3,))]) >>> array2root(a, 'test.root', mode='recreate') >>> root2array('test.root') array([([1, 2, 3],), ([4, 5, 6],)], dtype=[('array', '<i4', (3,))])
[ "Convert", "a", "numpy", "array", "into", "a", "ROOT", "TTree", "and", "save", "it", "in", "a", "ROOT", "TFile", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_tree.py#L579-L637
train
30,968
scikit-hep/root_numpy
root_numpy/_hist.py
fill_hist
def fill_hist(hist, array, weights=None, return_indices=False): """Fill a ROOT histogram with a NumPy array. Parameters ---------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. The number of columns must match the dimensionality of the histogram. Supply a flat numpy array when filling a 1D histogram. weights : numpy array A flat numpy array of weights for each sample in ``array``. return_indices : bool, optional (default=False) If True then return an array of the bin indices filled for each element in ``array``. Returns ------- indices : numpy array or None If ``return_indices`` is True, then return an array of the bin indices filled for each element in ``array`` otherwise return None. """ import ROOT array = np.asarray(array, dtype=np.double) if weights is not None: weights = np.asarray(weights, dtype=np.double) if weights.shape[0] != array.shape[0]: raise ValueError("array and weights must have the same length") if weights.ndim != 1: raise ValueError("weight must be 1-dimensional") if isinstance(hist, ROOT.TH3): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 3: raise ValueError( "length of the second dimension must equal " "the dimension of the histogram") return _librootnumpy.fill_h3( ROOT.AsCObject(hist), array, weights, return_indices) elif isinstance(hist, ROOT.TH2): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 2: raise ValueError( "length of the second dimension must equal " "the dimension of the histogram") return _librootnumpy.fill_h2( ROOT.AsCObject(hist), array, weights, return_indices) elif isinstance(hist, ROOT.TH1): if array.ndim != 1: raise ValueError("array must be 1-dimensional") return _librootnumpy.fill_h1( ROOT.AsCObject(hist), array, weights, return_indices) raise TypeError( "hist must be an instance of ROOT.TH1, ROOT.TH2, or ROOT.TH3")
python
def fill_hist(hist, array, weights=None, return_indices=False): """Fill a ROOT histogram with a NumPy array. Parameters ---------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. The number of columns must match the dimensionality of the histogram. Supply a flat numpy array when filling a 1D histogram. weights : numpy array A flat numpy array of weights for each sample in ``array``. return_indices : bool, optional (default=False) If True then return an array of the bin indices filled for each element in ``array``. Returns ------- indices : numpy array or None If ``return_indices`` is True, then return an array of the bin indices filled for each element in ``array`` otherwise return None. """ import ROOT array = np.asarray(array, dtype=np.double) if weights is not None: weights = np.asarray(weights, dtype=np.double) if weights.shape[0] != array.shape[0]: raise ValueError("array and weights must have the same length") if weights.ndim != 1: raise ValueError("weight must be 1-dimensional") if isinstance(hist, ROOT.TH3): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 3: raise ValueError( "length of the second dimension must equal " "the dimension of the histogram") return _librootnumpy.fill_h3( ROOT.AsCObject(hist), array, weights, return_indices) elif isinstance(hist, ROOT.TH2): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 2: raise ValueError( "length of the second dimension must equal " "the dimension of the histogram") return _librootnumpy.fill_h2( ROOT.AsCObject(hist), array, weights, return_indices) elif isinstance(hist, ROOT.TH1): if array.ndim != 1: raise ValueError("array must be 1-dimensional") return _librootnumpy.fill_h1( ROOT.AsCObject(hist), array, weights, return_indices) raise TypeError( "hist must be an instance of ROOT.TH1, ROOT.TH2, or ROOT.TH3")
[ "def", "fill_hist", "(", "hist", ",", "array", ",", "weights", "=", "None", ",", "return_indices", "=", "False", ")", ":", "import", "ROOT", "array", "=", "np", ".", "asarray", "(", "array", ",", "dtype", "=", "np", ".", "double", ")", "if", "weights...
Fill a ROOT histogram with a NumPy array. Parameters ---------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. The number of columns must match the dimensionality of the histogram. Supply a flat numpy array when filling a 1D histogram. weights : numpy array A flat numpy array of weights for each sample in ``array``. return_indices : bool, optional (default=False) If True then return an array of the bin indices filled for each element in ``array``. Returns ------- indices : numpy array or None If ``return_indices`` is True, then return an array of the bin indices filled for each element in ``array`` otherwise return None.
[ "Fill", "a", "ROOT", "histogram", "with", "a", "NumPy", "array", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_hist.py#L22-L78
train
30,969
scikit-hep/root_numpy
root_numpy/_hist.py
fill_profile
def fill_profile(profile, array, weights=None, return_indices=False): """Fill a ROOT profile with a NumPy array. Parameters ---------- profile : ROOT TProfile, TProfile2D, or TProfile3D The ROOT profile to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. There must be one more column than the dimensionality of the profile. weights : numpy array A flat numpy array of weights for each sample in ``array``. return_indices : bool, optional (default=False) If True then return an array of the bin indices filled for each element in ``array``. Returns ------- indices : numpy array or None If ``return_indices`` is True, then return an array of the bin indices filled for each element in ``array`` otherwise return None. """ import ROOT array = np.asarray(array, dtype=np.double) if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != profile.GetDimension() + 1: raise ValueError( "there must be one more column than the " "dimensionality of the profile") if weights is not None: weights = np.asarray(weights, dtype=np.double) if weights.shape[0] != array.shape[0]: raise ValueError("array and weights must have the same length") if weights.ndim != 1: raise ValueError("weight must be 1-dimensional") if isinstance(profile, ROOT.TProfile3D): return _librootnumpy.fill_p3( ROOT.AsCObject(profile), array, weights, return_indices) elif isinstance(profile, ROOT.TProfile2D): return _librootnumpy.fill_p2( ROOT.AsCObject(profile), array, weights, return_indices) elif isinstance(profile, ROOT.TProfile): return _librootnumpy.fill_p1( ROOT.AsCObject(profile), array, weights, return_indices) raise TypeError( "profile must be an instance of " "ROOT.TProfile, ROOT.TProfile2D, or ROOT.TProfile3D")
python
def fill_profile(profile, array, weights=None, return_indices=False): """Fill a ROOT profile with a NumPy array. Parameters ---------- profile : ROOT TProfile, TProfile2D, or TProfile3D The ROOT profile to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. There must be one more column than the dimensionality of the profile. weights : numpy array A flat numpy array of weights for each sample in ``array``. return_indices : bool, optional (default=False) If True then return an array of the bin indices filled for each element in ``array``. Returns ------- indices : numpy array or None If ``return_indices`` is True, then return an array of the bin indices filled for each element in ``array`` otherwise return None. """ import ROOT array = np.asarray(array, dtype=np.double) if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != profile.GetDimension() + 1: raise ValueError( "there must be one more column than the " "dimensionality of the profile") if weights is not None: weights = np.asarray(weights, dtype=np.double) if weights.shape[0] != array.shape[0]: raise ValueError("array and weights must have the same length") if weights.ndim != 1: raise ValueError("weight must be 1-dimensional") if isinstance(profile, ROOT.TProfile3D): return _librootnumpy.fill_p3( ROOT.AsCObject(profile), array, weights, return_indices) elif isinstance(profile, ROOT.TProfile2D): return _librootnumpy.fill_p2( ROOT.AsCObject(profile), array, weights, return_indices) elif isinstance(profile, ROOT.TProfile): return _librootnumpy.fill_p1( ROOT.AsCObject(profile), array, weights, return_indices) raise TypeError( "profile must be an instance of " "ROOT.TProfile, ROOT.TProfile2D, or ROOT.TProfile3D")
[ "def", "fill_profile", "(", "profile", ",", "array", ",", "weights", "=", "None", ",", "return_indices", "=", "False", ")", ":", "import", "ROOT", "array", "=", "np", ".", "asarray", "(", "array", ",", "dtype", "=", "np", ".", "double", ")", "if", "a...
Fill a ROOT profile with a NumPy array. Parameters ---------- profile : ROOT TProfile, TProfile2D, or TProfile3D The ROOT profile to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. There must be one more column than the dimensionality of the profile. weights : numpy array A flat numpy array of weights for each sample in ``array``. return_indices : bool, optional (default=False) If True then return an array of the bin indices filled for each element in ``array``. Returns ------- indices : numpy array or None If ``return_indices`` is True, then return an array of the bin indices filled for each element in ``array`` otherwise return None.
[ "Fill", "a", "ROOT", "profile", "with", "a", "NumPy", "array", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_hist.py#L81-L129
train
30,970
scikit-hep/root_numpy
root_numpy/_hist.py
array2hist
def array2hist(array, hist, errors=None): """Convert a NumPy array into a ROOT histogram Parameters ---------- array : numpy array A 1, 2, or 3-d numpy array that will set the bin contents of the ROOT histogram. hist : ROOT TH1, TH2, or TH3 A ROOT histogram. errors : numpy array A numpy array of errors with matching dimensionality as the bin contents array. If not given, no errors are set Returns ------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram with bin contents set from the array. Raises ------ TypeError If hist is not a ROOT histogram. ValueError If the array and histogram are not compatible in terms of dimensionality or number of bins along any axis. Notes ----- The NumPy array is copied into the histogram's internal array. If the input NumPy array is not of the same data type as the histogram bin contents (i.e. TH1D vs TH1F, etc.) and/or the input array does not contain overflow bins along any of the axes, an additional copy is made into a temporary array with all values converted into the matching data type and with overflow bins included. Avoid this second copy by ensuring that the NumPy array data type matches the histogram data type and that overflow bins are included. See Also -------- hist2array Examples -------- >>> from root_numpy import array2hist, hist2array >>> import numpy as np >>> from rootpy.plotting import Hist2D >>> hist = Hist2D(5, 0, 1, 3, 0, 1, type='F') >>> array = np.random.randint(0, 10, size=(7, 5)) >>> array array([[6, 7, 8, 3, 4], [8, 9, 7, 6, 2], [2, 3, 4, 5, 2], [7, 6, 5, 7, 3], [2, 0, 5, 6, 8], [0, 0, 6, 5, 2], [2, 2, 1, 5, 4]]) >>> _ = array2hist(array, hist) >>> # dtype matches histogram type (D, F, I, S, C) >>> hist2array(hist) array([[ 9., 7., 6.], [ 3., 4., 5.], [ 6., 5., 7.], [ 0., 5., 6.], [ 0., 6., 5.]], dtype=float32) >>> # overflow is excluded by default >>> hist2array(hist, include_overflow=True) array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., 4., 5., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32) >>> array2 = hist2array(hist, include_overflow=True, copy=False) >>> hist[2, 2] = -10 >>> # array2 views the same memory as hist because copy=False >>> array2 array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., -10., 5., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32) >>> # x, y, z axes correspond to axes 0, 1, 2 in numpy >>> hist[2, 3] = -10 >>> array2 array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., -10., -10., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32) """ import ROOT if isinstance(hist, ROOT.TH3): shape = (hist.GetNbinsX() + 2, hist.GetNbinsY() + 2, hist.GetNbinsZ() + 2) elif isinstance(hist, ROOT.TH2): shape = (hist.GetNbinsX() + 2, hist.GetNbinsY() + 2) elif isinstance(hist, ROOT.TH1): shape = (hist.GetNbinsX() + 2,) else: raise TypeError( "hist must be an instance of ROOT.TH1, ROOT.TH2, or ROOT.TH3") # Determine the corresponding numpy dtype for hist_type in 'DFISC': if isinstance(hist, getattr(ROOT, 'TArray{0}'.format(hist_type))): break else: raise AssertionError( "hist is somehow an instance of TH[1|2|3] " "but not TArray[D|F|I|S|C]") # Constuct a NumPy array viewing the underlying histogram array dtype = np.dtype(DTYPE_ROOT2NUMPY[hist_type]) # No copy is made if the dtype is the same as input _array = np.ascontiguousarray(array, dtype=dtype) if errors is not None: if errors.shape != array.shape: raise ValueError("Contents and errors are not compatible") # errors are specified as doubles in SetError function _errors = np.ascontiguousarray(errors, dtype=np.float64) else: _errors = None if _array.ndim != len(shape): raise ValueError( "array and histogram do not have " "the same number of dimensions") if _array.shape != shape: # Check for overflow along each axis slices = [] for axis, bins in enumerate(shape): if _array.shape[axis] == bins - 2: slices.append(slice(1, -1)) elif _array.shape[axis] == bins: slices.append(slice(None)) else: raise ValueError( "array and histogram are not compatible along " "the {0}-axis".format("xyz"[axis])) array_overflow = np.zeros(shape, dtype=dtype) array_overflow[tuple(slices)] = _array _array = array_overflow if _errors is not None: errors_overflow = np.zeros(shape, dtype=np.float64) errors_overflow[tuple(slices)] = _errors _errors = errors_overflow ARRAY_NUMPY2ROOT[len(shape)][hist_type]( ROOT.AsCObject(hist), np.ravel(np.transpose(_array))) # Set the number of entries to the number of array elements hist.SetEntries(_array.size) if _errors is not None: hist.SetError(np.ravel(_errors.T)) return hist
python
def array2hist(array, hist, errors=None): """Convert a NumPy array into a ROOT histogram Parameters ---------- array : numpy array A 1, 2, or 3-d numpy array that will set the bin contents of the ROOT histogram. hist : ROOT TH1, TH2, or TH3 A ROOT histogram. errors : numpy array A numpy array of errors with matching dimensionality as the bin contents array. If not given, no errors are set Returns ------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram with bin contents set from the array. Raises ------ TypeError If hist is not a ROOT histogram. ValueError If the array and histogram are not compatible in terms of dimensionality or number of bins along any axis. Notes ----- The NumPy array is copied into the histogram's internal array. If the input NumPy array is not of the same data type as the histogram bin contents (i.e. TH1D vs TH1F, etc.) and/or the input array does not contain overflow bins along any of the axes, an additional copy is made into a temporary array with all values converted into the matching data type and with overflow bins included. Avoid this second copy by ensuring that the NumPy array data type matches the histogram data type and that overflow bins are included. See Also -------- hist2array Examples -------- >>> from root_numpy import array2hist, hist2array >>> import numpy as np >>> from rootpy.plotting import Hist2D >>> hist = Hist2D(5, 0, 1, 3, 0, 1, type='F') >>> array = np.random.randint(0, 10, size=(7, 5)) >>> array array([[6, 7, 8, 3, 4], [8, 9, 7, 6, 2], [2, 3, 4, 5, 2], [7, 6, 5, 7, 3], [2, 0, 5, 6, 8], [0, 0, 6, 5, 2], [2, 2, 1, 5, 4]]) >>> _ = array2hist(array, hist) >>> # dtype matches histogram type (D, F, I, S, C) >>> hist2array(hist) array([[ 9., 7., 6.], [ 3., 4., 5.], [ 6., 5., 7.], [ 0., 5., 6.], [ 0., 6., 5.]], dtype=float32) >>> # overflow is excluded by default >>> hist2array(hist, include_overflow=True) array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., 4., 5., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32) >>> array2 = hist2array(hist, include_overflow=True, copy=False) >>> hist[2, 2] = -10 >>> # array2 views the same memory as hist because copy=False >>> array2 array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., -10., 5., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32) >>> # x, y, z axes correspond to axes 0, 1, 2 in numpy >>> hist[2, 3] = -10 >>> array2 array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., -10., -10., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32) """ import ROOT if isinstance(hist, ROOT.TH3): shape = (hist.GetNbinsX() + 2, hist.GetNbinsY() + 2, hist.GetNbinsZ() + 2) elif isinstance(hist, ROOT.TH2): shape = (hist.GetNbinsX() + 2, hist.GetNbinsY() + 2) elif isinstance(hist, ROOT.TH1): shape = (hist.GetNbinsX() + 2,) else: raise TypeError( "hist must be an instance of ROOT.TH1, ROOT.TH2, or ROOT.TH3") # Determine the corresponding numpy dtype for hist_type in 'DFISC': if isinstance(hist, getattr(ROOT, 'TArray{0}'.format(hist_type))): break else: raise AssertionError( "hist is somehow an instance of TH[1|2|3] " "but not TArray[D|F|I|S|C]") # Constuct a NumPy array viewing the underlying histogram array dtype = np.dtype(DTYPE_ROOT2NUMPY[hist_type]) # No copy is made if the dtype is the same as input _array = np.ascontiguousarray(array, dtype=dtype) if errors is not None: if errors.shape != array.shape: raise ValueError("Contents and errors are not compatible") # errors are specified as doubles in SetError function _errors = np.ascontiguousarray(errors, dtype=np.float64) else: _errors = None if _array.ndim != len(shape): raise ValueError( "array and histogram do not have " "the same number of dimensions") if _array.shape != shape: # Check for overflow along each axis slices = [] for axis, bins in enumerate(shape): if _array.shape[axis] == bins - 2: slices.append(slice(1, -1)) elif _array.shape[axis] == bins: slices.append(slice(None)) else: raise ValueError( "array and histogram are not compatible along " "the {0}-axis".format("xyz"[axis])) array_overflow = np.zeros(shape, dtype=dtype) array_overflow[tuple(slices)] = _array _array = array_overflow if _errors is not None: errors_overflow = np.zeros(shape, dtype=np.float64) errors_overflow[tuple(slices)] = _errors _errors = errors_overflow ARRAY_NUMPY2ROOT[len(shape)][hist_type]( ROOT.AsCObject(hist), np.ravel(np.transpose(_array))) # Set the number of entries to the number of array elements hist.SetEntries(_array.size) if _errors is not None: hist.SetError(np.ravel(_errors.T)) return hist
[ "def", "array2hist", "(", "array", ",", "hist", ",", "errors", "=", "None", ")", ":", "import", "ROOT", "if", "isinstance", "(", "hist", ",", "ROOT", ".", "TH3", ")", ":", "shape", "=", "(", "hist", ".", "GetNbinsX", "(", ")", "+", "2", ",", "his...
Convert a NumPy array into a ROOT histogram Parameters ---------- array : numpy array A 1, 2, or 3-d numpy array that will set the bin contents of the ROOT histogram. hist : ROOT TH1, TH2, or TH3 A ROOT histogram. errors : numpy array A numpy array of errors with matching dimensionality as the bin contents array. If not given, no errors are set Returns ------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram with bin contents set from the array. Raises ------ TypeError If hist is not a ROOT histogram. ValueError If the array and histogram are not compatible in terms of dimensionality or number of bins along any axis. Notes ----- The NumPy array is copied into the histogram's internal array. If the input NumPy array is not of the same data type as the histogram bin contents (i.e. TH1D vs TH1F, etc.) and/or the input array does not contain overflow bins along any of the axes, an additional copy is made into a temporary array with all values converted into the matching data type and with overflow bins included. Avoid this second copy by ensuring that the NumPy array data type matches the histogram data type and that overflow bins are included. See Also -------- hist2array Examples -------- >>> from root_numpy import array2hist, hist2array >>> import numpy as np >>> from rootpy.plotting import Hist2D >>> hist = Hist2D(5, 0, 1, 3, 0, 1, type='F') >>> array = np.random.randint(0, 10, size=(7, 5)) >>> array array([[6, 7, 8, 3, 4], [8, 9, 7, 6, 2], [2, 3, 4, 5, 2], [7, 6, 5, 7, 3], [2, 0, 5, 6, 8], [0, 0, 6, 5, 2], [2, 2, 1, 5, 4]]) >>> _ = array2hist(array, hist) >>> # dtype matches histogram type (D, F, I, S, C) >>> hist2array(hist) array([[ 9., 7., 6.], [ 3., 4., 5.], [ 6., 5., 7.], [ 0., 5., 6.], [ 0., 6., 5.]], dtype=float32) >>> # overflow is excluded by default >>> hist2array(hist, include_overflow=True) array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., 4., 5., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32) >>> array2 = hist2array(hist, include_overflow=True, copy=False) >>> hist[2, 2] = -10 >>> # array2 views the same memory as hist because copy=False >>> array2 array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., -10., 5., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32) >>> # x, y, z axes correspond to axes 0, 1, 2 in numpy >>> hist[2, 3] = -10 >>> array2 array([[ 6., 7., 8., 3., 4.], [ 8., 9., 7., 6., 2.], [ 2., 3., -10., -10., 2.], [ 7., 6., 5., 7., 3.], [ 2., 0., 5., 6., 8.], [ 0., 0., 6., 5., 2.], [ 2., 2., 1., 5., 4.]], dtype=float32)
[ "Convert", "a", "NumPy", "array", "into", "a", "ROOT", "histogram" ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_hist.py#L263-L426
train
30,971
scikit-hep/root_numpy
docs/sphinxext/gen_rst.py
extract_docstring
def extract_docstring(filename): """ Extract a module-level docstring, if any """ lines = file(filename).readlines() start_row = 0 if lines[0].startswith('#!'): lines.pop(0) start_row = 1 docstring = '' first_par = '' tokens = tokenize.generate_tokens(iter(lines).next) for tok_type, tok_content, _, (erow, _), _ in tokens: tok_type = token.tok_name[tok_type] if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'): continue elif tok_type == 'STRING': docstring = eval(tok_content) # If the docstring is formatted with several paragraphs, extract # the first one: paragraphs = '\n'.join(line.rstrip() for line in docstring.split('\n')).split('\n\n') if len(paragraphs) > 0: first_par = paragraphs[0] break end_row = erow + 1 + start_row if lines and lines[end_row - 2] == 'print(__doc__)\n': end_row += 1 return docstring, first_par, end_row
python
def extract_docstring(filename): """ Extract a module-level docstring, if any """ lines = file(filename).readlines() start_row = 0 if lines[0].startswith('#!'): lines.pop(0) start_row = 1 docstring = '' first_par = '' tokens = tokenize.generate_tokens(iter(lines).next) for tok_type, tok_content, _, (erow, _), _ in tokens: tok_type = token.tok_name[tok_type] if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'): continue elif tok_type == 'STRING': docstring = eval(tok_content) # If the docstring is formatted with several paragraphs, extract # the first one: paragraphs = '\n'.join(line.rstrip() for line in docstring.split('\n')).split('\n\n') if len(paragraphs) > 0: first_par = paragraphs[0] break end_row = erow + 1 + start_row if lines and lines[end_row - 2] == 'print(__doc__)\n': end_row += 1 return docstring, first_par, end_row
[ "def", "extract_docstring", "(", "filename", ")", ":", "lines", "=", "file", "(", "filename", ")", ".", "readlines", "(", ")", "start_row", "=", "0", "if", "lines", "[", "0", "]", ".", "startswith", "(", "'#!'", ")", ":", "lines", ".", "pop", "(", ...
Extract a module-level docstring, if any
[ "Extract", "a", "module", "-", "level", "docstring", "if", "any" ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/docs/sphinxext/gen_rst.py#L94-L122
train
30,972
scikit-hep/root_numpy
docs/sphinxext/gen_rst.py
generate_example_rst
def generate_example_rst(app): """ Generate the list of examples, as well as the contents of examples. """ root_dir = os.path.join(app.builder.srcdir, 'auto_examples') example_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples') try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) if not os.path.exists(example_dir): os.makedirs(example_dir) if not os.path.exists(root_dir): os.makedirs(root_dir) # we create an index.rst with all examples fhindex = file(os.path.join(root_dir, 'index.rst'), 'w') #Note: The sidebar button has been removed from the examples page for now # due to how it messes up the layout. Will be fixed at a later point fhindex.write("""\ .. raw:: html <style type="text/css"> div#sidebarbutton { display: none; } .figure { float: left; margin: 10px; width: auto; height: 200px; width: 180px; } .figure img { display: inline; } .figure .caption { width: 170px; text-align: center !important; } </style> .. _examples-index: Examples ======== """) # Here we don't use an os.walk, but we recurse only twice: flat is # better than nested. generate_dir_rst('.', fhindex, example_dir, root_dir, plot_gallery) for dir in sorted(os.listdir(example_dir)): if os.path.isdir(os.path.join(example_dir, dir)): generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery) fhindex.flush()
python
def generate_example_rst(app): """ Generate the list of examples, as well as the contents of examples. """ root_dir = os.path.join(app.builder.srcdir, 'auto_examples') example_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples') try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) if not os.path.exists(example_dir): os.makedirs(example_dir) if not os.path.exists(root_dir): os.makedirs(root_dir) # we create an index.rst with all examples fhindex = file(os.path.join(root_dir, 'index.rst'), 'w') #Note: The sidebar button has been removed from the examples page for now # due to how it messes up the layout. Will be fixed at a later point fhindex.write("""\ .. raw:: html <style type="text/css"> div#sidebarbutton { display: none; } .figure { float: left; margin: 10px; width: auto; height: 200px; width: 180px; } .figure img { display: inline; } .figure .caption { width: 170px; text-align: center !important; } </style> .. _examples-index: Examples ======== """) # Here we don't use an os.walk, but we recurse only twice: flat is # better than nested. generate_dir_rst('.', fhindex, example_dir, root_dir, plot_gallery) for dir in sorted(os.listdir(example_dir)): if os.path.isdir(os.path.join(example_dir, dir)): generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery) fhindex.flush()
[ "def", "generate_example_rst", "(", "app", ")", ":", "root_dir", "=", "os", ".", "path", ".", "join", "(", "app", ".", "builder", ".", "srcdir", ",", "'auto_examples'", ")", "example_dir", "=", "os", ".", "path", ".", "abspath", "(", "app", ".", "build...
Generate the list of examples, as well as the contents of examples.
[ "Generate", "the", "list", "of", "examples", "as", "well", "as", "the", "contents", "of", "examples", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/docs/sphinxext/gen_rst.py#L125-L185
train
30,973
scikit-hep/root_numpy
root_numpy/_array.py
array
def array(arr, copy=True): """Convert a ROOT TArray into a NumPy array. Parameters ---------- arr : ROOT TArray A ROOT TArrayD, TArrayF, TArrayL, TArrayI or TArrayS copy : bool, optional (default=True) If True (the default) then copy the underlying array, otherwise the NumPy array will view (and not own) the same memory as the ROOT array. Returns ------- arr : NumPy array A NumPy array Examples -------- >>> from root_numpy import array >>> from ROOT import TArrayD >>> a = TArrayD(5) >>> a[3] = 3.141 >>> array(a) array([ 0. , 0. , 0. , 3.141, 0. ]) """ import ROOT if isinstance(arr, ROOT.TArrayD): arr = _librootnumpy.array_d(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayF): arr = _librootnumpy.array_f(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayL): arr = _librootnumpy.array_l(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayI): arr = _librootnumpy.array_i(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayS): arr = _librootnumpy.array_s(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayC): arr = _librootnumpy.array_c(ROOT.AsCObject(arr)) else: raise TypeError( "unable to convert object of type {0} " "into a numpy array".format(type(arr))) if copy: return np.copy(arr) return arr
python
def array(arr, copy=True): """Convert a ROOT TArray into a NumPy array. Parameters ---------- arr : ROOT TArray A ROOT TArrayD, TArrayF, TArrayL, TArrayI or TArrayS copy : bool, optional (default=True) If True (the default) then copy the underlying array, otherwise the NumPy array will view (and not own) the same memory as the ROOT array. Returns ------- arr : NumPy array A NumPy array Examples -------- >>> from root_numpy import array >>> from ROOT import TArrayD >>> a = TArrayD(5) >>> a[3] = 3.141 >>> array(a) array([ 0. , 0. , 0. , 3.141, 0. ]) """ import ROOT if isinstance(arr, ROOT.TArrayD): arr = _librootnumpy.array_d(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayF): arr = _librootnumpy.array_f(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayL): arr = _librootnumpy.array_l(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayI): arr = _librootnumpy.array_i(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayS): arr = _librootnumpy.array_s(ROOT.AsCObject(arr)) elif isinstance(arr, ROOT.TArrayC): arr = _librootnumpy.array_c(ROOT.AsCObject(arr)) else: raise TypeError( "unable to convert object of type {0} " "into a numpy array".format(type(arr))) if copy: return np.copy(arr) return arr
[ "def", "array", "(", "arr", ",", "copy", "=", "True", ")", ":", "import", "ROOT", "if", "isinstance", "(", "arr", ",", "ROOT", ".", "TArrayD", ")", ":", "arr", "=", "_librootnumpy", ".", "array_d", "(", "ROOT", ".", "AsCObject", "(", "arr", ")", ")...
Convert a ROOT TArray into a NumPy array. Parameters ---------- arr : ROOT TArray A ROOT TArrayD, TArrayF, TArrayL, TArrayI or TArrayS copy : bool, optional (default=True) If True (the default) then copy the underlying array, otherwise the NumPy array will view (and not own) the same memory as the ROOT array. Returns ------- arr : NumPy array A NumPy array Examples -------- >>> from root_numpy import array >>> from ROOT import TArrayD >>> a = TArrayD(5) >>> a[3] = 3.141 >>> array(a) array([ 0. , 0. , 0. , 3.141, 0. ])
[ "Convert", "a", "ROOT", "TArray", "into", "a", "NumPy", "array", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_array.py#L10-L55
train
30,974
scikit-hep/root_numpy
root_numpy/_utils.py
stretch
def stretch(arr, fields=None, return_indices=False): """Stretch an array. Stretch an array by ``hstack()``-ing multiple array fields while preserving column names and record array structure. If a scalar field is specified, it will be stretched along with array fields. Parameters ---------- arr : NumPy structured or record array The array to be stretched. fields : list of strings or string, optional (default=None) A list of column names or a single column name to stretch. If ``fields`` is a string, then the output array is a one-dimensional unstructured array containing only the stretched elements of that field. If None, then stretch all fields. return_indices : bool, optional (default=False) If True, the array index of each stretched array entry will be returned in addition to the stretched array. This changes the return type of this function to a tuple consisting of a structured array and a numpy int64 array. Returns ------- ret : A NumPy structured array The stretched array. Examples -------- >>> import numpy as np >>> from root_numpy import stretch >>> arr = np.empty(2, dtype=[('scalar', np.int), ('array', 'O')]) >>> arr[0] = (0, np.array([1, 2, 3], dtype=np.float)) >>> arr[1] = (1, np.array([4, 5, 6], dtype=np.float)) >>> stretch(arr, ['scalar', 'array']) array([(0, 1.0), (0, 2.0), (0, 3.0), (1, 4.0), (1, 5.0), (1, 6.0)], dtype=[('scalar', '<i8'), ('array', '<f8')]) """ dtype = [] len_array = None flatten = False if fields is None: fields = arr.dtype.names elif isinstance(fields, string_types): fields = [fields] flatten = True # Construct dtype and check consistency for field in fields: dt = arr.dtype[field] if dt == 'O' or len(dt.shape): if dt == 'O': # Variable-length array field lengths = VLEN(arr[field]) else: # Fixed-length array field lengths = np.repeat(dt.shape[0], arr.shape[0]) if len_array is None: len_array = lengths elif not np.array_equal(lengths, len_array): raise ValueError( "inconsistent lengths of array columns in input") if dt == 'O': dtype.append((field, arr[field][0].dtype)) else: dtype.append((field, arr[field].dtype, dt.shape[1:])) else: # Scalar field dtype.append((field, dt)) if len_array is None: raise RuntimeError("no array column in input") # Build stretched output ret = np.empty(np.sum(len_array), dtype=dtype) for field in fields: dt = arr.dtype[field] if dt == 'O' or len(dt.shape) == 1: # Variable-length or 1D fixed-length array field ret[field] = np.hstack(arr[field]) elif len(dt.shape): # Multidimensional fixed-length array field ret[field] = np.vstack(arr[field]) else: # Scalar field ret[field] = np.repeat(arr[field], len_array) if flatten: ret = ret[fields[0]] if return_indices: idx = np.concatenate(list(map(np.arange, len_array))) return ret, idx return ret
python
def stretch(arr, fields=None, return_indices=False): """Stretch an array. Stretch an array by ``hstack()``-ing multiple array fields while preserving column names and record array structure. If a scalar field is specified, it will be stretched along with array fields. Parameters ---------- arr : NumPy structured or record array The array to be stretched. fields : list of strings or string, optional (default=None) A list of column names or a single column name to stretch. If ``fields`` is a string, then the output array is a one-dimensional unstructured array containing only the stretched elements of that field. If None, then stretch all fields. return_indices : bool, optional (default=False) If True, the array index of each stretched array entry will be returned in addition to the stretched array. This changes the return type of this function to a tuple consisting of a structured array and a numpy int64 array. Returns ------- ret : A NumPy structured array The stretched array. Examples -------- >>> import numpy as np >>> from root_numpy import stretch >>> arr = np.empty(2, dtype=[('scalar', np.int), ('array', 'O')]) >>> arr[0] = (0, np.array([1, 2, 3], dtype=np.float)) >>> arr[1] = (1, np.array([4, 5, 6], dtype=np.float)) >>> stretch(arr, ['scalar', 'array']) array([(0, 1.0), (0, 2.0), (0, 3.0), (1, 4.0), (1, 5.0), (1, 6.0)], dtype=[('scalar', '<i8'), ('array', '<f8')]) """ dtype = [] len_array = None flatten = False if fields is None: fields = arr.dtype.names elif isinstance(fields, string_types): fields = [fields] flatten = True # Construct dtype and check consistency for field in fields: dt = arr.dtype[field] if dt == 'O' or len(dt.shape): if dt == 'O': # Variable-length array field lengths = VLEN(arr[field]) else: # Fixed-length array field lengths = np.repeat(dt.shape[0], arr.shape[0]) if len_array is None: len_array = lengths elif not np.array_equal(lengths, len_array): raise ValueError( "inconsistent lengths of array columns in input") if dt == 'O': dtype.append((field, arr[field][0].dtype)) else: dtype.append((field, arr[field].dtype, dt.shape[1:])) else: # Scalar field dtype.append((field, dt)) if len_array is None: raise RuntimeError("no array column in input") # Build stretched output ret = np.empty(np.sum(len_array), dtype=dtype) for field in fields: dt = arr.dtype[field] if dt == 'O' or len(dt.shape) == 1: # Variable-length or 1D fixed-length array field ret[field] = np.hstack(arr[field]) elif len(dt.shape): # Multidimensional fixed-length array field ret[field] = np.vstack(arr[field]) else: # Scalar field ret[field] = np.repeat(arr[field], len_array) if flatten: ret = ret[fields[0]] if return_indices: idx = np.concatenate(list(map(np.arange, len_array))) return ret, idx return ret
[ "def", "stretch", "(", "arr", ",", "fields", "=", "None", ",", "return_indices", "=", "False", ")", ":", "dtype", "=", "[", "]", "len_array", "=", "None", "flatten", "=", "False", "if", "fields", "is", "None", ":", "fields", "=", "arr", ".", "dtype",...
Stretch an array. Stretch an array by ``hstack()``-ing multiple array fields while preserving column names and record array structure. If a scalar field is specified, it will be stretched along with array fields. Parameters ---------- arr : NumPy structured or record array The array to be stretched. fields : list of strings or string, optional (default=None) A list of column names or a single column name to stretch. If ``fields`` is a string, then the output array is a one-dimensional unstructured array containing only the stretched elements of that field. If None, then stretch all fields. return_indices : bool, optional (default=False) If True, the array index of each stretched array entry will be returned in addition to the stretched array. This changes the return type of this function to a tuple consisting of a structured array and a numpy int64 array. Returns ------- ret : A NumPy structured array The stretched array. Examples -------- >>> import numpy as np >>> from root_numpy import stretch >>> arr = np.empty(2, dtype=[('scalar', np.int), ('array', 'O')]) >>> arr[0] = (0, np.array([1, 2, 3], dtype=np.float)) >>> arr[1] = (1, np.array([4, 5, 6], dtype=np.float)) >>> stretch(arr, ['scalar', 'array']) array([(0, 1.0), (0, 2.0), (0, 3.0), (1, 4.0), (1, 5.0), (1, 6.0)], dtype=[('scalar', '<i8'), ('array', '<f8')])
[ "Stretch", "an", "array", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_utils.py#L130-L226
train
30,975
scikit-hep/root_numpy
root_numpy/_utils.py
dup_idx
def dup_idx(arr): """Return the indices of all duplicated array elements. Parameters ---------- arr : array-like object An array-like object Returns ------- idx : NumPy array An array containing the indices of the duplicated elements Examples -------- >>> from root_numpy import dup_idx >>> dup_idx([1, 2, 3, 4, 5]) array([], dtype=int64) >>> dup_idx([1, 2, 3, 4, 5, 5]) array([4, 5]) >>> dup_idx([1, 2, 3, 4, 5, 5, 1]) array([0, 4, 5, 6]) """ _, b = np.unique(arr, return_inverse=True) return np.nonzero(np.logical_or.reduce( b[:, np.newaxis] == np.nonzero(np.bincount(b) > 1), axis=1))[0]
python
def dup_idx(arr): """Return the indices of all duplicated array elements. Parameters ---------- arr : array-like object An array-like object Returns ------- idx : NumPy array An array containing the indices of the duplicated elements Examples -------- >>> from root_numpy import dup_idx >>> dup_idx([1, 2, 3, 4, 5]) array([], dtype=int64) >>> dup_idx([1, 2, 3, 4, 5, 5]) array([4, 5]) >>> dup_idx([1, 2, 3, 4, 5, 5, 1]) array([0, 4, 5, 6]) """ _, b = np.unique(arr, return_inverse=True) return np.nonzero(np.logical_or.reduce( b[:, np.newaxis] == np.nonzero(np.bincount(b) > 1), axis=1))[0]
[ "def", "dup_idx", "(", "arr", ")", ":", "_", ",", "b", "=", "np", ".", "unique", "(", "arr", ",", "return_inverse", "=", "True", ")", "return", "np", ".", "nonzero", "(", "np", ".", "logical_or", ".", "reduce", "(", "b", "[", ":", ",", "np", "....
Return the indices of all duplicated array elements. Parameters ---------- arr : array-like object An array-like object Returns ------- idx : NumPy array An array containing the indices of the duplicated elements Examples -------- >>> from root_numpy import dup_idx >>> dup_idx([1, 2, 3, 4, 5]) array([], dtype=int64) >>> dup_idx([1, 2, 3, 4, 5, 5]) array([4, 5]) >>> dup_idx([1, 2, 3, 4, 5, 5, 1]) array([0, 4, 5, 6])
[ "Return", "the", "indices", "of", "all", "duplicated", "array", "elements", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_utils.py#L229-L256
train
30,976
scikit-hep/root_numpy
root_numpy/_utils.py
blockwise_inner_join
def blockwise_inner_join(data, left, foreign_key, right, force_repeat=None, foreign_key_name=None): """Perform a blockwise inner join. Perform a blockwise inner join from names specified in ``left`` to ``right`` via ``foreign_key``: left->foreign_key->right. Parameters ---------- data : array A structured NumPy array. left : array Array of left side column names. foreign_key : array or string NumPy array or string ``foreign_key`` column name. This column can be either an integer or an array of ints. If ``foreign_key`` is an array of int column, left column will be treated according to left column type: * Scalar columns or columns in ``force_repeat`` will be repeated * Array columns not in ``force_repeat`` will be assumed to the same length as ``foreign_key`` and will be stretched by index right : array Array of right side column names. These are array columns that each index ``foreign_key`` points to. These columns are assumed to have the same length. force_repeat : array, optional (default=None) Array of left column names that will be forced to stretch even if it's an array (useful when you want to emulate a multiple join). foreign_key_name : str, optional (default=None) The name of foreign key column in the output array. Examples -------- >>> import numpy as np >>> from root_numpy import blockwise_inner_join >>> test_data = np.array([ (1.0, np.array([11, 12, 13]), np.array([1, 0, 1]), 0, np.array([1, 2, 3])), (2.0, np.array([21, 22, 23]), np.array([-1, 2, -1]), 1, np.array([31, 32, 33]))], dtype=[('sl', np.float), ('al', 'O'), ('fk', 'O'), ('s_fk', np.int), ('ar', 'O')]) >>> blockwise_inner_join(test_data, ['sl', 'al'], test_data['fk'], ['ar']) array([(1.0, 11, 2, 1), (1.0, 12, 1, 0), (1.0, 13, 2, 1), (2.0, 22, 33, 2)], dtype=[('sl', '<f8'), ('al', '<i8'), ('ar', '<i8'), ('fk', '<i8')]) >>> blockwise_inner_join(test_data, ['sl', 'al'], test_data['fk'], ['ar'], force_repeat=['al']) array([(1.0, [11, 12, 13], 2, 1), (1.0, [11, 12, 13], 1, 0), (1.0, [11, 12, 13], 2, 1), (2.0, [21, 22, 23], 33, 2)], dtype=[('sl', '<f8'), ('al', '|O8'), ('ar', '<i8'), ('fk', '<i8')]) """ if isinstance(foreign_key, string_types): foreign_key = data[foreign_key] return _blockwise_inner_join(data, left, foreign_key, right, force_repeat, foreign_key_name)
python
def blockwise_inner_join(data, left, foreign_key, right, force_repeat=None, foreign_key_name=None): """Perform a blockwise inner join. Perform a blockwise inner join from names specified in ``left`` to ``right`` via ``foreign_key``: left->foreign_key->right. Parameters ---------- data : array A structured NumPy array. left : array Array of left side column names. foreign_key : array or string NumPy array or string ``foreign_key`` column name. This column can be either an integer or an array of ints. If ``foreign_key`` is an array of int column, left column will be treated according to left column type: * Scalar columns or columns in ``force_repeat`` will be repeated * Array columns not in ``force_repeat`` will be assumed to the same length as ``foreign_key`` and will be stretched by index right : array Array of right side column names. These are array columns that each index ``foreign_key`` points to. These columns are assumed to have the same length. force_repeat : array, optional (default=None) Array of left column names that will be forced to stretch even if it's an array (useful when you want to emulate a multiple join). foreign_key_name : str, optional (default=None) The name of foreign key column in the output array. Examples -------- >>> import numpy as np >>> from root_numpy import blockwise_inner_join >>> test_data = np.array([ (1.0, np.array([11, 12, 13]), np.array([1, 0, 1]), 0, np.array([1, 2, 3])), (2.0, np.array([21, 22, 23]), np.array([-1, 2, -1]), 1, np.array([31, 32, 33]))], dtype=[('sl', np.float), ('al', 'O'), ('fk', 'O'), ('s_fk', np.int), ('ar', 'O')]) >>> blockwise_inner_join(test_data, ['sl', 'al'], test_data['fk'], ['ar']) array([(1.0, 11, 2, 1), (1.0, 12, 1, 0), (1.0, 13, 2, 1), (2.0, 22, 33, 2)], dtype=[('sl', '<f8'), ('al', '<i8'), ('ar', '<i8'), ('fk', '<i8')]) >>> blockwise_inner_join(test_data, ['sl', 'al'], test_data['fk'], ['ar'], force_repeat=['al']) array([(1.0, [11, 12, 13], 2, 1), (1.0, [11, 12, 13], 1, 0), (1.0, [11, 12, 13], 2, 1), (2.0, [21, 22, 23], 33, 2)], dtype=[('sl', '<f8'), ('al', '|O8'), ('ar', '<i8'), ('fk', '<i8')]) """ if isinstance(foreign_key, string_types): foreign_key = data[foreign_key] return _blockwise_inner_join(data, left, foreign_key, right, force_repeat, foreign_key_name)
[ "def", "blockwise_inner_join", "(", "data", ",", "left", ",", "foreign_key", ",", "right", ",", "force_repeat", "=", "None", ",", "foreign_key_name", "=", "None", ")", ":", "if", "isinstance", "(", "foreign_key", ",", "string_types", ")", ":", "foreign_key", ...
Perform a blockwise inner join. Perform a blockwise inner join from names specified in ``left`` to ``right`` via ``foreign_key``: left->foreign_key->right. Parameters ---------- data : array A structured NumPy array. left : array Array of left side column names. foreign_key : array or string NumPy array or string ``foreign_key`` column name. This column can be either an integer or an array of ints. If ``foreign_key`` is an array of int column, left column will be treated according to left column type: * Scalar columns or columns in ``force_repeat`` will be repeated * Array columns not in ``force_repeat`` will be assumed to the same length as ``foreign_key`` and will be stretched by index right : array Array of right side column names. These are array columns that each index ``foreign_key`` points to. These columns are assumed to have the same length. force_repeat : array, optional (default=None) Array of left column names that will be forced to stretch even if it's an array (useful when you want to emulate a multiple join). foreign_key_name : str, optional (default=None) The name of foreign key column in the output array. Examples -------- >>> import numpy as np >>> from root_numpy import blockwise_inner_join >>> test_data = np.array([ (1.0, np.array([11, 12, 13]), np.array([1, 0, 1]), 0, np.array([1, 2, 3])), (2.0, np.array([21, 22, 23]), np.array([-1, 2, -1]), 1, np.array([31, 32, 33]))], dtype=[('sl', np.float), ('al', 'O'), ('fk', 'O'), ('s_fk', np.int), ('ar', 'O')]) >>> blockwise_inner_join(test_data, ['sl', 'al'], test_data['fk'], ['ar']) array([(1.0, 11, 2, 1), (1.0, 12, 1, 0), (1.0, 13, 2, 1), (2.0, 22, 33, 2)], dtype=[('sl', '<f8'), ('al', '<i8'), ('ar', '<i8'), ('fk', '<i8')]) >>> blockwise_inner_join(test_data, ['sl', 'al'], test_data['fk'], ['ar'], force_repeat=['al']) array([(1.0, [11, 12, 13], 2, 1), (1.0, [11, 12, 13], 1, 0), (1.0, [11, 12, 13], 2, 1), (2.0, [21, 22, 23], 33, 2)], dtype=[('sl', '<f8'), ('al', '|O8'), ('ar', '<i8'), ('fk', '<i8')])
[ "Perform", "a", "blockwise", "inner", "join", "." ]
3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8
https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_utils.py#L259-L314
train
30,977
PyMySQL/Tornado-MySQL
tornado_mysql/cursors.py
Cursor.executemany
def executemany(self, query, args): """Run several data against one query PyMySQL can execute bulkinsert for query like 'INSERT ... VALUES (%s)'. In other form of queries, just run :meth:`execute` many times. """ if not args: return m = RE_INSERT_VALUES.match(query) if m: q_prefix = m.group(1) q_values = m.group(2).rstrip() q_postfix = m.group(3) or '' assert q_values[0] == '(' and q_values[-1] == ')' yield self._do_execute_many(q_prefix, q_values, q_postfix, args, self.max_stmt_length, self._get_db().encoding) else: rows = 0 for arg in args: yield self.execute(query, arg) rows += self.rowcount self.rowcount = rows raise gen.Return(self.rowcount)
python
def executemany(self, query, args): """Run several data against one query PyMySQL can execute bulkinsert for query like 'INSERT ... VALUES (%s)'. In other form of queries, just run :meth:`execute` many times. """ if not args: return m = RE_INSERT_VALUES.match(query) if m: q_prefix = m.group(1) q_values = m.group(2).rstrip() q_postfix = m.group(3) or '' assert q_values[0] == '(' and q_values[-1] == ')' yield self._do_execute_many(q_prefix, q_values, q_postfix, args, self.max_stmt_length, self._get_db().encoding) else: rows = 0 for arg in args: yield self.execute(query, arg) rows += self.rowcount self.rowcount = rows raise gen.Return(self.rowcount)
[ "def", "executemany", "(", "self", ",", "query", ",", "args", ")", ":", "if", "not", "args", ":", "return", "m", "=", "RE_INSERT_VALUES", ".", "match", "(", "query", ")", "if", "m", ":", "q_prefix", "=", "m", ".", "group", "(", "1", ")", "q_values"...
Run several data against one query PyMySQL can execute bulkinsert for query like 'INSERT ... VALUES (%s)'. In other form of queries, just run :meth:`execute` many times.
[ "Run", "several", "data", "against", "one", "query" ]
75d3466e4332e43b2bf853799f1122dec5da60bc
https://github.com/PyMySQL/Tornado-MySQL/blob/75d3466e4332e43b2bf853799f1122dec5da60bc/tornado_mysql/cursors.py#L137-L161
train
30,978
PyMySQL/Tornado-MySQL
tornado_mysql/__init__.py
Binary
def Binary(x): """Return x as a binary type.""" if isinstance(x, text_type) and not (JYTHON or IRONPYTHON): return x.encode() return bytes(x)
python
def Binary(x): """Return x as a binary type.""" if isinstance(x, text_type) and not (JYTHON or IRONPYTHON): return x.encode() return bytes(x)
[ "def", "Binary", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "text_type", ")", "and", "not", "(", "JYTHON", "or", "IRONPYTHON", ")", ":", "return", "x", ".", "encode", "(", ")", "return", "bytes", "(", "x", ")" ]
Return x as a binary type.
[ "Return", "x", "as", "a", "binary", "type", "." ]
75d3466e4332e43b2bf853799f1122dec5da60bc
https://github.com/PyMySQL/Tornado-MySQL/blob/75d3466e4332e43b2bf853799f1122dec5da60bc/tornado_mysql/__init__.py#L77-L81
train
30,979
PyMySQL/Tornado-MySQL
tornado_mysql/converters.py
convert_mysql_timestamp
def convert_mysql_timestamp(timestamp): """Convert a MySQL TIMESTAMP to a Timestamp object. MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME: >>> mysql_timestamp_converter('2007-02-25 22:32:17') datetime.datetime(2007, 2, 25, 22, 32, 17) MySQL < 4.1 uses a big string of numbers: >>> mysql_timestamp_converter('20070225223217') datetime.datetime(2007, 2, 25, 22, 32, 17) Illegal values are returned as None: >>> mysql_timestamp_converter('2007-02-31 22:32:17') is None True >>> mysql_timestamp_converter('00000000000000') is None True """ if timestamp[4] == '-': return convert_datetime(timestamp) timestamp += "0"*(14-len(timestamp)) # padding year, month, day, hour, minute, second = \ int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), \ int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14]) try: return datetime.datetime(year, month, day, hour, minute, second) except ValueError: return None
python
def convert_mysql_timestamp(timestamp): """Convert a MySQL TIMESTAMP to a Timestamp object. MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME: >>> mysql_timestamp_converter('2007-02-25 22:32:17') datetime.datetime(2007, 2, 25, 22, 32, 17) MySQL < 4.1 uses a big string of numbers: >>> mysql_timestamp_converter('20070225223217') datetime.datetime(2007, 2, 25, 22, 32, 17) Illegal values are returned as None: >>> mysql_timestamp_converter('2007-02-31 22:32:17') is None True >>> mysql_timestamp_converter('00000000000000') is None True """ if timestamp[4] == '-': return convert_datetime(timestamp) timestamp += "0"*(14-len(timestamp)) # padding year, month, day, hour, minute, second = \ int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), \ int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14]) try: return datetime.datetime(year, month, day, hour, minute, second) except ValueError: return None
[ "def", "convert_mysql_timestamp", "(", "timestamp", ")", ":", "if", "timestamp", "[", "4", "]", "==", "'-'", ":", "return", "convert_datetime", "(", "timestamp", ")", "timestamp", "+=", "\"0\"", "*", "(", "14", "-", "len", "(", "timestamp", ")", ")", "# ...
Convert a MySQL TIMESTAMP to a Timestamp object. MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME: >>> mysql_timestamp_converter('2007-02-25 22:32:17') datetime.datetime(2007, 2, 25, 22, 32, 17) MySQL < 4.1 uses a big string of numbers: >>> mysql_timestamp_converter('20070225223217') datetime.datetime(2007, 2, 25, 22, 32, 17) Illegal values are returned as None: >>> mysql_timestamp_converter('2007-02-31 22:32:17') is None True >>> mysql_timestamp_converter('00000000000000') is None True
[ "Convert", "a", "MySQL", "TIMESTAMP", "to", "a", "Timestamp", "object", "." ]
75d3466e4332e43b2bf853799f1122dec5da60bc
https://github.com/PyMySQL/Tornado-MySQL/blob/75d3466e4332e43b2bf853799f1122dec5da60bc/tornado_mysql/converters.py#L222-L252
train
30,980
PyMySQL/Tornado-MySQL
tornado_mysql/connections.py
Connection.close
def close(self): """Close the socket without sending quit message.""" stream = self._stream if stream is None: return self._stream = None stream.close()
python
def close(self): """Close the socket without sending quit message.""" stream = self._stream if stream is None: return self._stream = None stream.close()
[ "def", "close", "(", "self", ")", ":", "stream", "=", "self", ".", "_stream", "if", "stream", "is", "None", ":", "return", "self", ".", "_stream", "=", "None", "stream", ".", "close", "(", ")" ]
Close the socket without sending quit message.
[ "Close", "the", "socket", "without", "sending", "quit", "message", "." ]
75d3466e4332e43b2bf853799f1122dec5da60bc
https://github.com/PyMySQL/Tornado-MySQL/blob/75d3466e4332e43b2bf853799f1122dec5da60bc/tornado_mysql/connections.py#L588-L594
train
30,981
PyMySQL/Tornado-MySQL
tornado_mysql/connections.py
Connection.close_async
def close_async(self): """Send the quit message and close the socket""" if self._stream is None or self._stream.closed(): self._stream = None return send_data = struct.pack('<i', 1) + int2byte(COMMAND.COM_QUIT) yield self._stream.write(send_data) self.close()
python
def close_async(self): """Send the quit message and close the socket""" if self._stream is None or self._stream.closed(): self._stream = None return send_data = struct.pack('<i', 1) + int2byte(COMMAND.COM_QUIT) yield self._stream.write(send_data) self.close()
[ "def", "close_async", "(", "self", ")", ":", "if", "self", ".", "_stream", "is", "None", "or", "self", ".", "_stream", ".", "closed", "(", ")", ":", "self", ".", "_stream", "=", "None", "return", "send_data", "=", "struct", ".", "pack", "(", "'<i'", ...
Send the quit message and close the socket
[ "Send", "the", "quit", "message", "and", "close", "the", "socket" ]
75d3466e4332e43b2bf853799f1122dec5da60bc
https://github.com/PyMySQL/Tornado-MySQL/blob/75d3466e4332e43b2bf853799f1122dec5da60bc/tornado_mysql/connections.py#L597-L604
train
30,982
PyMySQL/Tornado-MySQL
tornado_mysql/connections.py
Connection.select_db
def select_db(self, db): '''Set current db''' yield self._execute_command(COMMAND.COM_INIT_DB, db) yield self._read_ok_packet()
python
def select_db(self, db): '''Set current db''' yield self._execute_command(COMMAND.COM_INIT_DB, db) yield self._read_ok_packet()
[ "def", "select_db", "(", "self", ",", "db", ")", ":", "yield", "self", ".", "_execute_command", "(", "COMMAND", ".", "COM_INIT_DB", ",", "db", ")", "yield", "self", ".", "_read_ok_packet", "(", ")" ]
Set current db
[ "Set", "current", "db" ]
75d3466e4332e43b2bf853799f1122dec5da60bc
https://github.com/PyMySQL/Tornado-MySQL/blob/75d3466e4332e43b2bf853799f1122dec5da60bc/tornado_mysql/connections.py#L668-L671
train
30,983
PyMySQL/Tornado-MySQL
tornado_mysql/pools.py
Pool.execute
def execute(self, query, params=None, cursor=None): """Execute query in pool. Returns future yielding closed cursor. You can get rows, lastrowid, etc from the cursor. :param cursor: cursor class(Cursor, DictCursor. etc.) :return: Future of cursor :rtype: Future """ conn = yield self._get_conn() try: cur = conn.cursor(cursor) yield cur.execute(query, params) yield cur.close() except: self._close_conn(conn) raise else: self._put_conn(conn) raise Return(cur)
python
def execute(self, query, params=None, cursor=None): """Execute query in pool. Returns future yielding closed cursor. You can get rows, lastrowid, etc from the cursor. :param cursor: cursor class(Cursor, DictCursor. etc.) :return: Future of cursor :rtype: Future """ conn = yield self._get_conn() try: cur = conn.cursor(cursor) yield cur.execute(query, params) yield cur.close() except: self._close_conn(conn) raise else: self._put_conn(conn) raise Return(cur)
[ "def", "execute", "(", "self", ",", "query", ",", "params", "=", "None", ",", "cursor", "=", "None", ")", ":", "conn", "=", "yield", "self", ".", "_get_conn", "(", ")", "try", ":", "cur", "=", "conn", ".", "cursor", "(", "cursor", ")", "yield", "...
Execute query in pool. Returns future yielding closed cursor. You can get rows, lastrowid, etc from the cursor. :param cursor: cursor class(Cursor, DictCursor. etc.) :return: Future of cursor :rtype: Future
[ "Execute", "query", "in", "pool", "." ]
75d3466e4332e43b2bf853799f1122dec5da60bc
https://github.com/PyMySQL/Tornado-MySQL/blob/75d3466e4332e43b2bf853799f1122dec5da60bc/tornado_mysql/pools.py#L119-L139
train
30,984
makinacorpus/django-geojson
djgeojson/views.py
TiledGeoJSONLayerView.get_queryset
def get_queryset(self): """ Inspired by Glen Roberton's django-geojson-tiles view """ self.z, self.x, self.y = self._parse_args() nw = self.tile_coord(self.x, self.y, self.z) se = self.tile_coord(self.x + 1, self.y + 1, self.z) bbox = Polygon((nw, (se[0], nw[1]), se, (nw[0], se[1]), nw)) qs = super(TiledGeoJSONLayerView, self).get_queryset() qs = qs.filter(**{ '%s__intersects' % self.geometry_field: bbox }) self.bbox = bbox.extent # Simplification dict by zoom level simplifications = self.simplifications or {} z = self.z self.simplify = simplifications.get(z) while self.simplify is None and z < 32: z += 1 self.simplify = simplifications.get(z) # Won't trim point geometries to a boundary model_field = qs.model._meta.get_field(self.geometry_field) self.trim_to_boundary = (self.trim_to_boundary and not isinstance(model_field, PointField) and Intersection is not None) if self.trim_to_boundary: if django.VERSION < (1, 9): qs = qs.intersection(bbox) else: qs = qs.annotate(intersection=Intersection(self.geometry_field, bbox)) self.geometry_field = 'intersection' return qs
python
def get_queryset(self): """ Inspired by Glen Roberton's django-geojson-tiles view """ self.z, self.x, self.y = self._parse_args() nw = self.tile_coord(self.x, self.y, self.z) se = self.tile_coord(self.x + 1, self.y + 1, self.z) bbox = Polygon((nw, (se[0], nw[1]), se, (nw[0], se[1]), nw)) qs = super(TiledGeoJSONLayerView, self).get_queryset() qs = qs.filter(**{ '%s__intersects' % self.geometry_field: bbox }) self.bbox = bbox.extent # Simplification dict by zoom level simplifications = self.simplifications or {} z = self.z self.simplify = simplifications.get(z) while self.simplify is None and z < 32: z += 1 self.simplify = simplifications.get(z) # Won't trim point geometries to a boundary model_field = qs.model._meta.get_field(self.geometry_field) self.trim_to_boundary = (self.trim_to_boundary and not isinstance(model_field, PointField) and Intersection is not None) if self.trim_to_boundary: if django.VERSION < (1, 9): qs = qs.intersection(bbox) else: qs = qs.annotate(intersection=Intersection(self.geometry_field, bbox)) self.geometry_field = 'intersection' return qs
[ "def", "get_queryset", "(", "self", ")", ":", "self", ".", "z", ",", "self", ".", "x", ",", "self", ".", "y", "=", "self", ".", "_parse_args", "(", ")", "nw", "=", "self", ".", "tile_coord", "(", "self", ".", "x", ",", "self", ".", "y", ",", ...
Inspired by Glen Roberton's django-geojson-tiles view
[ "Inspired", "by", "Glen", "Roberton", "s", "django", "-", "geojson", "-", "tiles", "view" ]
42fa800eea6502c1271c0cfa73c03c2bd499b536
https://github.com/makinacorpus/django-geojson/blob/42fa800eea6502c1271c0cfa73c03c2bd499b536/djgeojson/views.py#L127-L162
train
30,985
makinacorpus/django-geojson
djgeojson/serializers.py
json_encoder_with_precision
def json_encoder_with_precision(precision, JSONEncoderClass): """ Context manager to set float precision during json encoding """ needs_class_hack = not hasattr(json.encoder, 'FLOAT_REPR') try: if precision is not None: def float_repr(o): return format(o, '.%sf' % precision) if not needs_class_hack: # python is not 3.5 original_float_repr = json.encoder.FLOAT_REPR json.encoder.FLOAT_REPR = float_repr else: # HACK to allow usage of float precision in python 3.5 # Needed because python 3.5 removes the global FLOAT_REPR hack class JSONEncoderClass(JSONEncoderClass): FLOAT_REPR = float.__repr__ # Follows code copied from cPython Lib/json/encoder.py # The only change is that in floatstr _repr=float.__repr__ is replaced def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = json.encoder.encode_basestring_ascii else: _encoder = json.encoder.encode_basestring def floatstr(o, allow_nan=self.allow_nan, _repr=float_repr, _inf=json.encoder.INFINITY, _neginf=-json.encoder.INFINITY): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on the # internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError( "Out of range float values are not JSON compliant: " + repr(o)) return text if (_one_shot and json.encoder.c_make_encoder is not None and self.indent is None): _iterencode = json.encoder.c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan) else: _iterencode = json.encoder._make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0) yield JSONEncoderClass finally: if precision is not None: if not needs_class_hack: # restore FLOAT_REPR json.encoder.FLOAT_REPR = original_float_repr
python
def json_encoder_with_precision(precision, JSONEncoderClass): """ Context manager to set float precision during json encoding """ needs_class_hack = not hasattr(json.encoder, 'FLOAT_REPR') try: if precision is not None: def float_repr(o): return format(o, '.%sf' % precision) if not needs_class_hack: # python is not 3.5 original_float_repr = json.encoder.FLOAT_REPR json.encoder.FLOAT_REPR = float_repr else: # HACK to allow usage of float precision in python 3.5 # Needed because python 3.5 removes the global FLOAT_REPR hack class JSONEncoderClass(JSONEncoderClass): FLOAT_REPR = float.__repr__ # Follows code copied from cPython Lib/json/encoder.py # The only change is that in floatstr _repr=float.__repr__ is replaced def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = json.encoder.encode_basestring_ascii else: _encoder = json.encoder.encode_basestring def floatstr(o, allow_nan=self.allow_nan, _repr=float_repr, _inf=json.encoder.INFINITY, _neginf=-json.encoder.INFINITY): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on the # internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError( "Out of range float values are not JSON compliant: " + repr(o)) return text if (_one_shot and json.encoder.c_make_encoder is not None and self.indent is None): _iterencode = json.encoder.c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan) else: _iterencode = json.encoder._make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0) yield JSONEncoderClass finally: if precision is not None: if not needs_class_hack: # restore FLOAT_REPR json.encoder.FLOAT_REPR = original_float_repr
[ "def", "json_encoder_with_precision", "(", "precision", ",", "JSONEncoderClass", ")", ":", "needs_class_hack", "=", "not", "hasattr", "(", "json", ".", "encoder", ",", "'FLOAT_REPR'", ")", "try", ":", "if", "precision", "is", "not", "None", ":", "def", "float_...
Context manager to set float precision during json encoding
[ "Context", "manager", "to", "set", "float", "precision", "during", "json", "encoding" ]
42fa800eea6502c1271c0cfa73c03c2bd499b536
https://github.com/makinacorpus/django-geojson/blob/42fa800eea6502c1271c0cfa73c03c2bd499b536/djgeojson/serializers.py#L77-L156
train
30,986
chaoss/grimoirelab-toolkit
grimoirelab_toolkit/datetime.py
datetime_to_utc
def datetime_to_utc(ts): """Convert a timestamp to UTC+0 timezone. Returns the given datetime object converted to a date with UTC+0 timezone. For naive datetimes, it will be assumed that they are in UTC+0. When the timezone is wrong, UTC+0 will be set as default (using `dateutil.tz.tzutc` object). :param dt: timestamp to convert :returns: a datetime object :raises InvalidDateError: when the given parameter is not an instance of datetime """ if not isinstance(ts, datetime.datetime): msg = '<%s> object' % type(ts) raise InvalidDateError(date=msg) if not ts.tzinfo: ts = ts.replace(tzinfo=dateutil.tz.tzutc()) try: ts = ts.astimezone(dateutil.tz.tzutc()) except ValueError: logger.warning("Date %s str does not have a valid timezone", ts) logger.warning("Date converted to UTC removing timezone info") ts = ts.replace(tzinfo=dateutil.tz.tzutc()).astimezone(dateutil.tz.tzutc()) return ts
python
def datetime_to_utc(ts): """Convert a timestamp to UTC+0 timezone. Returns the given datetime object converted to a date with UTC+0 timezone. For naive datetimes, it will be assumed that they are in UTC+0. When the timezone is wrong, UTC+0 will be set as default (using `dateutil.tz.tzutc` object). :param dt: timestamp to convert :returns: a datetime object :raises InvalidDateError: when the given parameter is not an instance of datetime """ if not isinstance(ts, datetime.datetime): msg = '<%s> object' % type(ts) raise InvalidDateError(date=msg) if not ts.tzinfo: ts = ts.replace(tzinfo=dateutil.tz.tzutc()) try: ts = ts.astimezone(dateutil.tz.tzutc()) except ValueError: logger.warning("Date %s str does not have a valid timezone", ts) logger.warning("Date converted to UTC removing timezone info") ts = ts.replace(tzinfo=dateutil.tz.tzutc()).astimezone(dateutil.tz.tzutc()) return ts
[ "def", "datetime_to_utc", "(", "ts", ")", ":", "if", "not", "isinstance", "(", "ts", ",", "datetime", ".", "datetime", ")", ":", "msg", "=", "'<%s> object'", "%", "type", "(", "ts", ")", "raise", "InvalidDateError", "(", "date", "=", "msg", ")", "if", ...
Convert a timestamp to UTC+0 timezone. Returns the given datetime object converted to a date with UTC+0 timezone. For naive datetimes, it will be assumed that they are in UTC+0. When the timezone is wrong, UTC+0 will be set as default (using `dateutil.tz.tzutc` object). :param dt: timestamp to convert :returns: a datetime object :raises InvalidDateError: when the given parameter is not an instance of datetime
[ "Convert", "a", "timestamp", "to", "UTC", "+", "0", "timezone", "." ]
30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b
https://github.com/chaoss/grimoirelab-toolkit/blob/30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b/grimoirelab_toolkit/datetime.py#L65-L94
train
30,987
chaoss/grimoirelab-toolkit
grimoirelab_toolkit/datetime.py
unixtime_to_datetime
def unixtime_to_datetime(ut): """Convert a unixtime timestamp to a datetime object. The function converts a timestamp in Unix format to a datetime object. UTC timezone will also be set. :param ut: Unix timestamp to convert :returns: a datetime object :raises InvalidDateError: when the given timestamp cannot be converted into a valid date """ try: dt = datetime.datetime.utcfromtimestamp(ut) dt = dt.replace(tzinfo=dateutil.tz.tzutc()) return dt except Exception: raise InvalidDateError(date=str(ut))
python
def unixtime_to_datetime(ut): """Convert a unixtime timestamp to a datetime object. The function converts a timestamp in Unix format to a datetime object. UTC timezone will also be set. :param ut: Unix timestamp to convert :returns: a datetime object :raises InvalidDateError: when the given timestamp cannot be converted into a valid date """ try: dt = datetime.datetime.utcfromtimestamp(ut) dt = dt.replace(tzinfo=dateutil.tz.tzutc()) return dt except Exception: raise InvalidDateError(date=str(ut))
[ "def", "unixtime_to_datetime", "(", "ut", ")", ":", "try", ":", "dt", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "ut", ")", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "dateutil", ".", "tz", ".", "tzutc", "(", ")", ")", ...
Convert a unixtime timestamp to a datetime object. The function converts a timestamp in Unix format to a datetime object. UTC timezone will also be set. :param ut: Unix timestamp to convert :returns: a datetime object :raises InvalidDateError: when the given timestamp cannot be converted into a valid date
[ "Convert", "a", "unixtime", "timestamp", "to", "a", "datetime", "object", "." ]
30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b
https://github.com/chaoss/grimoirelab-toolkit/blob/30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b/grimoirelab_toolkit/datetime.py#L151-L169
train
30,988
chaoss/grimoirelab-toolkit
grimoirelab_toolkit/introspect.py
inspect_signature_parameters
def inspect_signature_parameters(callable_, excluded=None): """Get the parameters of a callable. Returns a list with the signature parameters of `callable_`. Parameters contained in `excluded` tuple will not be included in the result. :param callable_: callable object :param excluded: tuple with default parameters to exclude :result: list of parameters """ if not excluded: excluded = () signature = inspect.signature(callable_) params = [ v for p, v in signature.parameters.items() if p not in excluded ] return params
python
def inspect_signature_parameters(callable_, excluded=None): """Get the parameters of a callable. Returns a list with the signature parameters of `callable_`. Parameters contained in `excluded` tuple will not be included in the result. :param callable_: callable object :param excluded: tuple with default parameters to exclude :result: list of parameters """ if not excluded: excluded = () signature = inspect.signature(callable_) params = [ v for p, v in signature.parameters.items() if p not in excluded ] return params
[ "def", "inspect_signature_parameters", "(", "callable_", ",", "excluded", "=", "None", ")", ":", "if", "not", "excluded", ":", "excluded", "=", "(", ")", "signature", "=", "inspect", ".", "signature", "(", "callable_", ")", "params", "=", "[", "v", "for", ...
Get the parameters of a callable. Returns a list with the signature parameters of `callable_`. Parameters contained in `excluded` tuple will not be included in the result. :param callable_: callable object :param excluded: tuple with default parameters to exclude :result: list of parameters
[ "Get", "the", "parameters", "of", "a", "callable", "." ]
30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b
https://github.com/chaoss/grimoirelab-toolkit/blob/30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b/grimoirelab_toolkit/introspect.py#L39-L59
train
30,989
chaoss/grimoirelab-toolkit
grimoirelab_toolkit/introspect.py
find_signature_parameters
def find_signature_parameters(callable_, candidates, excluded=('self', 'cls')): """Find on a set of candidates the parameters needed to execute a callable. Returns a dictionary with the `candidates` found on `callable_`. When any of the required parameters of a callable is not found, it raises a `AttributeError` exception. A signature parameter whitout a default value is considered as required. :param callable_: callable object :param candidates: dict with the possible parameters to use with the callable :param excluded: tuple with default parameters to exclude :result: dict of parameters ready to use with the callable :raises AttributeError: when any of the required parameters for executing a callable is not found in `candidates` """ signature_params = inspect_signature_parameters(callable_, excluded=excluded) exec_params = {} add_all = False for param in signature_params: name = param.name if str(param).startswith('*'): add_all = True elif name in candidates: exec_params[name] = candidates[name] elif param.default == inspect.Parameter.empty: msg = "required argument %s not found" % name raise AttributeError(msg, name) else: continue if add_all: exec_params = candidates return exec_params
python
def find_signature_parameters(callable_, candidates, excluded=('self', 'cls')): """Find on a set of candidates the parameters needed to execute a callable. Returns a dictionary with the `candidates` found on `callable_`. When any of the required parameters of a callable is not found, it raises a `AttributeError` exception. A signature parameter whitout a default value is considered as required. :param callable_: callable object :param candidates: dict with the possible parameters to use with the callable :param excluded: tuple with default parameters to exclude :result: dict of parameters ready to use with the callable :raises AttributeError: when any of the required parameters for executing a callable is not found in `candidates` """ signature_params = inspect_signature_parameters(callable_, excluded=excluded) exec_params = {} add_all = False for param in signature_params: name = param.name if str(param).startswith('*'): add_all = True elif name in candidates: exec_params[name] = candidates[name] elif param.default == inspect.Parameter.empty: msg = "required argument %s not found" % name raise AttributeError(msg, name) else: continue if add_all: exec_params = candidates return exec_params
[ "def", "find_signature_parameters", "(", "callable_", ",", "candidates", ",", "excluded", "=", "(", "'self'", ",", "'cls'", ")", ")", ":", "signature_params", "=", "inspect_signature_parameters", "(", "callable_", ",", "excluded", "=", "excluded", ")", "exec_param...
Find on a set of candidates the parameters needed to execute a callable. Returns a dictionary with the `candidates` found on `callable_`. When any of the required parameters of a callable is not found, it raises a `AttributeError` exception. A signature parameter whitout a default value is considered as required. :param callable_: callable object :param candidates: dict with the possible parameters to use with the callable :param excluded: tuple with default parameters to exclude :result: dict of parameters ready to use with the callable :raises AttributeError: when any of the required parameters for executing a callable is not found in `candidates`
[ "Find", "on", "a", "set", "of", "candidates", "the", "parameters", "needed", "to", "execute", "a", "callable", "." ]
30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b
https://github.com/chaoss/grimoirelab-toolkit/blob/30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b/grimoirelab_toolkit/introspect.py#L62-L102
train
30,990
chaoss/grimoirelab-toolkit
grimoirelab_toolkit/introspect.py
find_class_properties
def find_class_properties(cls): """Find property members in a class. Returns all the property members of a class in a list of (name, value) pairs. Only those members defined with `property` decorator will be included in the list. :param cls: class where property members will be searched :returns: list of properties """ candidates = inspect.getmembers(cls, inspect.isdatadescriptor) result = [ (name, value) for name, value in candidates if isinstance(value, property) ] return result
python
def find_class_properties(cls): """Find property members in a class. Returns all the property members of a class in a list of (name, value) pairs. Only those members defined with `property` decorator will be included in the list. :param cls: class where property members will be searched :returns: list of properties """ candidates = inspect.getmembers(cls, inspect.isdatadescriptor) result = [ (name, value) for name, value in candidates if isinstance(value, property) ] return result
[ "def", "find_class_properties", "(", "cls", ")", ":", "candidates", "=", "inspect", ".", "getmembers", "(", "cls", ",", "inspect", ".", "isdatadescriptor", ")", "result", "=", "[", "(", "name", ",", "value", ")", "for", "name", ",", "value", "in", "candi...
Find property members in a class. Returns all the property members of a class in a list of (name, value) pairs. Only those members defined with `property` decorator will be included in the list. :param cls: class where property members will be searched :returns: list of properties
[ "Find", "property", "members", "in", "a", "class", "." ]
30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b
https://github.com/chaoss/grimoirelab-toolkit/blob/30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b/grimoirelab_toolkit/introspect.py#L105-L121
train
30,991
Feneric/doxypypy
doxypypy/doxypypy.py
coroutine
def coroutine(func): """Basic decorator to implement the coroutine pattern.""" def __start(*args, **kwargs): """Automatically calls next() on the internal generator function.""" __cr = func(*args, **kwargs) next(__cr) return __cr return __start
python
def coroutine(func): """Basic decorator to implement the coroutine pattern.""" def __start(*args, **kwargs): """Automatically calls next() on the internal generator function.""" __cr = func(*args, **kwargs) next(__cr) return __cr return __start
[ "def", "coroutine", "(", "func", ")", ":", "def", "__start", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Automatically calls next() on the internal generator function.\"\"\"", "__cr", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")",...
Basic decorator to implement the coroutine pattern.
[ "Basic", "decorator", "to", "implement", "the", "coroutine", "pattern", "." ]
a8555b15fa2a758ea8392372de31c0f635cc0d93
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L25-L32
train
30,992
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._endCodeIfNeeded
def _endCodeIfNeeded(line, inCodeBlock): """Simple routine to append end code marker if needed.""" assert isinstance(line, str) if inCodeBlock: line = '# @endcode{0}{1}'.format(linesep, line.rstrip()) inCodeBlock = False return line, inCodeBlock
python
def _endCodeIfNeeded(line, inCodeBlock): """Simple routine to append end code marker if needed.""" assert isinstance(line, str) if inCodeBlock: line = '# @endcode{0}{1}'.format(linesep, line.rstrip()) inCodeBlock = False return line, inCodeBlock
[ "def", "_endCodeIfNeeded", "(", "line", ",", "inCodeBlock", ")", ":", "assert", "isinstance", "(", "line", ",", "str", ")", "if", "inCodeBlock", ":", "line", "=", "'# @endcode{0}{1}'", ".", "format", "(", "linesep", ",", "line", ".", "rstrip", "(", ")", ...
Simple routine to append end code marker if needed.
[ "Simple", "routine", "to", "append", "end", "code", "marker", "if", "needed", "." ]
a8555b15fa2a758ea8392372de31c0f635cc0d93
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L112-L118
train
30,993
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._checkIfCode
def _checkIfCode(self, inCodeBlockObj): """Checks whether or not a given line appears to be Python code.""" while True: line, lines, lineNum = (yield) testLineNum = 1 currentLineNum = 0 testLine = line.strip() lineOfCode = None while lineOfCode is None: match = AstWalker.__errorLineRE.match(testLine) if not testLine or testLine == '...' or match: # These are ambiguous. line, lines, lineNum = (yield) testLine = line.strip() #testLineNum = 1 elif testLine.startswith('>>>'): # This is definitely code. lineOfCode = True else: try: compLine = compile_command(testLine) if compLine and lines[currentLineNum].strip().startswith('#'): lineOfCode = True else: line, lines, lineNum = (yield) line = line.strip() if line.startswith('>>>'): # Definitely code, don't compile further. lineOfCode = True else: testLine += linesep + line testLine = testLine.strip() testLineNum += 1 except (SyntaxError, RuntimeError): # This is definitely not code. lineOfCode = False except Exception: # Other errors are ambiguous. line, lines, lineNum = (yield) testLine = line.strip() #testLineNum = 1 currentLineNum = lineNum - testLineNum if not inCodeBlockObj[0] and lineOfCode: inCodeBlockObj[0] = True lines[currentLineNum] = '{0}{1}# @code{1}'.format( lines[currentLineNum], linesep ) elif inCodeBlockObj[0] and lineOfCode is False: # None is ambiguous, so strict checking # against False is necessary. inCodeBlockObj[0] = False lines[currentLineNum] = '{0}{1}# @endcode{1}'.format( lines[currentLineNum], linesep )
python
def _checkIfCode(self, inCodeBlockObj): """Checks whether or not a given line appears to be Python code.""" while True: line, lines, lineNum = (yield) testLineNum = 1 currentLineNum = 0 testLine = line.strip() lineOfCode = None while lineOfCode is None: match = AstWalker.__errorLineRE.match(testLine) if not testLine or testLine == '...' or match: # These are ambiguous. line, lines, lineNum = (yield) testLine = line.strip() #testLineNum = 1 elif testLine.startswith('>>>'): # This is definitely code. lineOfCode = True else: try: compLine = compile_command(testLine) if compLine and lines[currentLineNum].strip().startswith('#'): lineOfCode = True else: line, lines, lineNum = (yield) line = line.strip() if line.startswith('>>>'): # Definitely code, don't compile further. lineOfCode = True else: testLine += linesep + line testLine = testLine.strip() testLineNum += 1 except (SyntaxError, RuntimeError): # This is definitely not code. lineOfCode = False except Exception: # Other errors are ambiguous. line, lines, lineNum = (yield) testLine = line.strip() #testLineNum = 1 currentLineNum = lineNum - testLineNum if not inCodeBlockObj[0] and lineOfCode: inCodeBlockObj[0] = True lines[currentLineNum] = '{0}{1}# @code{1}'.format( lines[currentLineNum], linesep ) elif inCodeBlockObj[0] and lineOfCode is False: # None is ambiguous, so strict checking # against False is necessary. inCodeBlockObj[0] = False lines[currentLineNum] = '{0}{1}# @endcode{1}'.format( lines[currentLineNum], linesep )
[ "def", "_checkIfCode", "(", "self", ",", "inCodeBlockObj", ")", ":", "while", "True", ":", "line", ",", "lines", ",", "lineNum", "=", "(", "yield", ")", "testLineNum", "=", "1", "currentLineNum", "=", "0", "testLine", "=", "line", ".", "strip", "(", ")...
Checks whether or not a given line appears to be Python code.
[ "Checks", "whether", "or", "not", "a", "given", "line", "appears", "to", "be", "Python", "code", "." ]
a8555b15fa2a758ea8392372de31c0f635cc0d93
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L121-L176
train
30,994
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.__writeDocstring
def __writeDocstring(self): """ Runs eternally, dumping out docstring line batches as they get fed in. Replaces original batches of docstring lines with modified versions fed in via send. """ while True: firstLineNum, lastLineNum, lines = (yield) newDocstringLen = lastLineNum - firstLineNum + 1 while len(lines) < newDocstringLen: lines.append('') # Substitute the new block of lines for the original block of lines. self.docLines[firstLineNum: lastLineNum + 1] = lines
python
def __writeDocstring(self): """ Runs eternally, dumping out docstring line batches as they get fed in. Replaces original batches of docstring lines with modified versions fed in via send. """ while True: firstLineNum, lastLineNum, lines = (yield) newDocstringLen = lastLineNum - firstLineNum + 1 while len(lines) < newDocstringLen: lines.append('') # Substitute the new block of lines for the original block of lines. self.docLines[firstLineNum: lastLineNum + 1] = lines
[ "def", "__writeDocstring", "(", "self", ")", ":", "while", "True", ":", "firstLineNum", ",", "lastLineNum", ",", "lines", "=", "(", "yield", ")", "newDocstringLen", "=", "lastLineNum", "-", "firstLineNum", "+", "1", "while", "len", "(", "lines", ")", "<", ...
Runs eternally, dumping out docstring line batches as they get fed in. Replaces original batches of docstring lines with modified versions fed in via send.
[ "Runs", "eternally", "dumping", "out", "docstring", "line", "batches", "as", "they", "get", "fed", "in", "." ]
a8555b15fa2a758ea8392372de31c0f635cc0d93
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L371-L384
train
30,995
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._checkMemberName
def _checkMemberName(name): """ See if a member name indicates that it should be private. Private variables in Python (starting with a double underscore but not ending in a double underscore) and bed lumps (variables that are not really private but are by common convention treated as protected because they begin with a single underscore) get Doxygen tags labeling them appropriately. """ assert isinstance(name, str) restrictionLevel = None if not name.endswith('__'): if name.startswith('__'): restrictionLevel = 'private' elif name.startswith('_'): restrictionLevel = 'protected' return restrictionLevel
python
def _checkMemberName(name): """ See if a member name indicates that it should be private. Private variables in Python (starting with a double underscore but not ending in a double underscore) and bed lumps (variables that are not really private but are by common convention treated as protected because they begin with a single underscore) get Doxygen tags labeling them appropriately. """ assert isinstance(name, str) restrictionLevel = None if not name.endswith('__'): if name.startswith('__'): restrictionLevel = 'private' elif name.startswith('_'): restrictionLevel = 'protected' return restrictionLevel
[ "def", "_checkMemberName", "(", "name", ")", ":", "assert", "isinstance", "(", "name", ",", "str", ")", "restrictionLevel", "=", "None", "if", "not", "name", ".", "endswith", "(", "'__'", ")", ":", "if", "name", ".", "startswith", "(", "'__'", ")", ":"...
See if a member name indicates that it should be private. Private variables in Python (starting with a double underscore but not ending in a double underscore) and bed lumps (variables that are not really private but are by common convention treated as protected because they begin with a single underscore) get Doxygen tags labeling them appropriately.
[ "See", "if", "a", "member", "name", "indicates", "that", "it", "should", "be", "private", "." ]
a8555b15fa2a758ea8392372de31c0f635cc0d93
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L518-L535
train
30,996
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._processMembers
def _processMembers(self, node, contextTag): """ Mark up members if they should be private. If the name indicates it should be private or protected, apply the appropriate Doxygen tags. """ restrictionLevel = self._checkMemberName(node.name) if restrictionLevel: workTag = '{0}{1}# @{2}'.format(contextTag, linesep, restrictionLevel) else: workTag = contextTag return workTag
python
def _processMembers(self, node, contextTag): """ Mark up members if they should be private. If the name indicates it should be private or protected, apply the appropriate Doxygen tags. """ restrictionLevel = self._checkMemberName(node.name) if restrictionLevel: workTag = '{0}{1}# @{2}'.format(contextTag, linesep, restrictionLevel) else: workTag = contextTag return workTag
[ "def", "_processMembers", "(", "self", ",", "node", ",", "contextTag", ")", ":", "restrictionLevel", "=", "self", ".", "_checkMemberName", "(", "node", ".", "name", ")", "if", "restrictionLevel", ":", "workTag", "=", "'{0}{1}# @{2}'", ".", "format", "(", "co...
Mark up members if they should be private. If the name indicates it should be private or protected, apply the appropriate Doxygen tags.
[ "Mark", "up", "members", "if", "they", "should", "be", "private", "." ]
a8555b15fa2a758ea8392372de31c0f635cc0d93
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L537-L551
train
30,997
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.visit
def visit(self, node, **kwargs): """ Visit a node and extract useful information from it. This is virtually identical to the standard version contained in NodeVisitor. It is only overridden because we're tracking extra information (the hierarchy of containing nodes) not preserved in the original. """ containingNodes = kwargs.get('containingNodes', []) method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node, containingNodes=containingNodes)
python
def visit(self, node, **kwargs): """ Visit a node and extract useful information from it. This is virtually identical to the standard version contained in NodeVisitor. It is only overridden because we're tracking extra information (the hierarchy of containing nodes) not preserved in the original. """ containingNodes = kwargs.get('containingNodes', []) method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node, containingNodes=containingNodes)
[ "def", "visit", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "containingNodes", "=", "kwargs", ".", "get", "(", "'containingNodes'", ",", "[", "]", ")", "method", "=", "'visit_'", "+", "node", ".", "__class__", ".", "__name__", "visitor...
Visit a node and extract useful information from it. This is virtually identical to the standard version contained in NodeVisitor. It is only overridden because we're tracking extra information (the hierarchy of containing nodes) not preserved in the original.
[ "Visit", "a", "node", "and", "extract", "useful", "information", "from", "it", "." ]
a8555b15fa2a758ea8392372de31c0f635cc0d93
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L570-L582
train
30,998
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._getFullPathName
def _getFullPathName(self, containingNodes): """ Returns the full node hierarchy rooted at module name. The list representing the full path through containing nodes (starting with the module itself) is returned. """ assert isinstance(containingNodes, list) return [(self.options.fullPathNamespace, 'module')] + containingNodes
python
def _getFullPathName(self, containingNodes): """ Returns the full node hierarchy rooted at module name. The list representing the full path through containing nodes (starting with the module itself) is returned. """ assert isinstance(containingNodes, list) return [(self.options.fullPathNamespace, 'module')] + containingNodes
[ "def", "_getFullPathName", "(", "self", ",", "containingNodes", ")", ":", "assert", "isinstance", "(", "containingNodes", ",", "list", ")", "return", "[", "(", "self", ".", "options", ".", "fullPathNamespace", ",", "'module'", ")", "]", "+", "containingNodes" ...
Returns the full node hierarchy rooted at module name. The list representing the full path through containing nodes (starting with the module itself) is returned.
[ "Returns", "the", "full", "node", "hierarchy", "rooted", "at", "module", "name", "." ]
a8555b15fa2a758ea8392372de31c0f635cc0d93
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L584-L592
train
30,999