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
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
what-studio/profiling | profiling/viewer.py | StatisticsWidget.get_mark | def get_mark(self):
"""Gets an expanded, collapsed, or leaf icon."""
if self.is_leaf:
char = self.icon_chars[2]
else:
char = self.icon_chars[int(self.expanded)]
return urwid.SelectableIcon(('mark', char), 0) | python | def get_mark(self):
"""Gets an expanded, collapsed, or leaf icon."""
if self.is_leaf:
char = self.icon_chars[2]
else:
char = self.icon_chars[int(self.expanded)]
return urwid.SelectableIcon(('mark', char), 0) | [
"def",
"get_mark",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_leaf",
":",
"char",
"=",
"self",
".",
"icon_chars",
"[",
"2",
"]",
"else",
":",
"char",
"=",
"self",
".",
"icon_chars",
"[",
"int",
"(",
"self",
".",
"expanded",
")",
"]",
"return",
"urwid",
".",
"SelectableIcon",
"(",
"(",
"'mark'",
",",
"char",
")",
",",
"0",
")"
] | Gets an expanded, collapsed, or leaf icon. | [
"Gets",
"an",
"expanded",
"collapsed",
"or",
"leaf",
"icon",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/viewer.py#L271-L277 | train |
what-studio/profiling | profiling/viewer.py | StatisticsTable.get_path | def get_path(self):
"""Gets the path to the focused statistics. Each step is a hash of
statistics object.
"""
path = deque()
__, node = self.get_focus()
while not node.is_root():
stats = node.get_value()
path.appendleft(hash(stats))
node = node.get_parent()
return path | python | def get_path(self):
"""Gets the path to the focused statistics. Each step is a hash of
statistics object.
"""
path = deque()
__, node = self.get_focus()
while not node.is_root():
stats = node.get_value()
path.appendleft(hash(stats))
node = node.get_parent()
return path | [
"def",
"get_path",
"(",
"self",
")",
":",
"path",
"=",
"deque",
"(",
")",
"__",
",",
"node",
"=",
"self",
".",
"get_focus",
"(",
")",
"while",
"not",
"node",
".",
"is_root",
"(",
")",
":",
"stats",
"=",
"node",
".",
"get_value",
"(",
")",
"path",
".",
"appendleft",
"(",
"hash",
"(",
"stats",
")",
")",
"node",
"=",
"node",
".",
"get_parent",
"(",
")",
"return",
"path"
] | Gets the path to the focused statistics. Each step is a hash of
statistics object. | [
"Gets",
"the",
"path",
"to",
"the",
"focused",
"statistics",
".",
"Each",
"step",
"is",
"a",
"hash",
"of",
"statistics",
"object",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/viewer.py#L551-L561 | train |
what-studio/profiling | profiling/viewer.py | StatisticsTable.find_node | def find_node(self, node, path):
"""Finds a node by the given path from the given node."""
for hash_value in path:
if isinstance(node, LeafStatisticsNode):
break
for stats in node.get_child_keys():
if hash(stats) == hash_value:
node = node.get_child_node(stats)
break
else:
break
return node | python | def find_node(self, node, path):
"""Finds a node by the given path from the given node."""
for hash_value in path:
if isinstance(node, LeafStatisticsNode):
break
for stats in node.get_child_keys():
if hash(stats) == hash_value:
node = node.get_child_node(stats)
break
else:
break
return node | [
"def",
"find_node",
"(",
"self",
",",
"node",
",",
"path",
")",
":",
"for",
"hash_value",
"in",
"path",
":",
"if",
"isinstance",
"(",
"node",
",",
"LeafStatisticsNode",
")",
":",
"break",
"for",
"stats",
"in",
"node",
".",
"get_child_keys",
"(",
")",
":",
"if",
"hash",
"(",
"stats",
")",
"==",
"hash_value",
":",
"node",
"=",
"node",
".",
"get_child_node",
"(",
"stats",
")",
"break",
"else",
":",
"break",
"return",
"node"
] | Finds a node by the given path from the given node. | [
"Finds",
"a",
"node",
"by",
"the",
"given",
"path",
"from",
"the",
"given",
"node",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/viewer.py#L563-L574 | train |
what-studio/profiling | profiling/viewer.py | StatisticsViewer.update_result | def update_result(self):
"""Updates the result on the table."""
try:
if self.paused:
result = self._paused_result
else:
result = self._final_result
except AttributeError:
self.table.update_frame()
return
stats, cpu_time, wall_time, title, at = result
self.table.set_result(stats, cpu_time, wall_time, title, at) | python | def update_result(self):
"""Updates the result on the table."""
try:
if self.paused:
result = self._paused_result
else:
result = self._final_result
except AttributeError:
self.table.update_frame()
return
stats, cpu_time, wall_time, title, at = result
self.table.set_result(stats, cpu_time, wall_time, title, at) | [
"def",
"update_result",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"paused",
":",
"result",
"=",
"self",
".",
"_paused_result",
"else",
":",
"result",
"=",
"self",
".",
"_final_result",
"except",
"AttributeError",
":",
"self",
".",
"table",
".",
"update_frame",
"(",
")",
"return",
"stats",
",",
"cpu_time",
",",
"wall_time",
",",
"title",
",",
"at",
"=",
"result",
"self",
".",
"table",
".",
"set_result",
"(",
"stats",
",",
"cpu_time",
",",
"wall_time",
",",
"title",
",",
"at",
")"
] | Updates the result on the table. | [
"Updates",
"the",
"result",
"on",
"the",
"table",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/viewer.py#L812-L823 | train |
what-studio/profiling | profiling/__main__.py | option_getter | def option_getter(type):
"""Gets an unbound method to get a configuration option as the given type.
"""
option_getters = {None: ConfigParser.get,
int: ConfigParser.getint,
float: ConfigParser.getfloat,
bool: ConfigParser.getboolean}
return option_getters.get(type, option_getters[None]) | python | def option_getter(type):
"""Gets an unbound method to get a configuration option as the given type.
"""
option_getters = {None: ConfigParser.get,
int: ConfigParser.getint,
float: ConfigParser.getfloat,
bool: ConfigParser.getboolean}
return option_getters.get(type, option_getters[None]) | [
"def",
"option_getter",
"(",
"type",
")",
":",
"option_getters",
"=",
"{",
"None",
":",
"ConfigParser",
".",
"get",
",",
"int",
":",
"ConfigParser",
".",
"getint",
",",
"float",
":",
"ConfigParser",
".",
"getfloat",
",",
"bool",
":",
"ConfigParser",
".",
"getboolean",
"}",
"return",
"option_getters",
".",
"get",
"(",
"type",
",",
"option_getters",
"[",
"None",
"]",
")"
] | Gets an unbound method to get a configuration option as the given type. | [
"Gets",
"an",
"unbound",
"method",
"to",
"get",
"a",
"configuration",
"option",
"as",
"the",
"given",
"type",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L116-L123 | train |
what-studio/profiling | profiling/__main__.py | config_default | def config_default(option, default=None, type=None, section=cli.name):
"""Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale'))
"""
def f(option=option, default=default, type=type, section=section):
config = read_config()
if type is None and default is not None:
# detect type from default.
type = builtins.type(default)
get_option = option_getter(type)
try:
return get_option(config, section, option)
except (NoOptionError, NoSectionError):
return default
return f | python | def config_default(option, default=None, type=None, section=cli.name):
"""Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale'))
"""
def f(option=option, default=default, type=type, section=section):
config = read_config()
if type is None and default is not None:
# detect type from default.
type = builtins.type(default)
get_option = option_getter(type)
try:
return get_option(config, section, option)
except (NoOptionError, NoSectionError):
return default
return f | [
"def",
"config_default",
"(",
"option",
",",
"default",
"=",
"None",
",",
"type",
"=",
"None",
",",
"section",
"=",
"cli",
".",
"name",
")",
":",
"def",
"f",
"(",
"option",
"=",
"option",
",",
"default",
"=",
"default",
",",
"type",
"=",
"type",
",",
"section",
"=",
"section",
")",
":",
"config",
"=",
"read_config",
"(",
")",
"if",
"type",
"is",
"None",
"and",
"default",
"is",
"not",
"None",
":",
"# detect type from default.",
"type",
"=",
"builtins",
".",
"type",
"(",
"default",
")",
"get_option",
"=",
"option_getter",
"(",
"type",
")",
"try",
":",
"return",
"get_option",
"(",
"config",
",",
"section",
",",
"option",
")",
"except",
"(",
"NoOptionError",
",",
"NoSectionError",
")",
":",
"return",
"default",
"return",
"f"
] | Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale')) | [
"Guesses",
"a",
"default",
"value",
"of",
"a",
"CLI",
"option",
"from",
"the",
"configuration",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L126-L144 | train |
what-studio/profiling | profiling/__main__.py | config_flag | def config_flag(option, value, default=False, section=cli.name):
"""Guesses whether a CLI flag should be turned on or off from the
configuration. If the configuration option value is same with the given
value, it returns ``True``.
::
@click.option('--ko-kr', 'locale', is_flag=True,
default=config_flag('locale', 'ko_KR'))
"""
class x(object):
def __bool__(self, option=option, value=value,
default=default, section=section):
config = read_config()
type = builtins.type(value)
get_option = option_getter(type)
try:
return get_option(config, section, option) == value
except (NoOptionError, NoSectionError):
return default
__nonzero__ = __bool__
return x() | python | def config_flag(option, value, default=False, section=cli.name):
"""Guesses whether a CLI flag should be turned on or off from the
configuration. If the configuration option value is same with the given
value, it returns ``True``.
::
@click.option('--ko-kr', 'locale', is_flag=True,
default=config_flag('locale', 'ko_KR'))
"""
class x(object):
def __bool__(self, option=option, value=value,
default=default, section=section):
config = read_config()
type = builtins.type(value)
get_option = option_getter(type)
try:
return get_option(config, section, option) == value
except (NoOptionError, NoSectionError):
return default
__nonzero__ = __bool__
return x() | [
"def",
"config_flag",
"(",
"option",
",",
"value",
",",
"default",
"=",
"False",
",",
"section",
"=",
"cli",
".",
"name",
")",
":",
"class",
"x",
"(",
"object",
")",
":",
"def",
"__bool__",
"(",
"self",
",",
"option",
"=",
"option",
",",
"value",
"=",
"value",
",",
"default",
"=",
"default",
",",
"section",
"=",
"section",
")",
":",
"config",
"=",
"read_config",
"(",
")",
"type",
"=",
"builtins",
".",
"type",
"(",
"value",
")",
"get_option",
"=",
"option_getter",
"(",
"type",
")",
"try",
":",
"return",
"get_option",
"(",
"config",
",",
"section",
",",
"option",
")",
"==",
"value",
"except",
"(",
"NoOptionError",
",",
"NoSectionError",
")",
":",
"return",
"default",
"__nonzero__",
"=",
"__bool__",
"return",
"x",
"(",
")"
] | Guesses whether a CLI flag should be turned on or off from the
configuration. If the configuration option value is same with the given
value, it returns ``True``.
::
@click.option('--ko-kr', 'locale', is_flag=True,
default=config_flag('locale', 'ko_KR')) | [
"Guesses",
"whether",
"a",
"CLI",
"flag",
"should",
"be",
"turned",
"on",
"or",
"off",
"from",
"the",
"configuration",
".",
"If",
"the",
"configuration",
"option",
"value",
"is",
"same",
"with",
"the",
"given",
"value",
"it",
"returns",
"True",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L147-L169 | train |
what-studio/profiling | profiling/__main__.py | get_title | def get_title(src_name, src_type=None):
"""Normalizes a source name as a string to be used for viewer's title."""
if src_type == 'tcp':
return '{0}:{1}'.format(*src_name)
return os.path.basename(src_name) | python | def get_title(src_name, src_type=None):
"""Normalizes a source name as a string to be used for viewer's title."""
if src_type == 'tcp':
return '{0}:{1}'.format(*src_name)
return os.path.basename(src_name) | [
"def",
"get_title",
"(",
"src_name",
",",
"src_type",
"=",
"None",
")",
":",
"if",
"src_type",
"==",
"'tcp'",
":",
"return",
"'{0}:{1}'",
".",
"format",
"(",
"*",
"src_name",
")",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"src_name",
")"
] | Normalizes a source name as a string to be used for viewer's title. | [
"Normalizes",
"a",
"source",
"name",
"as",
"a",
"string",
"to",
"be",
"used",
"for",
"viewer",
"s",
"title",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L172-L176 | train |
what-studio/profiling | profiling/__main__.py | spawn_thread | def spawn_thread(func, *args, **kwargs):
"""Spawns a daemon thread."""
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread | python | def spawn_thread(func, *args, **kwargs):
"""Spawns a daemon thread."""
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread | [
"def",
"spawn_thread",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
")",
"return",
"thread"
] | Spawns a daemon thread. | [
"Spawns",
"a",
"daemon",
"thread",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L189-L194 | train |
what-studio/profiling | profiling/__main__.py | spawn | def spawn(mode, func, *args, **kwargs):
"""Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
"""
if mode is None:
# 'threading' is the default mode.
mode = 'threading'
elif mode not in spawn.modes:
# validate the given mode.
raise ValueError('Invalid spawn mode: %s' % mode)
if mode == 'threading':
return spawn_thread(func, *args, **kwargs)
elif mode == 'gevent':
import gevent
import gevent.monkey
gevent.monkey.patch_select()
gevent.monkey.patch_socket()
return gevent.spawn(func, *args, **kwargs)
elif mode == 'eventlet':
import eventlet
eventlet.patcher.monkey_patch(select=True, socket=True)
return eventlet.spawn(func, *args, **kwargs)
assert False | python | def spawn(mode, func, *args, **kwargs):
"""Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet`
"""
if mode is None:
# 'threading' is the default mode.
mode = 'threading'
elif mode not in spawn.modes:
# validate the given mode.
raise ValueError('Invalid spawn mode: %s' % mode)
if mode == 'threading':
return spawn_thread(func, *args, **kwargs)
elif mode == 'gevent':
import gevent
import gevent.monkey
gevent.monkey.patch_select()
gevent.monkey.patch_socket()
return gevent.spawn(func, *args, **kwargs)
elif mode == 'eventlet':
import eventlet
eventlet.patcher.monkey_patch(select=True, socket=True)
return eventlet.spawn(func, *args, **kwargs)
assert False | [
"def",
"spawn",
"(",
"mode",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"is",
"None",
":",
"# 'threading' is the default mode.",
"mode",
"=",
"'threading'",
"elif",
"mode",
"not",
"in",
"spawn",
".",
"modes",
":",
"# validate the given mode.",
"raise",
"ValueError",
"(",
"'Invalid spawn mode: %s'",
"%",
"mode",
")",
"if",
"mode",
"==",
"'threading'",
":",
"return",
"spawn_thread",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"elif",
"mode",
"==",
"'gevent'",
":",
"import",
"gevent",
"import",
"gevent",
".",
"monkey",
"gevent",
".",
"monkey",
".",
"patch_select",
"(",
")",
"gevent",
".",
"monkey",
".",
"patch_socket",
"(",
")",
"return",
"gevent",
".",
"spawn",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"elif",
"mode",
"==",
"'eventlet'",
":",
"import",
"eventlet",
"eventlet",
".",
"patcher",
".",
"monkey_patch",
"(",
"select",
"=",
"True",
",",
"socket",
"=",
"True",
")",
"return",
"eventlet",
".",
"spawn",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"assert",
"False"
] | Spawns a thread-like object which runs the given function concurrently.
Available modes:
- `threading`
- `greenlet`
- `eventlet` | [
"Spawns",
"a",
"thread",
"-",
"like",
"object",
"which",
"runs",
"the",
"given",
"function",
"concurrently",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L197-L225 | train |
what-studio/profiling | profiling/__main__.py | profile | def profile(script, argv, profiler_factory,
pickle_protocol, dump_filename, mono):
"""Profile a Python script."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
__profile__(filename, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono) | python | def profile(script, argv, profiler_factory,
pickle_protocol, dump_filename, mono):
"""Profile a Python script."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
__profile__(filename, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono) | [
"def",
"profile",
"(",
"script",
",",
"argv",
",",
"profiler_factory",
",",
"pickle_protocol",
",",
"dump_filename",
",",
"mono",
")",
":",
"filename",
",",
"code",
",",
"globals_",
"=",
"script",
"sys",
".",
"argv",
"[",
":",
"]",
"=",
"[",
"filename",
"]",
"+",
"list",
"(",
"argv",
")",
"__profile__",
"(",
"filename",
",",
"code",
",",
"globals_",
",",
"profiler_factory",
",",
"pickle_protocol",
"=",
"pickle_protocol",
",",
"dump_filename",
"=",
"dump_filename",
",",
"mono",
"=",
"mono",
")"
] | Profile a Python script. | [
"Profile",
"a",
"Python",
"script",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L582-L589 | train |
what-studio/profiling | profiling/__main__.py | live_profile | def live_profile(script, argv, profiler_factory, interval, spawn, signum,
pickle_protocol, mono):
"""Profile a Python script continuously."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
parent_sock, child_sock = socket.socketpair()
stderr_r_fd, stderr_w_fd = os.pipe()
pid = os.fork()
if pid:
# parent
os.close(stderr_w_fd)
viewer, loop = make_viewer(mono)
# loop.screen._term_output_file = open(os.devnull, 'w')
title = get_title(filename)
client = ProfilingClient(viewer, loop.event_loop, parent_sock, title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
os.kill(pid, signal.SIGINT)
except BaseException:
# unexpected profiler error.
os.kill(pid, signal.SIGTERM)
raise
finally:
parent_sock.close()
# get exit code of child.
w_pid, status = os.waitpid(pid, os.WNOHANG)
if w_pid == 0:
os.kill(pid, signal.SIGTERM)
exit_code = os.WEXITSTATUS(status)
# print stderr of child.
with os.fdopen(stderr_r_fd, 'r') as f:
child_stderr = f.read()
if child_stderr:
sys.stdout.flush()
sys.stderr.write(child_stderr)
# exit with exit code of child.
sys.exit(exit_code)
else:
# child
os.close(stderr_r_fd)
# mute stdin, stdout.
devnull = os.open(os.devnull, os.O_RDWR)
for f in [sys.stdin, sys.stdout]:
os.dup2(devnull, f.fileno())
# redirect stderr to parent.
os.dup2(stderr_w_fd, sys.stderr.fileno())
frame = sys._getframe()
profiler = profiler_factory(base_frame=frame, base_code=code)
profiler_trigger = BackgroundProfiler(profiler, signum)
profiler_trigger.prepare()
server_args = (interval, noop, pickle_protocol)
server = SelectProfilingServer(None, profiler_trigger, *server_args)
server.clients.add(child_sock)
spawn(server.connected, child_sock)
try:
exec_(code, globals_)
finally:
os.close(stderr_w_fd)
child_sock.shutdown(socket.SHUT_WR) | python | def live_profile(script, argv, profiler_factory, interval, spawn, signum,
pickle_protocol, mono):
"""Profile a Python script continuously."""
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
parent_sock, child_sock = socket.socketpair()
stderr_r_fd, stderr_w_fd = os.pipe()
pid = os.fork()
if pid:
# parent
os.close(stderr_w_fd)
viewer, loop = make_viewer(mono)
# loop.screen._term_output_file = open(os.devnull, 'w')
title = get_title(filename)
client = ProfilingClient(viewer, loop.event_loop, parent_sock, title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
os.kill(pid, signal.SIGINT)
except BaseException:
# unexpected profiler error.
os.kill(pid, signal.SIGTERM)
raise
finally:
parent_sock.close()
# get exit code of child.
w_pid, status = os.waitpid(pid, os.WNOHANG)
if w_pid == 0:
os.kill(pid, signal.SIGTERM)
exit_code = os.WEXITSTATUS(status)
# print stderr of child.
with os.fdopen(stderr_r_fd, 'r') as f:
child_stderr = f.read()
if child_stderr:
sys.stdout.flush()
sys.stderr.write(child_stderr)
# exit with exit code of child.
sys.exit(exit_code)
else:
# child
os.close(stderr_r_fd)
# mute stdin, stdout.
devnull = os.open(os.devnull, os.O_RDWR)
for f in [sys.stdin, sys.stdout]:
os.dup2(devnull, f.fileno())
# redirect stderr to parent.
os.dup2(stderr_w_fd, sys.stderr.fileno())
frame = sys._getframe()
profiler = profiler_factory(base_frame=frame, base_code=code)
profiler_trigger = BackgroundProfiler(profiler, signum)
profiler_trigger.prepare()
server_args = (interval, noop, pickle_protocol)
server = SelectProfilingServer(None, profiler_trigger, *server_args)
server.clients.add(child_sock)
spawn(server.connected, child_sock)
try:
exec_(code, globals_)
finally:
os.close(stderr_w_fd)
child_sock.shutdown(socket.SHUT_WR) | [
"def",
"live_profile",
"(",
"script",
",",
"argv",
",",
"profiler_factory",
",",
"interval",
",",
"spawn",
",",
"signum",
",",
"pickle_protocol",
",",
"mono",
")",
":",
"filename",
",",
"code",
",",
"globals_",
"=",
"script",
"sys",
".",
"argv",
"[",
":",
"]",
"=",
"[",
"filename",
"]",
"+",
"list",
"(",
"argv",
")",
"parent_sock",
",",
"child_sock",
"=",
"socket",
".",
"socketpair",
"(",
")",
"stderr_r_fd",
",",
"stderr_w_fd",
"=",
"os",
".",
"pipe",
"(",
")",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
":",
"# parent",
"os",
".",
"close",
"(",
"stderr_w_fd",
")",
"viewer",
",",
"loop",
"=",
"make_viewer",
"(",
"mono",
")",
"# loop.screen._term_output_file = open(os.devnull, 'w')",
"title",
"=",
"get_title",
"(",
"filename",
")",
"client",
"=",
"ProfilingClient",
"(",
"viewer",
",",
"loop",
".",
"event_loop",
",",
"parent_sock",
",",
"title",
")",
"client",
".",
"start",
"(",
")",
"try",
":",
"loop",
".",
"run",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGINT",
")",
"except",
"BaseException",
":",
"# unexpected profiler error.",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"raise",
"finally",
":",
"parent_sock",
".",
"close",
"(",
")",
"# get exit code of child.",
"w_pid",
",",
"status",
"=",
"os",
".",
"waitpid",
"(",
"pid",
",",
"os",
".",
"WNOHANG",
")",
"if",
"w_pid",
"==",
"0",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"exit_code",
"=",
"os",
".",
"WEXITSTATUS",
"(",
"status",
")",
"# print stderr of child.",
"with",
"os",
".",
"fdopen",
"(",
"stderr_r_fd",
",",
"'r'",
")",
"as",
"f",
":",
"child_stderr",
"=",
"f",
".",
"read",
"(",
")",
"if",
"child_stderr",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"child_stderr",
")",
"# exit with exit code of child.",
"sys",
".",
"exit",
"(",
"exit_code",
")",
"else",
":",
"# child",
"os",
".",
"close",
"(",
"stderr_r_fd",
")",
"# mute stdin, stdout.",
"devnull",
"=",
"os",
".",
"open",
"(",
"os",
".",
"devnull",
",",
"os",
".",
"O_RDWR",
")",
"for",
"f",
"in",
"[",
"sys",
".",
"stdin",
",",
"sys",
".",
"stdout",
"]",
":",
"os",
".",
"dup2",
"(",
"devnull",
",",
"f",
".",
"fileno",
"(",
")",
")",
"# redirect stderr to parent.",
"os",
".",
"dup2",
"(",
"stderr_w_fd",
",",
"sys",
".",
"stderr",
".",
"fileno",
"(",
")",
")",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
")",
"profiler",
"=",
"profiler_factory",
"(",
"base_frame",
"=",
"frame",
",",
"base_code",
"=",
"code",
")",
"profiler_trigger",
"=",
"BackgroundProfiler",
"(",
"profiler",
",",
"signum",
")",
"profiler_trigger",
".",
"prepare",
"(",
")",
"server_args",
"=",
"(",
"interval",
",",
"noop",
",",
"pickle_protocol",
")",
"server",
"=",
"SelectProfilingServer",
"(",
"None",
",",
"profiler_trigger",
",",
"*",
"server_args",
")",
"server",
".",
"clients",
".",
"add",
"(",
"child_sock",
")",
"spawn",
"(",
"server",
".",
"connected",
",",
"child_sock",
")",
"try",
":",
"exec_",
"(",
"code",
",",
"globals_",
")",
"finally",
":",
"os",
".",
"close",
"(",
"stderr_w_fd",
")",
"child_sock",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_WR",
")"
] | Profile a Python script continuously. | [
"Profile",
"a",
"Python",
"script",
"continuously",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L597-L657 | train |
what-studio/profiling | profiling/__main__.py | view | def view(src, mono):
"""Inspect statistics by TUI view."""
src_type, src_name = src
title = get_title(src_name, src_type)
viewer, loop = make_viewer(mono)
if src_type == 'dump':
time = datetime.fromtimestamp(os.path.getmtime(src_name))
with open(src_name, 'rb') as f:
profiler_class, (stats, cpu_time, wall_time) = pickle.load(f)
viewer.set_profiler_class(profiler_class)
viewer.set_result(stats, cpu_time, wall_time, title=title, at=time)
viewer.activate()
elif src_type in ('tcp', 'sock'):
family = {'tcp': socket.AF_INET, 'sock': socket.AF_UNIX}[src_type]
client = FailoverProfilingClient(viewer, loop.event_loop,
src_name, family, title=title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
pass | python | def view(src, mono):
"""Inspect statistics by TUI view."""
src_type, src_name = src
title = get_title(src_name, src_type)
viewer, loop = make_viewer(mono)
if src_type == 'dump':
time = datetime.fromtimestamp(os.path.getmtime(src_name))
with open(src_name, 'rb') as f:
profiler_class, (stats, cpu_time, wall_time) = pickle.load(f)
viewer.set_profiler_class(profiler_class)
viewer.set_result(stats, cpu_time, wall_time, title=title, at=time)
viewer.activate()
elif src_type in ('tcp', 'sock'):
family = {'tcp': socket.AF_INET, 'sock': socket.AF_UNIX}[src_type]
client = FailoverProfilingClient(viewer, loop.event_loop,
src_name, family, title=title)
client.start()
try:
loop.run()
except KeyboardInterrupt:
pass | [
"def",
"view",
"(",
"src",
",",
"mono",
")",
":",
"src_type",
",",
"src_name",
"=",
"src",
"title",
"=",
"get_title",
"(",
"src_name",
",",
"src_type",
")",
"viewer",
",",
"loop",
"=",
"make_viewer",
"(",
"mono",
")",
"if",
"src_type",
"==",
"'dump'",
":",
"time",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"src_name",
")",
")",
"with",
"open",
"(",
"src_name",
",",
"'rb'",
")",
"as",
"f",
":",
"profiler_class",
",",
"(",
"stats",
",",
"cpu_time",
",",
"wall_time",
")",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"viewer",
".",
"set_profiler_class",
"(",
"profiler_class",
")",
"viewer",
".",
"set_result",
"(",
"stats",
",",
"cpu_time",
",",
"wall_time",
",",
"title",
"=",
"title",
",",
"at",
"=",
"time",
")",
"viewer",
".",
"activate",
"(",
")",
"elif",
"src_type",
"in",
"(",
"'tcp'",
",",
"'sock'",
")",
":",
"family",
"=",
"{",
"'tcp'",
":",
"socket",
".",
"AF_INET",
",",
"'sock'",
":",
"socket",
".",
"AF_UNIX",
"}",
"[",
"src_type",
"]",
"client",
"=",
"FailoverProfilingClient",
"(",
"viewer",
",",
"loop",
".",
"event_loop",
",",
"src_name",
",",
"family",
",",
"title",
"=",
"title",
")",
"client",
".",
"start",
"(",
")",
"try",
":",
"loop",
".",
"run",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
] | Inspect statistics by TUI view. | [
"Inspect",
"statistics",
"by",
"TUI",
"view",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L707-L727 | train |
what-studio/profiling | profiling/__main__.py | timeit_profile | def timeit_profile(stmt, number, repeat, setup,
profiler_factory, pickle_protocol, dump_filename, mono,
**_ignored):
"""Profile a Python statement like timeit."""
del _ignored
globals_ = {}
exec_(setup, globals_)
if number is None:
# determine number so that 0.2 <= total time < 2.0 like timeit.
dummy_profiler = profiler_factory()
dummy_profiler.start()
for x in range(1, 10):
number = 10 ** x
t = time.time()
for y in range(number):
exec_(stmt, globals_)
if time.time() - t >= 0.2:
break
dummy_profiler.stop()
del dummy_profiler
code = compile('for _ in range(%d): %s' % (number, stmt),
'STATEMENT', 'exec')
__profile__(stmt, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono) | python | def timeit_profile(stmt, number, repeat, setup,
profiler_factory, pickle_protocol, dump_filename, mono,
**_ignored):
"""Profile a Python statement like timeit."""
del _ignored
globals_ = {}
exec_(setup, globals_)
if number is None:
# determine number so that 0.2 <= total time < 2.0 like timeit.
dummy_profiler = profiler_factory()
dummy_profiler.start()
for x in range(1, 10):
number = 10 ** x
t = time.time()
for y in range(number):
exec_(stmt, globals_)
if time.time() - t >= 0.2:
break
dummy_profiler.stop()
del dummy_profiler
code = compile('for _ in range(%d): %s' % (number, stmt),
'STATEMENT', 'exec')
__profile__(stmt, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
mono=mono) | [
"def",
"timeit_profile",
"(",
"stmt",
",",
"number",
",",
"repeat",
",",
"setup",
",",
"profiler_factory",
",",
"pickle_protocol",
",",
"dump_filename",
",",
"mono",
",",
"*",
"*",
"_ignored",
")",
":",
"del",
"_ignored",
"globals_",
"=",
"{",
"}",
"exec_",
"(",
"setup",
",",
"globals_",
")",
"if",
"number",
"is",
"None",
":",
"# determine number so that 0.2 <= total time < 2.0 like timeit.",
"dummy_profiler",
"=",
"profiler_factory",
"(",
")",
"dummy_profiler",
".",
"start",
"(",
")",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"number",
"=",
"10",
"**",
"x",
"t",
"=",
"time",
".",
"time",
"(",
")",
"for",
"y",
"in",
"range",
"(",
"number",
")",
":",
"exec_",
"(",
"stmt",
",",
"globals_",
")",
"if",
"time",
".",
"time",
"(",
")",
"-",
"t",
">=",
"0.2",
":",
"break",
"dummy_profiler",
".",
"stop",
"(",
")",
"del",
"dummy_profiler",
"code",
"=",
"compile",
"(",
"'for _ in range(%d): %s'",
"%",
"(",
"number",
",",
"stmt",
")",
",",
"'STATEMENT'",
",",
"'exec'",
")",
"__profile__",
"(",
"stmt",
",",
"code",
",",
"globals_",
",",
"profiler_factory",
",",
"pickle_protocol",
"=",
"pickle_protocol",
",",
"dump_filename",
"=",
"dump_filename",
",",
"mono",
"=",
"mono",
")"
] | Profile a Python statement like timeit. | [
"Profile",
"a",
"Python",
"statement",
"like",
"timeit",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/__main__.py#L744-L768 | train |
what-studio/profiling | profiling/stats.py | spread_stats | def spread_stats(stats, spreader=False):
"""Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded statistics also.
"""
spread = spread_t() if spreader else True
descendants = deque(stats)
while descendants:
_stats = descendants.popleft()
if spreader:
spread.clear()
yield _stats, spread
else:
yield _stats
if spread:
descendants.extend(_stats) | python | def spread_stats(stats, spreader=False):
"""Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded statistics also.
"""
spread = spread_t() if spreader else True
descendants = deque(stats)
while descendants:
_stats = descendants.popleft()
if spreader:
spread.clear()
yield _stats, spread
else:
yield _stats
if spread:
descendants.extend(_stats) | [
"def",
"spread_stats",
"(",
"stats",
",",
"spreader",
"=",
"False",
")",
":",
"spread",
"=",
"spread_t",
"(",
")",
"if",
"spreader",
"else",
"True",
"descendants",
"=",
"deque",
"(",
"stats",
")",
"while",
"descendants",
":",
"_stats",
"=",
"descendants",
".",
"popleft",
"(",
")",
"if",
"spreader",
":",
"spread",
".",
"clear",
"(",
")",
"yield",
"_stats",
",",
"spread",
"else",
":",
"yield",
"_stats",
"if",
"spread",
":",
"descendants",
".",
"extend",
"(",
"_stats",
")"
] | Iterates all descendant statistics under the given root statistics.
When ``spreader=True``, each iteration yields a descendant statistics and
`spread()` function together. You should call `spread()` if you want to
spread the yielded statistics also. | [
"Iterates",
"all",
"descendant",
"statistics",
"under",
"the",
"given",
"root",
"statistics",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/stats.py#L38-L56 | train |
what-studio/profiling | profiling/stats.py | Statistics.own_time | def own_time(self):
"""The exclusive execution time."""
sub_time = sum(stats.deep_time for stats in self)
return max(0., self.deep_time - sub_time) | python | def own_time(self):
"""The exclusive execution time."""
sub_time = sum(stats.deep_time for stats in self)
return max(0., self.deep_time - sub_time) | [
"def",
"own_time",
"(",
"self",
")",
":",
"sub_time",
"=",
"sum",
"(",
"stats",
".",
"deep_time",
"for",
"stats",
"in",
"self",
")",
"return",
"max",
"(",
"0.",
",",
"self",
".",
"deep_time",
"-",
"sub_time",
")"
] | The exclusive execution time. | [
"The",
"exclusive",
"execution",
"time",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/stats.py#L137-L140 | train |
what-studio/profiling | profiling/stats.py | FlatFrozenStatistics.flatten | def flatten(cls, stats):
"""Makes a flat statistics from the given statistics."""
flat_children = {}
for _stats in spread_stats(stats):
key = (_stats.name, _stats.filename, _stats.lineno, _stats.module)
try:
flat_stats = flat_children[key]
except KeyError:
flat_stats = flat_children[key] = cls(*key)
flat_stats.own_hits += _stats.own_hits
flat_stats.deep_hits += _stats.deep_hits
flat_stats.own_time += _stats.own_time
flat_stats.deep_time += _stats.deep_time
children = list(itervalues(flat_children))
return cls(stats.name, stats.filename, stats.lineno, stats.module,
stats.own_hits, stats.deep_hits, stats.own_time,
stats.deep_time, children) | python | def flatten(cls, stats):
"""Makes a flat statistics from the given statistics."""
flat_children = {}
for _stats in spread_stats(stats):
key = (_stats.name, _stats.filename, _stats.lineno, _stats.module)
try:
flat_stats = flat_children[key]
except KeyError:
flat_stats = flat_children[key] = cls(*key)
flat_stats.own_hits += _stats.own_hits
flat_stats.deep_hits += _stats.deep_hits
flat_stats.own_time += _stats.own_time
flat_stats.deep_time += _stats.deep_time
children = list(itervalues(flat_children))
return cls(stats.name, stats.filename, stats.lineno, stats.module,
stats.own_hits, stats.deep_hits, stats.own_time,
stats.deep_time, children) | [
"def",
"flatten",
"(",
"cls",
",",
"stats",
")",
":",
"flat_children",
"=",
"{",
"}",
"for",
"_stats",
"in",
"spread_stats",
"(",
"stats",
")",
":",
"key",
"=",
"(",
"_stats",
".",
"name",
",",
"_stats",
".",
"filename",
",",
"_stats",
".",
"lineno",
",",
"_stats",
".",
"module",
")",
"try",
":",
"flat_stats",
"=",
"flat_children",
"[",
"key",
"]",
"except",
"KeyError",
":",
"flat_stats",
"=",
"flat_children",
"[",
"key",
"]",
"=",
"cls",
"(",
"*",
"key",
")",
"flat_stats",
".",
"own_hits",
"+=",
"_stats",
".",
"own_hits",
"flat_stats",
".",
"deep_hits",
"+=",
"_stats",
".",
"deep_hits",
"flat_stats",
".",
"own_time",
"+=",
"_stats",
".",
"own_time",
"flat_stats",
".",
"deep_time",
"+=",
"_stats",
".",
"deep_time",
"children",
"=",
"list",
"(",
"itervalues",
"(",
"flat_children",
")",
")",
"return",
"cls",
"(",
"stats",
".",
"name",
",",
"stats",
".",
"filename",
",",
"stats",
".",
"lineno",
",",
"stats",
".",
"module",
",",
"stats",
".",
"own_hits",
",",
"stats",
".",
"deep_hits",
",",
"stats",
".",
"own_time",
",",
"stats",
".",
"deep_time",
",",
"children",
")"
] | Makes a flat statistics from the given statistics. | [
"Makes",
"a",
"flat",
"statistics",
"from",
"the",
"given",
"statistics",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/stats.py#L357-L373 | train |
what-studio/profiling | setup.py | requirements | def requirements(filename):
"""Reads requirements from a file."""
with open(filename) as f:
return [x.strip() for x in f.readlines() if x.strip()] | python | def requirements(filename):
"""Reads requirements from a file."""
with open(filename) as f:
return [x.strip() for x in f.readlines() if x.strip()] | [
"def",
"requirements",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"return",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"f",
".",
"readlines",
"(",
")",
"if",
"x",
".",
"strip",
"(",
")",
"]"
] | Reads requirements from a file. | [
"Reads",
"requirements",
"from",
"a",
"file",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/setup.py#L68-L71 | train |
what-studio/profiling | profiling/sampling/__init__.py | SamplingProfiler.sample | def sample(self, frame):
"""Samples the given frame."""
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void)
stats = parent_stats.ensure_child(frame.f_code, RecordingStatistics)
stats.own_hits += 1 | python | def sample(self, frame):
"""Samples the given frame."""
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void)
stats = parent_stats.ensure_child(frame.f_code, RecordingStatistics)
stats.own_hits += 1 | [
"def",
"sample",
"(",
"self",
",",
"frame",
")",
":",
"frames",
"=",
"self",
".",
"frame_stack",
"(",
"frame",
")",
"if",
"frames",
":",
"frames",
".",
"pop",
"(",
")",
"parent_stats",
"=",
"self",
".",
"stats",
"for",
"f",
"in",
"frames",
":",
"parent_stats",
"=",
"parent_stats",
".",
"ensure_child",
"(",
"f",
".",
"f_code",
",",
"void",
")",
"stats",
"=",
"parent_stats",
".",
"ensure_child",
"(",
"frame",
".",
"f_code",
",",
"RecordingStatistics",
")",
"stats",
".",
"own_hits",
"+=",
"1"
] | Samples the given frame. | [
"Samples",
"the",
"given",
"frame",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/sampling/__init__.py#L65-L74 | train |
what-studio/profiling | profiling/utils.py | deferral | def deferral():
"""Defers a function call when it is being required like Go.
::
with deferral() as defer:
sys.setprofile(f)
defer(sys.setprofile, None)
# do something.
"""
deferred = []
defer = lambda f, *a, **k: deferred.append((f, a, k))
try:
yield defer
finally:
while deferred:
f, a, k = deferred.pop()
f(*a, **k) | python | def deferral():
"""Defers a function call when it is being required like Go.
::
with deferral() as defer:
sys.setprofile(f)
defer(sys.setprofile, None)
# do something.
"""
deferred = []
defer = lambda f, *a, **k: deferred.append((f, a, k))
try:
yield defer
finally:
while deferred:
f, a, k = deferred.pop()
f(*a, **k) | [
"def",
"deferral",
"(",
")",
":",
"deferred",
"=",
"[",
"]",
"defer",
"=",
"lambda",
"f",
",",
"*",
"a",
",",
"*",
"*",
"k",
":",
"deferred",
".",
"append",
"(",
"(",
"f",
",",
"a",
",",
"k",
")",
")",
"try",
":",
"yield",
"defer",
"finally",
":",
"while",
"deferred",
":",
"f",
",",
"a",
",",
"k",
"=",
"deferred",
".",
"pop",
"(",
")",
"f",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")"
] | Defers a function call when it is being required like Go.
::
with deferral() as defer:
sys.setprofile(f)
defer(sys.setprofile, None)
# do something. | [
"Defers",
"a",
"function",
"call",
"when",
"it",
"is",
"being",
"required",
"like",
"Go",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/utils.py#L135-L153 | train |
what-studio/profiling | profiling/utils.py | Runnable.start | def start(self, *args, **kwargs):
"""Starts the instance.
:raises RuntimeError: has been already started.
:raises TypeError: :meth:`run` is not canonical.
"""
if self.is_running():
raise RuntimeError('Already started')
self._running = self.run(*args, **kwargs)
try:
yielded = next(self._running)
except StopIteration:
raise TypeError('run() must yield just one time')
if yielded is not None:
raise TypeError('run() must yield without value') | python | def start(self, *args, **kwargs):
"""Starts the instance.
:raises RuntimeError: has been already started.
:raises TypeError: :meth:`run` is not canonical.
"""
if self.is_running():
raise RuntimeError('Already started')
self._running = self.run(*args, **kwargs)
try:
yielded = next(self._running)
except StopIteration:
raise TypeError('run() must yield just one time')
if yielded is not None:
raise TypeError('run() must yield without value') | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"is_running",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Already started'",
")",
"self",
".",
"_running",
"=",
"self",
".",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yielded",
"=",
"next",
"(",
"self",
".",
"_running",
")",
"except",
"StopIteration",
":",
"raise",
"TypeError",
"(",
"'run() must yield just one time'",
")",
"if",
"yielded",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"'run() must yield without value'",
")"
] | Starts the instance.
:raises RuntimeError: has been already started.
:raises TypeError: :meth:`run` is not canonical. | [
"Starts",
"the",
"instance",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/utils.py#L38-L53 | train |
what-studio/profiling | profiling/utils.py | Runnable.stop | def stop(self):
"""Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical.
"""
if not self.is_running():
raise RuntimeError('Not started')
running, self._running = self._running, None
try:
next(running)
except StopIteration:
# expected.
pass
else:
raise TypeError('run() must yield just one time') | python | def stop(self):
"""Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical.
"""
if not self.is_running():
raise RuntimeError('Not started')
running, self._running = self._running, None
try:
next(running)
except StopIteration:
# expected.
pass
else:
raise TypeError('run() must yield just one time') | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_running",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Not started'",
")",
"running",
",",
"self",
".",
"_running",
"=",
"self",
".",
"_running",
",",
"None",
"try",
":",
"next",
"(",
"running",
")",
"except",
"StopIteration",
":",
"# expected.",
"pass",
"else",
":",
"raise",
"TypeError",
"(",
"'run() must yield just one time'",
")"
] | Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical. | [
"Stops",
"the",
"instance",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/utils.py#L55-L71 | train |
what-studio/profiling | profiling/remote/select.py | SelectProfilingServer.sockets | def sockets(self):
"""Returns the set of the sockets."""
if self.listener is None:
return self.clients
else:
return self.clients.union([self.listener]) | python | def sockets(self):
"""Returns the set of the sockets."""
if self.listener is None:
return self.clients
else:
return self.clients.union([self.listener]) | [
"def",
"sockets",
"(",
"self",
")",
":",
"if",
"self",
".",
"listener",
"is",
"None",
":",
"return",
"self",
".",
"clients",
"else",
":",
"return",
"self",
".",
"clients",
".",
"union",
"(",
"[",
"self",
".",
"listener",
"]",
")"
] | Returns the set of the sockets. | [
"Returns",
"the",
"set",
"of",
"the",
"sockets",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/select.py#L62-L67 | train |
what-studio/profiling | profiling/remote/select.py | SelectProfilingServer.select_sockets | def select_sockets(self, timeout=None):
"""EINTR safe version of `select`. It focuses on just incoming
sockets.
"""
if timeout is not None:
t = time.time()
while True:
try:
ready, __, __ = select.select(self.sockets(), (), (), timeout)
except ValueError:
# there's fd=0 socket.
pass
except select.error as exc:
# ignore an interrupted system call.
if exc.args[0] != EINTR:
raise
else:
# succeeded.
return ready
# retry.
if timeout is None:
continue
# decrease timeout.
t2 = time.time()
timeout -= t2 - t
t = t2
if timeout <= 0:
# timed out.
return [] | python | def select_sockets(self, timeout=None):
"""EINTR safe version of `select`. It focuses on just incoming
sockets.
"""
if timeout is not None:
t = time.time()
while True:
try:
ready, __, __ = select.select(self.sockets(), (), (), timeout)
except ValueError:
# there's fd=0 socket.
pass
except select.error as exc:
# ignore an interrupted system call.
if exc.args[0] != EINTR:
raise
else:
# succeeded.
return ready
# retry.
if timeout is None:
continue
# decrease timeout.
t2 = time.time()
timeout -= t2 - t
t = t2
if timeout <= 0:
# timed out.
return [] | [
"def",
"select_sockets",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"ready",
",",
"__",
",",
"__",
"=",
"select",
".",
"select",
"(",
"self",
".",
"sockets",
"(",
")",
",",
"(",
")",
",",
"(",
")",
",",
"timeout",
")",
"except",
"ValueError",
":",
"# there's fd=0 socket.",
"pass",
"except",
"select",
".",
"error",
"as",
"exc",
":",
"# ignore an interrupted system call.",
"if",
"exc",
".",
"args",
"[",
"0",
"]",
"!=",
"EINTR",
":",
"raise",
"else",
":",
"# succeeded.",
"return",
"ready",
"# retry.",
"if",
"timeout",
"is",
"None",
":",
"continue",
"# decrease timeout.",
"t2",
"=",
"time",
".",
"time",
"(",
")",
"timeout",
"-=",
"t2",
"-",
"t",
"t",
"=",
"t2",
"if",
"timeout",
"<=",
"0",
":",
"# timed out.",
"return",
"[",
"]"
] | EINTR safe version of `select`. It focuses on just incoming
sockets. | [
"EINTR",
"safe",
"version",
"of",
"select",
".",
"It",
"focuses",
"on",
"just",
"incoming",
"sockets",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/select.py#L69-L97 | train |
what-studio/profiling | profiling/remote/select.py | SelectProfilingServer.dispatch_sockets | def dispatch_sockets(self, timeout=None):
"""Dispatches incoming sockets."""
for sock in self.select_sockets(timeout=timeout):
if sock is self.listener:
listener = sock
sock, addr = listener.accept()
self.connected(sock)
else:
try:
sock.recv(1)
except socket.error as exc:
if exc.errno != ECONNRESET:
raise
self.disconnected(sock) | python | def dispatch_sockets(self, timeout=None):
"""Dispatches incoming sockets."""
for sock in self.select_sockets(timeout=timeout):
if sock is self.listener:
listener = sock
sock, addr = listener.accept()
self.connected(sock)
else:
try:
sock.recv(1)
except socket.error as exc:
if exc.errno != ECONNRESET:
raise
self.disconnected(sock) | [
"def",
"dispatch_sockets",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"for",
"sock",
"in",
"self",
".",
"select_sockets",
"(",
"timeout",
"=",
"timeout",
")",
":",
"if",
"sock",
"is",
"self",
".",
"listener",
":",
"listener",
"=",
"sock",
"sock",
",",
"addr",
"=",
"listener",
".",
"accept",
"(",
")",
"self",
".",
"connected",
"(",
"sock",
")",
"else",
":",
"try",
":",
"sock",
".",
"recv",
"(",
"1",
")",
"except",
"socket",
".",
"error",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"ECONNRESET",
":",
"raise",
"self",
".",
"disconnected",
"(",
"sock",
")"
] | Dispatches incoming sockets. | [
"Dispatches",
"incoming",
"sockets",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/select.py#L99-L112 | train |
what-studio/profiling | profiling/tracing/__init__.py | TracingProfiler.record_entering | def record_entering(self, time, code, frame_key, parent_stats):
"""Entered to a function call."""
stats = parent_stats.ensure_child(code, RecordingStatistics)
self._times_entered[(code, frame_key)] = time
stats.own_hits += 1 | python | def record_entering(self, time, code, frame_key, parent_stats):
"""Entered to a function call."""
stats = parent_stats.ensure_child(code, RecordingStatistics)
self._times_entered[(code, frame_key)] = time
stats.own_hits += 1 | [
"def",
"record_entering",
"(",
"self",
",",
"time",
",",
"code",
",",
"frame_key",
",",
"parent_stats",
")",
":",
"stats",
"=",
"parent_stats",
".",
"ensure_child",
"(",
"code",
",",
"RecordingStatistics",
")",
"self",
".",
"_times_entered",
"[",
"(",
"code",
",",
"frame_key",
")",
"]",
"=",
"time",
"stats",
".",
"own_hits",
"+=",
"1"
] | Entered to a function call. | [
"Entered",
"to",
"a",
"function",
"call",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/tracing/__init__.py#L110-L114 | train |
what-studio/profiling | profiling/tracing/__init__.py | TracingProfiler.record_leaving | def record_leaving(self, time, code, frame_key, parent_stats):
"""Left from a function call."""
try:
stats = parent_stats.get_child(code)
time_entered = self._times_entered.pop((code, frame_key))
except KeyError:
return
time_elapsed = time - time_entered
stats.deep_time += max(0, time_elapsed) | python | def record_leaving(self, time, code, frame_key, parent_stats):
"""Left from a function call."""
try:
stats = parent_stats.get_child(code)
time_entered = self._times_entered.pop((code, frame_key))
except KeyError:
return
time_elapsed = time - time_entered
stats.deep_time += max(0, time_elapsed) | [
"def",
"record_leaving",
"(",
"self",
",",
"time",
",",
"code",
",",
"frame_key",
",",
"parent_stats",
")",
":",
"try",
":",
"stats",
"=",
"parent_stats",
".",
"get_child",
"(",
"code",
")",
"time_entered",
"=",
"self",
".",
"_times_entered",
".",
"pop",
"(",
"(",
"code",
",",
"frame_key",
")",
")",
"except",
"KeyError",
":",
"return",
"time_elapsed",
"=",
"time",
"-",
"time_entered",
"stats",
".",
"deep_time",
"+=",
"max",
"(",
"0",
",",
"time_elapsed",
")"
] | Left from a function call. | [
"Left",
"from",
"a",
"function",
"call",
"."
] | 49666ba3ea295eb73782ae6c18a4ec7929d7d8b7 | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/tracing/__init__.py#L116-L124 | train |
semiversus/python-broqer | broqer/op/subscribers/sink.py | build_sink | def build_sink(function: Callable[..., None] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Sink subscriber.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_sink(function: Callable[..., None]):
@wraps(function)
def _wrapper(*args, **kwargs) -> Sink:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Sink(function, *args, unpack=unpack, **kwargs)
return _wrapper
if function:
return _build_sink(function)
return _build_sink | python | def build_sink(function: Callable[..., None] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Sink subscriber.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_sink(function: Callable[..., None]):
@wraps(function)
def _wrapper(*args, **kwargs) -> Sink:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Sink(function, *args, unpack=unpack, **kwargs)
return _wrapper
if function:
return _build_sink(function)
return _build_sink | [
"def",
"build_sink",
"(",
"function",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
"=",
"None",
",",
"*",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"def",
"_build_sink",
"(",
"function",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Sink",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"return",
"Sink",
"(",
"function",
",",
"*",
"args",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_sink",
"(",
"function",
")",
"return",
"_build_sink"
] | Decorator to wrap a function to return a Sink subscriber.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value) | [
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"Sink",
"subscriber",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/subscribers/sink.py#L62-L80 | train |
semiversus/python-broqer | broqer/op/map_.py | build_map | def build_map(function: Callable[[Any], Any] = None,
unpack: bool = False):
""" Decorator to wrap a function to return a Map operator.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_map(function: Callable[[Any], Any]):
@wraps(function)
def _wrapper(*args, **kwargs) -> Map:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Map(function, *args, unpack=unpack, **kwargs)
return _wrapper
if function:
return _build_map(function)
return _build_map | python | def build_map(function: Callable[[Any], Any] = None,
unpack: bool = False):
""" Decorator to wrap a function to return a Map operator.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_map(function: Callable[[Any], Any]):
@wraps(function)
def _wrapper(*args, **kwargs) -> Map:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Map(function, *args, unpack=unpack, **kwargs)
return _wrapper
if function:
return _build_map(function)
return _build_map | [
"def",
"build_map",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
"=",
"None",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"def",
"_build_map",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Map",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"return",
"Map",
"(",
"function",
",",
"*",
"args",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_map",
"(",
"function",
")",
"return",
"_build_map"
] | Decorator to wrap a function to return a Map operator.
:param function: function to be wrapped
:param unpack: value from emits will be unpacked (*value) | [
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"Map",
"operator",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_.py#L92-L110 | train |
semiversus/python-broqer | broqer/op/subscribers/trace.py | Trace._trace_handler | def _trace_handler(publisher, value, label=None):
""" Default trace handler is printing the timestamp, the publisher name
and the emitted value
"""
line = '--- %8.3f: ' % (time() - Trace._timestamp_start)
line += repr(publisher) if label is None else label
line += ' %r' % (value,)
print(line) | python | def _trace_handler(publisher, value, label=None):
""" Default trace handler is printing the timestamp, the publisher name
and the emitted value
"""
line = '--- %8.3f: ' % (time() - Trace._timestamp_start)
line += repr(publisher) if label is None else label
line += ' %r' % (value,)
print(line) | [
"def",
"_trace_handler",
"(",
"publisher",
",",
"value",
",",
"label",
"=",
"None",
")",
":",
"line",
"=",
"'--- %8.3f: '",
"%",
"(",
"time",
"(",
")",
"-",
"Trace",
".",
"_timestamp_start",
")",
"line",
"+=",
"repr",
"(",
"publisher",
")",
"if",
"label",
"is",
"None",
"else",
"label",
"line",
"+=",
"' %r'",
"%",
"(",
"value",
",",
")",
"print",
"(",
"line",
")"
] | Default trace handler is printing the timestamp, the publisher name
and the emitted value | [
"Default",
"trace",
"handler",
"is",
"printing",
"the",
"timestamp",
"the",
"publisher",
"name",
"and",
"the",
"emitted",
"value"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/subscribers/trace.py#L45-L52 | train |
semiversus/python-broqer | broqer/op/subscribers/sink_async.py | build_sink_async | def build_sink_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a SinkAsync subscriber.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_sink_async(coro):
@wraps(coro)
def _wrapper(*args, mode=None, **kwargs) -> SinkAsync:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return SinkAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
return _wrapper
if coro:
return _build_sink_async(coro)
return _build_sink_async | python | def build_sink_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a SinkAsync subscriber.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_sink_async(coro):
@wraps(coro)
def _wrapper(*args, mode=None, **kwargs) -> SinkAsync:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return SinkAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
return _wrapper
if coro:
return _build_sink_async(coro)
return _build_sink_async | [
"def",
"build_sink_async",
"(",
"coro",
"=",
"None",
",",
"*",
",",
"mode",
"=",
"None",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"_mode",
"=",
"mode",
"def",
"_build_sink_async",
"(",
"coro",
")",
":",
"@",
"wraps",
"(",
"coro",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"mode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"SinkAsync",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"MODE",
".",
"CONCURRENT",
"if",
"_mode",
"is",
"None",
"else",
"_mode",
"return",
"SinkAsync",
"(",
"coro",
",",
"*",
"args",
",",
"mode",
"=",
"mode",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"coro",
":",
"return",
"_build_sink_async",
"(",
"coro",
")",
"return",
"_build_sink_async"
] | Decorator to wrap a coroutine to return a SinkAsync subscriber.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value) | [
"Decorator",
"to",
"wrap",
"a",
"coroutine",
"to",
"return",
"a",
"SinkAsync",
"subscriber",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/subscribers/sink_async.py#L60-L82 | train |
semiversus/python-broqer | broqer/op/accumulate.py | build_accumulate | def build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return an Accumulate operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def _build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]]):
@wraps(function)
def _wrapper(init=NONE) -> Accumulate:
init = _init if init is NONE else init
if init is NONE:
raise TypeError('"init" argument has to be defined')
return Accumulate(function, init=init)
return _wrapper
if function:
return _build_accumulate(function)
return _build_accumulate | python | def build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return an Accumulate operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def _build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]]):
@wraps(function)
def _wrapper(init=NONE) -> Accumulate:
init = _init if init is NONE else init
if init is NONE:
raise TypeError('"init" argument has to be defined')
return Accumulate(function, init=init)
return _wrapper
if function:
return _build_accumulate(function)
return _build_accumulate | [
"def",
"build_accumulate",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"*",
",",
"init",
":",
"Any",
"=",
"NONE",
")",
":",
"_init",
"=",
"init",
"def",
"_build_accumulate",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"init",
"=",
"NONE",
")",
"->",
"Accumulate",
":",
"init",
"=",
"_init",
"if",
"init",
"is",
"NONE",
"else",
"init",
"if",
"init",
"is",
"NONE",
":",
"raise",
"TypeError",
"(",
"'\"init\" argument has to be defined'",
")",
"return",
"Accumulate",
"(",
"function",
",",
"init",
"=",
"init",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_accumulate",
"(",
"function",
")",
"return",
"_build_accumulate"
] | Decorator to wrap a function to return an Accumulate operator.
:param function: function to be wrapped
:param init: optional initialization for state | [
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"an",
"Accumulate",
"operator",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/accumulate.py#L75-L96 | train |
semiversus/python-broqer | broqer/hub/utils/datatype_check.py | resolve_meta_key | def resolve_meta_key(hub, key, meta):
""" Resolve a value when it's a string and starts with '>' """
if key not in meta:
return None
value = meta[key]
if isinstance(value, str) and value[0] == '>':
topic = value[1:]
if topic not in hub:
raise KeyError('topic %s not found in hub' % topic)
return hub[topic].get()
return value | python | def resolve_meta_key(hub, key, meta):
""" Resolve a value when it's a string and starts with '>' """
if key not in meta:
return None
value = meta[key]
if isinstance(value, str) and value[0] == '>':
topic = value[1:]
if topic not in hub:
raise KeyError('topic %s not found in hub' % topic)
return hub[topic].get()
return value | [
"def",
"resolve_meta_key",
"(",
"hub",
",",
"key",
",",
"meta",
")",
":",
"if",
"key",
"not",
"in",
"meta",
":",
"return",
"None",
"value",
"=",
"meta",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
"and",
"value",
"[",
"0",
"]",
"==",
"'>'",
":",
"topic",
"=",
"value",
"[",
"1",
":",
"]",
"if",
"topic",
"not",
"in",
"hub",
":",
"raise",
"KeyError",
"(",
"'topic %s not found in hub'",
"%",
"topic",
")",
"return",
"hub",
"[",
"topic",
"]",
".",
"get",
"(",
")",
"return",
"value"
] | Resolve a value when it's a string and starts with '>' | [
"Resolve",
"a",
"value",
"when",
"it",
"s",
"a",
"string",
"and",
"starts",
"with",
">"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L10-L20 | train |
semiversus/python-broqer | broqer/hub/utils/datatype_check.py | DTTopic.checked_emit | def checked_emit(self, value: Any) -> asyncio.Future:
""" Casting and checking in one call """
if not isinstance(self._subject, Subscriber):
raise TypeError('Topic %r has to be a subscriber' % self._path)
value = self.cast(value)
self.check(value)
return self._subject.emit(value, who=self) | python | def checked_emit(self, value: Any) -> asyncio.Future:
""" Casting and checking in one call """
if not isinstance(self._subject, Subscriber):
raise TypeError('Topic %r has to be a subscriber' % self._path)
value = self.cast(value)
self.check(value)
return self._subject.emit(value, who=self) | [
"def",
"checked_emit",
"(",
"self",
",",
"value",
":",
"Any",
")",
"->",
"asyncio",
".",
"Future",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_subject",
",",
"Subscriber",
")",
":",
"raise",
"TypeError",
"(",
"'Topic %r has to be a subscriber'",
"%",
"self",
".",
"_path",
")",
"value",
"=",
"self",
".",
"cast",
"(",
"value",
")",
"self",
".",
"check",
"(",
"value",
")",
"return",
"self",
".",
"_subject",
".",
"emit",
"(",
"value",
",",
"who",
"=",
"self",
")"
] | Casting and checking in one call | [
"Casting",
"and",
"checking",
"in",
"one",
"call"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L178-L186 | train |
semiversus/python-broqer | broqer/hub/utils/datatype_check.py | DTRegistry.add_datatype | def add_datatype(self, name: str, datatype: DT):
""" Register the datatype with it's name """
self._datatypes[name] = datatype | python | def add_datatype(self, name: str, datatype: DT):
""" Register the datatype with it's name """
self._datatypes[name] = datatype | [
"def",
"add_datatype",
"(",
"self",
",",
"name",
":",
"str",
",",
"datatype",
":",
"DT",
")",
":",
"self",
".",
"_datatypes",
"[",
"name",
"]",
"=",
"datatype"
] | Register the datatype with it's name | [
"Register",
"the",
"datatype",
"with",
"it",
"s",
"name"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L202-L204 | train |
semiversus/python-broqer | broqer/hub/utils/datatype_check.py | DTRegistry.cast | def cast(self, topic, value):
""" Cast a string to the value based on the datatype """
datatype_key = topic.meta.get('datatype', 'none')
result = self._datatypes[datatype_key].cast(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
result = self._datatypes[validate_dt].cast(topic, result)
return result | python | def cast(self, topic, value):
""" Cast a string to the value based on the datatype """
datatype_key = topic.meta.get('datatype', 'none')
result = self._datatypes[datatype_key].cast(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
result = self._datatypes[validate_dt].cast(topic, result)
return result | [
"def",
"cast",
"(",
"self",
",",
"topic",
",",
"value",
")",
":",
"datatype_key",
"=",
"topic",
".",
"meta",
".",
"get",
"(",
"'datatype'",
",",
"'none'",
")",
"result",
"=",
"self",
".",
"_datatypes",
"[",
"datatype_key",
"]",
".",
"cast",
"(",
"topic",
",",
"value",
")",
"validate_dt",
"=",
"topic",
".",
"meta",
".",
"get",
"(",
"'validate'",
",",
"None",
")",
"if",
"validate_dt",
":",
"result",
"=",
"self",
".",
"_datatypes",
"[",
"validate_dt",
"]",
".",
"cast",
"(",
"topic",
",",
"result",
")",
"return",
"result"
] | Cast a string to the value based on the datatype | [
"Cast",
"a",
"string",
"to",
"the",
"value",
"based",
"on",
"the",
"datatype"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L213-L220 | train |
semiversus/python-broqer | broqer/hub/utils/datatype_check.py | DTRegistry.check | def check(self, topic, value):
""" Checking the value if it fits into the given specification """
datatype_key = topic.meta.get('datatype', 'none')
self._datatypes[datatype_key].check(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
self._datatypes[validate_dt].check(topic, value) | python | def check(self, topic, value):
""" Checking the value if it fits into the given specification """
datatype_key = topic.meta.get('datatype', 'none')
self._datatypes[datatype_key].check(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
self._datatypes[validate_dt].check(topic, value) | [
"def",
"check",
"(",
"self",
",",
"topic",
",",
"value",
")",
":",
"datatype_key",
"=",
"topic",
".",
"meta",
".",
"get",
"(",
"'datatype'",
",",
"'none'",
")",
"self",
".",
"_datatypes",
"[",
"datatype_key",
"]",
".",
"check",
"(",
"topic",
",",
"value",
")",
"validate_dt",
"=",
"topic",
".",
"meta",
".",
"get",
"(",
"'validate'",
",",
"None",
")",
"if",
"validate_dt",
":",
"self",
".",
"_datatypes",
"[",
"validate_dt",
"]",
".",
"check",
"(",
"topic",
",",
"value",
")"
] | Checking the value if it fits into the given specification | [
"Checking",
"the",
"value",
"if",
"it",
"fits",
"into",
"the",
"given",
"specification"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/utils/datatype_check.py#L222-L228 | train |
semiversus/python-broqer | broqer/op/partition.py | Partition.flush | def flush(self):
""" Emits the current queue and clears the queue """
self.notify(tuple(self._queue))
self._queue.clear() | python | def flush(self):
""" Emits the current queue and clears the queue """
self.notify(tuple(self._queue))
self._queue.clear() | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"notify",
"(",
"tuple",
"(",
"self",
".",
"_queue",
")",
")",
"self",
".",
"_queue",
".",
"clear",
"(",
")"
] | Emits the current queue and clears the queue | [
"Emits",
"the",
"current",
"queue",
"and",
"clears",
"the",
"queue"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/partition.py#L66-L69 | train |
semiversus/python-broqer | broqer/op/sample.py | Sample._periodic_callback | def _periodic_callback(self):
""" Will be started on first emit """
try:
self.notify(self._state) # emit to all subscribers
except Exception: # pylint: disable=broad-except
self._error_callback(*sys.exc_info())
if self._subscriptions:
# if there are still subscriptions register next _periodic callback
self._call_later_handle = \
self._loop.call_later(self._interval, self._periodic_callback)
else:
self._state = NONE
self._call_later_handle = None | python | def _periodic_callback(self):
""" Will be started on first emit """
try:
self.notify(self._state) # emit to all subscribers
except Exception: # pylint: disable=broad-except
self._error_callback(*sys.exc_info())
if self._subscriptions:
# if there are still subscriptions register next _periodic callback
self._call_later_handle = \
self._loop.call_later(self._interval, self._periodic_callback)
else:
self._state = NONE
self._call_later_handle = None | [
"def",
"_periodic_callback",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"notify",
"(",
"self",
".",
"_state",
")",
"# emit to all subscribers",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"self",
".",
"_error_callback",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
"if",
"self",
".",
"_subscriptions",
":",
"# if there are still subscriptions register next _periodic callback",
"self",
".",
"_call_later_handle",
"=",
"self",
".",
"_loop",
".",
"call_later",
"(",
"self",
".",
"_interval",
",",
"self",
".",
"_periodic_callback",
")",
"else",
":",
"self",
".",
"_state",
"=",
"NONE",
"self",
".",
"_call_later_handle",
"=",
"None"
] | Will be started on first emit | [
"Will",
"be",
"started",
"on",
"first",
"emit"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/sample.py#L84-L97 | train |
semiversus/python-broqer | broqer/op/reduce.py | build_reduce | def build_reduce(function: Callable[[Any, Any], Any] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return a Reduce operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def _build_reduce(function: Callable[[Any, Any], Any]):
@wraps(function)
def _wrapper(init=NONE) -> Reduce:
init = _init if init is NONE else init
if init is NONE:
raise TypeError('init argument has to be defined')
return Reduce(function, init=init)
return _wrapper
if function:
return _build_reduce(function)
return _build_reduce | python | def build_reduce(function: Callable[[Any, Any], Any] = None, *,
init: Any = NONE):
""" Decorator to wrap a function to return a Reduce operator.
:param function: function to be wrapped
:param init: optional initialization for state
"""
_init = init
def _build_reduce(function: Callable[[Any, Any], Any]):
@wraps(function)
def _wrapper(init=NONE) -> Reduce:
init = _init if init is NONE else init
if init is NONE:
raise TypeError('init argument has to be defined')
return Reduce(function, init=init)
return _wrapper
if function:
return _build_reduce(function)
return _build_reduce | [
"def",
"build_reduce",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Any",
"]",
"=",
"None",
",",
"*",
",",
"init",
":",
"Any",
"=",
"NONE",
")",
":",
"_init",
"=",
"init",
"def",
"_build_reduce",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
",",
"Any",
"]",
",",
"Any",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"init",
"=",
"NONE",
")",
"->",
"Reduce",
":",
"init",
"=",
"_init",
"if",
"init",
"is",
"NONE",
"else",
"init",
"if",
"init",
"is",
"NONE",
":",
"raise",
"TypeError",
"(",
"'init argument has to be defined'",
")",
"return",
"Reduce",
"(",
"function",
",",
"init",
"=",
"init",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_reduce",
"(",
"function",
")",
"return",
"_build_reduce"
] | Decorator to wrap a function to return a Reduce operator.
:param function: function to be wrapped
:param init: optional initialization for state | [
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"Reduce",
"operator",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/reduce.py#L54-L75 | train |
semiversus/python-broqer | broqer/op/sliding_window.py | SlidingWindow.flush | def flush(self):
""" Flush the queue - this will emit the current queue """
if not self._emit_partial and len(self._state) != self._state.maxlen:
self.notify(tuple(self._state))
self._state.clear() | python | def flush(self):
""" Flush the queue - this will emit the current queue """
if not self._emit_partial and len(self._state) != self._state.maxlen:
self.notify(tuple(self._state))
self._state.clear() | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_emit_partial",
"and",
"len",
"(",
"self",
".",
"_state",
")",
"!=",
"self",
".",
"_state",
".",
"maxlen",
":",
"self",
".",
"notify",
"(",
"tuple",
"(",
"self",
".",
"_state",
")",
")",
"self",
".",
"_state",
".",
"clear",
"(",
")"
] | Flush the queue - this will emit the current queue | [
"Flush",
"the",
"queue",
"-",
"this",
"will",
"emit",
"the",
"current",
"queue"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/sliding_window.py#L73-L77 | train |
semiversus/python-broqer | broqer/op/map_async.py | build_map_async | def build_map_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a MapAsync operator.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_map_async(coro):
@wraps(coro)
def _wrapper(*args, mode=None, **kwargs) -> MapAsync:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return MapAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
return _wrapper
if coro:
return _build_map_async(coro)
return _build_map_async | python | def build_map_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a MapAsync operator.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_map_async(coro):
@wraps(coro)
def _wrapper(*args, mode=None, **kwargs) -> MapAsync:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return MapAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
return _wrapper
if coro:
return _build_map_async(coro)
return _build_map_async | [
"def",
"build_map_async",
"(",
"coro",
"=",
"None",
",",
"*",
",",
"mode",
"=",
"None",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"_mode",
"=",
"mode",
"def",
"_build_map_async",
"(",
"coro",
")",
":",
"@",
"wraps",
"(",
"coro",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"mode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"MapAsync",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"MODE",
".",
"CONCURRENT",
"if",
"_mode",
"is",
"None",
"else",
"_mode",
"return",
"MapAsync",
"(",
"coro",
",",
"*",
"args",
",",
"mode",
"=",
"mode",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"coro",
":",
"return",
"_build_map_async",
"(",
"coro",
")",
"return",
"_build_map_async"
] | Decorator to wrap a coroutine to return a MapAsync operator.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value) | [
"Decorator",
"to",
"wrap",
"a",
"coroutine",
"to",
"return",
"a",
"MapAsync",
"operator",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_async.py#L234-L256 | train |
semiversus/python-broqer | broqer/op/map_async.py | MapAsync._future_done | def _future_done(self, future):
""" Will be called when the coroutine is done """
try:
# notify the subscribers (except result is an exception or NONE)
result = future.result() # may raise exception
if result is not NONE:
self.notify(result) # may also raise exception
except asyncio.CancelledError:
return
except Exception: # pylint: disable=broad-except
self._options.error_callback(*sys.exc_info())
# check if queue is present and something is in the queue
if self._queue:
value = self._queue.popleft()
# start the coroutine
self._run_coro(value)
else:
self._future = None | python | def _future_done(self, future):
""" Will be called when the coroutine is done """
try:
# notify the subscribers (except result is an exception or NONE)
result = future.result() # may raise exception
if result is not NONE:
self.notify(result) # may also raise exception
except asyncio.CancelledError:
return
except Exception: # pylint: disable=broad-except
self._options.error_callback(*sys.exc_info())
# check if queue is present and something is in the queue
if self._queue:
value = self._queue.popleft()
# start the coroutine
self._run_coro(value)
else:
self._future = None | [
"def",
"_future_done",
"(",
"self",
",",
"future",
")",
":",
"try",
":",
"# notify the subscribers (except result is an exception or NONE)",
"result",
"=",
"future",
".",
"result",
"(",
")",
"# may raise exception",
"if",
"result",
"is",
"not",
"NONE",
":",
"self",
".",
"notify",
"(",
"result",
")",
"# may also raise exception",
"except",
"asyncio",
".",
"CancelledError",
":",
"return",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"self",
".",
"_options",
".",
"error_callback",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
"# check if queue is present and something is in the queue",
"if",
"self",
".",
"_queue",
":",
"value",
"=",
"self",
".",
"_queue",
".",
"popleft",
"(",
")",
"# start the coroutine",
"self",
".",
"_run_coro",
"(",
"value",
")",
"else",
":",
"self",
".",
"_future",
"=",
"None"
] | Will be called when the coroutine is done | [
"Will",
"be",
"called",
"when",
"the",
"coroutine",
"is",
"done"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_async.py#L188-L207 | train |
semiversus/python-broqer | broqer/op/map_async.py | MapAsync._run_coro | def _run_coro(self, value):
""" Start the coroutine as task """
# when LAST_DISTINCT is used only start coroutine when value changed
if self._options.mode is MODE.LAST_DISTINCT and \
value == self._last_emit:
self._future = None
return
# store the value to be emitted for LAST_DISTINCT
self._last_emit = value
# publish the start of the coroutine
self.scheduled.notify(value)
# build the coroutine
values = value if self._options.unpack else (value,)
coro = self._options.coro(*values, *self._options.args,
**self._options.kwargs)
# create a task out of it and add ._future_done as callback
self._future = asyncio.ensure_future(coro)
self._future.add_done_callback(self._future_done) | python | def _run_coro(self, value):
""" Start the coroutine as task """
# when LAST_DISTINCT is used only start coroutine when value changed
if self._options.mode is MODE.LAST_DISTINCT and \
value == self._last_emit:
self._future = None
return
# store the value to be emitted for LAST_DISTINCT
self._last_emit = value
# publish the start of the coroutine
self.scheduled.notify(value)
# build the coroutine
values = value if self._options.unpack else (value,)
coro = self._options.coro(*values, *self._options.args,
**self._options.kwargs)
# create a task out of it and add ._future_done as callback
self._future = asyncio.ensure_future(coro)
self._future.add_done_callback(self._future_done) | [
"def",
"_run_coro",
"(",
"self",
",",
"value",
")",
":",
"# when LAST_DISTINCT is used only start coroutine when value changed",
"if",
"self",
".",
"_options",
".",
"mode",
"is",
"MODE",
".",
"LAST_DISTINCT",
"and",
"value",
"==",
"self",
".",
"_last_emit",
":",
"self",
".",
"_future",
"=",
"None",
"return",
"# store the value to be emitted for LAST_DISTINCT",
"self",
".",
"_last_emit",
"=",
"value",
"# publish the start of the coroutine",
"self",
".",
"scheduled",
".",
"notify",
"(",
"value",
")",
"# build the coroutine",
"values",
"=",
"value",
"if",
"self",
".",
"_options",
".",
"unpack",
"else",
"(",
"value",
",",
")",
"coro",
"=",
"self",
".",
"_options",
".",
"coro",
"(",
"*",
"values",
",",
"*",
"self",
".",
"_options",
".",
"args",
",",
"*",
"*",
"self",
".",
"_options",
".",
"kwargs",
")",
"# create a task out of it and add ._future_done as callback",
"self",
".",
"_future",
"=",
"asyncio",
".",
"ensure_future",
"(",
"coro",
")",
"self",
".",
"_future",
".",
"add_done_callback",
"(",
"self",
".",
"_future_done",
")"
] | Start the coroutine as task | [
"Start",
"the",
"coroutine",
"as",
"task"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_async.py#L209-L231 | train |
semiversus/python-broqer | broqer/op/filter_.py | build_filter | def build_filter(predicate: Callable[[Any], bool] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Filter operator.
:param predicate: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_filter(predicate: Callable[[Any], bool]):
@wraps(predicate)
def _wrapper(*args, **kwargs) -> Filter:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Filter(predicate, *args, unpack=unpack, **kwargs)
return _wrapper
if predicate:
return _build_filter(predicate)
return _build_filter | python | def build_filter(predicate: Callable[[Any], bool] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Filter operator.
:param predicate: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_filter(predicate: Callable[[Any], bool]):
@wraps(predicate)
def _wrapper(*args, **kwargs) -> Filter:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
return Filter(predicate, *args, unpack=unpack, **kwargs)
return _wrapper
if predicate:
return _build_filter(predicate)
return _build_filter | [
"def",
"build_filter",
"(",
"predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
"=",
"None",
",",
"*",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"def",
"_build_filter",
"(",
"predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
")",
":",
"@",
"wraps",
"(",
"predicate",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Filter",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"return",
"Filter",
"(",
"predicate",
",",
"*",
"args",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"predicate",
":",
"return",
"_build_filter",
"(",
"predicate",
")",
"return",
"_build_filter"
] | Decorator to wrap a function to return a Filter operator.
:param predicate: function to be wrapped
:param unpack: value from emits will be unpacked (*value) | [
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"Filter",
"operator",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/filter_.py#L119-L137 | train |
semiversus/python-broqer | broqer/op/operator_overloading.py | apply_operator_overloading | def apply_operator_overloading():
""" Function to apply operator overloading to Publisher class """
# operator overloading is (unfortunately) not working for the following
# cases:
# int, float, str - should return appropriate type instead of a Publisher
# len - should return an integer
# "x in y" - is using __bool__ which is not working with Publisher
for method in (
'__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__',
'__add__', '__and__', '__lshift__', '__mod__', '__mul__',
'__pow__', '__rshift__', '__sub__', '__xor__', '__concat__',
'__getitem__', '__floordiv__', '__truediv__'):
def _op(operand_left, operand_right, operation=method):
if isinstance(operand_right, Publisher):
return CombineLatest(operand_left, operand_right,
map_=getattr(operator, operation))
return _MapConstant(operand_left, operand_right,
getattr(operator, operation))
setattr(Publisher, method, _op)
for method, _method in (
('__radd__', '__add__'), ('__rand__', '__and__'),
('__rlshift__', '__lshift__'), ('__rmod__', '__mod__'),
('__rmul__', '__mul__'), ('__rpow__', '__pow__'),
('__rrshift__', '__rshift__'), ('__rsub__', '__sub__'),
('__rxor__', '__xor__'), ('__rfloordiv__', '__floordiv__'),
('__rtruediv__', '__truediv__')):
def _op(operand_left, operand_right, operation=_method):
return _MapConstantReverse(operand_left, operand_right,
getattr(operator, operation))
setattr(Publisher, method, _op)
for method, _method in (
('__neg__', operator.neg), ('__pos__', operator.pos),
('__abs__', operator.abs), ('__invert__', operator.invert),
('__round__', round), ('__trunc__', math.trunc),
('__floor__', math.floor), ('__ceil__', math.ceil)):
def _op_unary(operand, operation=_method):
return _MapUnary(operand, operation)
setattr(Publisher, method, _op_unary)
def _getattr(publisher, attribute_name):
if not publisher.inherited_type or \
not hasattr(publisher.inherited_type, attribute_name):
raise AttributeError('Attribute %r not found' % attribute_name)
return _GetAttr(publisher, attribute_name)
setattr(Publisher, '__getattr__', _getattr) | python | def apply_operator_overloading():
""" Function to apply operator overloading to Publisher class """
# operator overloading is (unfortunately) not working for the following
# cases:
# int, float, str - should return appropriate type instead of a Publisher
# len - should return an integer
# "x in y" - is using __bool__ which is not working with Publisher
for method in (
'__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__',
'__add__', '__and__', '__lshift__', '__mod__', '__mul__',
'__pow__', '__rshift__', '__sub__', '__xor__', '__concat__',
'__getitem__', '__floordiv__', '__truediv__'):
def _op(operand_left, operand_right, operation=method):
if isinstance(operand_right, Publisher):
return CombineLatest(operand_left, operand_right,
map_=getattr(operator, operation))
return _MapConstant(operand_left, operand_right,
getattr(operator, operation))
setattr(Publisher, method, _op)
for method, _method in (
('__radd__', '__add__'), ('__rand__', '__and__'),
('__rlshift__', '__lshift__'), ('__rmod__', '__mod__'),
('__rmul__', '__mul__'), ('__rpow__', '__pow__'),
('__rrshift__', '__rshift__'), ('__rsub__', '__sub__'),
('__rxor__', '__xor__'), ('__rfloordiv__', '__floordiv__'),
('__rtruediv__', '__truediv__')):
def _op(operand_left, operand_right, operation=_method):
return _MapConstantReverse(operand_left, operand_right,
getattr(operator, operation))
setattr(Publisher, method, _op)
for method, _method in (
('__neg__', operator.neg), ('__pos__', operator.pos),
('__abs__', operator.abs), ('__invert__', operator.invert),
('__round__', round), ('__trunc__', math.trunc),
('__floor__', math.floor), ('__ceil__', math.ceil)):
def _op_unary(operand, operation=_method):
return _MapUnary(operand, operation)
setattr(Publisher, method, _op_unary)
def _getattr(publisher, attribute_name):
if not publisher.inherited_type or \
not hasattr(publisher.inherited_type, attribute_name):
raise AttributeError('Attribute %r not found' % attribute_name)
return _GetAttr(publisher, attribute_name)
setattr(Publisher, '__getattr__', _getattr) | [
"def",
"apply_operator_overloading",
"(",
")",
":",
"# operator overloading is (unfortunately) not working for the following",
"# cases:",
"# int, float, str - should return appropriate type instead of a Publisher",
"# len - should return an integer",
"# \"x in y\" - is using __bool__ which is not working with Publisher",
"for",
"method",
"in",
"(",
"'__lt__'",
",",
"'__le__'",
",",
"'__eq__'",
",",
"'__ne__'",
",",
"'__ge__'",
",",
"'__gt__'",
",",
"'__add__'",
",",
"'__and__'",
",",
"'__lshift__'",
",",
"'__mod__'",
",",
"'__mul__'",
",",
"'__pow__'",
",",
"'__rshift__'",
",",
"'__sub__'",
",",
"'__xor__'",
",",
"'__concat__'",
",",
"'__getitem__'",
",",
"'__floordiv__'",
",",
"'__truediv__'",
")",
":",
"def",
"_op",
"(",
"operand_left",
",",
"operand_right",
",",
"operation",
"=",
"method",
")",
":",
"if",
"isinstance",
"(",
"operand_right",
",",
"Publisher",
")",
":",
"return",
"CombineLatest",
"(",
"operand_left",
",",
"operand_right",
",",
"map_",
"=",
"getattr",
"(",
"operator",
",",
"operation",
")",
")",
"return",
"_MapConstant",
"(",
"operand_left",
",",
"operand_right",
",",
"getattr",
"(",
"operator",
",",
"operation",
")",
")",
"setattr",
"(",
"Publisher",
",",
"method",
",",
"_op",
")",
"for",
"method",
",",
"_method",
"in",
"(",
"(",
"'__radd__'",
",",
"'__add__'",
")",
",",
"(",
"'__rand__'",
",",
"'__and__'",
")",
",",
"(",
"'__rlshift__'",
",",
"'__lshift__'",
")",
",",
"(",
"'__rmod__'",
",",
"'__mod__'",
")",
",",
"(",
"'__rmul__'",
",",
"'__mul__'",
")",
",",
"(",
"'__rpow__'",
",",
"'__pow__'",
")",
",",
"(",
"'__rrshift__'",
",",
"'__rshift__'",
")",
",",
"(",
"'__rsub__'",
",",
"'__sub__'",
")",
",",
"(",
"'__rxor__'",
",",
"'__xor__'",
")",
",",
"(",
"'__rfloordiv__'",
",",
"'__floordiv__'",
")",
",",
"(",
"'__rtruediv__'",
",",
"'__truediv__'",
")",
")",
":",
"def",
"_op",
"(",
"operand_left",
",",
"operand_right",
",",
"operation",
"=",
"_method",
")",
":",
"return",
"_MapConstantReverse",
"(",
"operand_left",
",",
"operand_right",
",",
"getattr",
"(",
"operator",
",",
"operation",
")",
")",
"setattr",
"(",
"Publisher",
",",
"method",
",",
"_op",
")",
"for",
"method",
",",
"_method",
"in",
"(",
"(",
"'__neg__'",
",",
"operator",
".",
"neg",
")",
",",
"(",
"'__pos__'",
",",
"operator",
".",
"pos",
")",
",",
"(",
"'__abs__'",
",",
"operator",
".",
"abs",
")",
",",
"(",
"'__invert__'",
",",
"operator",
".",
"invert",
")",
",",
"(",
"'__round__'",
",",
"round",
")",
",",
"(",
"'__trunc__'",
",",
"math",
".",
"trunc",
")",
",",
"(",
"'__floor__'",
",",
"math",
".",
"floor",
")",
",",
"(",
"'__ceil__'",
",",
"math",
".",
"ceil",
")",
")",
":",
"def",
"_op_unary",
"(",
"operand",
",",
"operation",
"=",
"_method",
")",
":",
"return",
"_MapUnary",
"(",
"operand",
",",
"operation",
")",
"setattr",
"(",
"Publisher",
",",
"method",
",",
"_op_unary",
")",
"def",
"_getattr",
"(",
"publisher",
",",
"attribute_name",
")",
":",
"if",
"not",
"publisher",
".",
"inherited_type",
"or",
"not",
"hasattr",
"(",
"publisher",
".",
"inherited_type",
",",
"attribute_name",
")",
":",
"raise",
"AttributeError",
"(",
"'Attribute %r not found'",
"%",
"attribute_name",
")",
"return",
"_GetAttr",
"(",
"publisher",
",",
"attribute_name",
")",
"setattr",
"(",
"Publisher",
",",
"'__getattr__'",
",",
"_getattr",
")"
] | Function to apply operator overloading to Publisher class | [
"Function",
"to",
"apply",
"operator",
"overloading",
"to",
"Publisher",
"class"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/operator_overloading.py#L112-L162 | train |
semiversus/python-broqer | broqer/hub/hub.py | Topic.assign | def assign(self, subject):
""" Assigns the given subject to the topic """
if not isinstance(subject, (Publisher, Subscriber)):
raise TypeError('Assignee has to be Publisher or Subscriber')
# check if not already assigned
if self._subject is not None:
raise SubscriptionError('Topic %r already assigned' % self._path)
self._subject = subject
# subscribe to subject if topic has subscriptions
if self._subscriptions:
self._subject.subscribe(self)
# if topic received emits before assignment replay those emits
if self._pre_assign_emit is not None:
for value in self._pre_assign_emit:
self._subject.emit(value, who=self)
self._pre_assign_emit = None
return subject | python | def assign(self, subject):
""" Assigns the given subject to the topic """
if not isinstance(subject, (Publisher, Subscriber)):
raise TypeError('Assignee has to be Publisher or Subscriber')
# check if not already assigned
if self._subject is not None:
raise SubscriptionError('Topic %r already assigned' % self._path)
self._subject = subject
# subscribe to subject if topic has subscriptions
if self._subscriptions:
self._subject.subscribe(self)
# if topic received emits before assignment replay those emits
if self._pre_assign_emit is not None:
for value in self._pre_assign_emit:
self._subject.emit(value, who=self)
self._pre_assign_emit = None
return subject | [
"def",
"assign",
"(",
"self",
",",
"subject",
")",
":",
"if",
"not",
"isinstance",
"(",
"subject",
",",
"(",
"Publisher",
",",
"Subscriber",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Assignee has to be Publisher or Subscriber'",
")",
"# check if not already assigned",
"if",
"self",
".",
"_subject",
"is",
"not",
"None",
":",
"raise",
"SubscriptionError",
"(",
"'Topic %r already assigned'",
"%",
"self",
".",
"_path",
")",
"self",
".",
"_subject",
"=",
"subject",
"# subscribe to subject if topic has subscriptions",
"if",
"self",
".",
"_subscriptions",
":",
"self",
".",
"_subject",
".",
"subscribe",
"(",
"self",
")",
"# if topic received emits before assignment replay those emits",
"if",
"self",
".",
"_pre_assign_emit",
"is",
"not",
"None",
":",
"for",
"value",
"in",
"self",
".",
"_pre_assign_emit",
":",
"self",
".",
"_subject",
".",
"emit",
"(",
"value",
",",
"who",
"=",
"self",
")",
"self",
".",
"_pre_assign_emit",
"=",
"None",
"return",
"subject"
] | Assigns the given subject to the topic | [
"Assigns",
"the",
"given",
"subject",
"to",
"the",
"topic"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/hub.py#L149-L170 | train |
semiversus/python-broqer | broqer/hub/hub.py | Hub.freeze | def freeze(self, freeze: bool = True):
""" Freezing the hub means that each topic has to be assigned and no
new topics can be created after this point.
"""
for topic in self._topics.values():
topic.freeze()
self._frozen = freeze | python | def freeze(self, freeze: bool = True):
""" Freezing the hub means that each topic has to be assigned and no
new topics can be created after this point.
"""
for topic in self._topics.values():
topic.freeze()
self._frozen = freeze | [
"def",
"freeze",
"(",
"self",
",",
"freeze",
":",
"bool",
"=",
"True",
")",
":",
"for",
"topic",
"in",
"self",
".",
"_topics",
".",
"values",
"(",
")",
":",
"topic",
".",
"freeze",
"(",
")",
"self",
".",
"_frozen",
"=",
"freeze"
] | Freezing the hub means that each topic has to be assigned and no
new topics can be created after this point. | [
"Freezing",
"the",
"hub",
"means",
"that",
"each",
"topic",
"has",
"to",
"be",
"assigned",
"and",
"no",
"new",
"topics",
"can",
"be",
"created",
"after",
"this",
"point",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/hub/hub.py#L247-L253 | train |
semiversus/python-broqer | broqer/op/throttle.py | Throttle.reset | def reset(self):
""" Reseting duration for throttling """
if self._call_later_handler is not None:
self._call_later_handler.cancel()
self._call_later_handler = None
self._wait_done_cb() | python | def reset(self):
""" Reseting duration for throttling """
if self._call_later_handler is not None:
self._call_later_handler.cancel()
self._call_later_handler = None
self._wait_done_cb() | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"_call_later_handler",
"is",
"not",
"None",
":",
"self",
".",
"_call_later_handler",
".",
"cancel",
"(",
")",
"self",
".",
"_call_later_handler",
"=",
"None",
"self",
".",
"_wait_done_cb",
"(",
")"
] | Reseting duration for throttling | [
"Reseting",
"duration",
"for",
"throttling"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/throttle.py#L82-L87 | train |
semiversus/python-broqer | broqer/op/map_threaded.py | build_map_threaded | def build_map_threaded(function: Callable[[Any], Any] = None,
mode=MODE.CONCURRENT, unpack: bool = False):
""" Decorator to wrap a function to return a MapThreaded operator.
:param function: function to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_map_threaded(function: Callable[[Any], Any]):
@wraps(function)
def _wrapper(*args, mode=None, **kwargs) -> MapThreaded:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return MapThreaded(function, *args, mode=mode, unpack=unpack,
**kwargs)
return _wrapper
if function:
return _build_map_threaded(function)
return _build_map_threaded | python | def build_map_threaded(function: Callable[[Any], Any] = None,
mode=MODE.CONCURRENT, unpack: bool = False):
""" Decorator to wrap a function to return a MapThreaded operator.
:param function: function to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode = mode
def _build_map_threaded(function: Callable[[Any], Any]):
@wraps(function)
def _wrapper(*args, mode=None, **kwargs) -> MapThreaded:
if 'unpack' in kwargs:
raise TypeError('"unpack" has to be defined by decorator')
if mode is None:
mode = MODE.CONCURRENT if _mode is None else _mode
return MapThreaded(function, *args, mode=mode, unpack=unpack,
**kwargs)
return _wrapper
if function:
return _build_map_threaded(function)
return _build_map_threaded | [
"def",
"build_map_threaded",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
"=",
"None",
",",
"mode",
"=",
"MODE",
".",
"CONCURRENT",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"_mode",
"=",
"mode",
"def",
"_build_map_threaded",
"(",
"function",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"mode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"MapThreaded",
":",
"if",
"'unpack'",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'\"unpack\" has to be defined by decorator'",
")",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"MODE",
".",
"CONCURRENT",
"if",
"_mode",
"is",
"None",
"else",
"_mode",
"return",
"MapThreaded",
"(",
"function",
",",
"*",
"args",
",",
"mode",
"=",
"mode",
",",
"unpack",
"=",
"unpack",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"if",
"function",
":",
"return",
"_build_map_threaded",
"(",
"function",
")",
"return",
"_build_map_threaded"
] | Decorator to wrap a function to return a MapThreaded operator.
:param function: function to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value) | [
"Decorator",
"to",
"wrap",
"a",
"function",
"to",
"return",
"a",
"MapThreaded",
"operator",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_threaded.py#L130-L154 | train |
semiversus/python-broqer | broqer/op/map_threaded.py | MapThreaded._thread_coro | async def _thread_coro(self, *args):
""" Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread """
return await self._loop.run_in_executor(
self._executor, self._function, *args) | python | async def _thread_coro(self, *args):
""" Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread """
return await self._loop.run_in_executor(
self._executor, self._function, *args) | [
"async",
"def",
"_thread_coro",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"await",
"self",
".",
"_loop",
".",
"run_in_executor",
"(",
"self",
".",
"_executor",
",",
"self",
".",
"_function",
",",
"*",
"args",
")"
] | Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread | [
"Coroutine",
"called",
"by",
"MapAsync",
".",
"It",
"s",
"wrapping",
"the",
"call",
"of",
"run_in_executor",
"to",
"run",
"the",
"synchronous",
"function",
"as",
"thread"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/map_threaded.py#L123-L127 | train |
semiversus/python-broqer | broqer/op/debounce.py | Debounce.reset | def reset(self):
""" Reset the debounce time """
if self._retrigger_value is not NONE:
self.notify(self._retrigger_value)
self._state = self._retrigger_value
self._next_state = self._retrigger_value
if self._call_later_handler:
self._call_later_handler.cancel()
self._call_later_handler = None | python | def reset(self):
""" Reset the debounce time """
if self._retrigger_value is not NONE:
self.notify(self._retrigger_value)
self._state = self._retrigger_value
self._next_state = self._retrigger_value
if self._call_later_handler:
self._call_later_handler.cancel()
self._call_later_handler = None | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"_retrigger_value",
"is",
"not",
"NONE",
":",
"self",
".",
"notify",
"(",
"self",
".",
"_retrigger_value",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_retrigger_value",
"self",
".",
"_next_state",
"=",
"self",
".",
"_retrigger_value",
"if",
"self",
".",
"_call_later_handler",
":",
"self",
".",
"_call_later_handler",
".",
"cancel",
"(",
")",
"self",
".",
"_call_later_handler",
"=",
"None"
] | Reset the debounce time | [
"Reset",
"the",
"debounce",
"time"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/op/debounce.py#L136-L144 | train |
semiversus/python-broqer | broqer/publisher.py | Publisher.subscribe | def subscribe(self, subscriber: 'Subscriber',
prepend: bool = False) -> SubscriptionDisposable:
""" Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list. When prepend is True, it will be added
in front of the list. This will habe an effect in the order the
subscribers are called.
:raises SubscriptionError: if subscriber already subscribed
"""
# `subscriber in self._subscriptions` is not working because
# tuple.__contains__ is using __eq__ which is overwritten and returns
# a new publisher - not helpful here
if any(subscriber is s for s in self._subscriptions):
raise SubscriptionError('Subscriber already registered')
if prepend:
self._subscriptions.insert(0, subscriber)
else:
self._subscriptions.append(subscriber)
return SubscriptionDisposable(self, subscriber) | python | def subscribe(self, subscriber: 'Subscriber',
prepend: bool = False) -> SubscriptionDisposable:
""" Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list. When prepend is True, it will be added
in front of the list. This will habe an effect in the order the
subscribers are called.
:raises SubscriptionError: if subscriber already subscribed
"""
# `subscriber in self._subscriptions` is not working because
# tuple.__contains__ is using __eq__ which is overwritten and returns
# a new publisher - not helpful here
if any(subscriber is s for s in self._subscriptions):
raise SubscriptionError('Subscriber already registered')
if prepend:
self._subscriptions.insert(0, subscriber)
else:
self._subscriptions.append(subscriber)
return SubscriptionDisposable(self, subscriber) | [
"def",
"subscribe",
"(",
"self",
",",
"subscriber",
":",
"'Subscriber'",
",",
"prepend",
":",
"bool",
"=",
"False",
")",
"->",
"SubscriptionDisposable",
":",
"# `subscriber in self._subscriptions` is not working because",
"# tuple.__contains__ is using __eq__ which is overwritten and returns",
"# a new publisher - not helpful here",
"if",
"any",
"(",
"subscriber",
"is",
"s",
"for",
"s",
"in",
"self",
".",
"_subscriptions",
")",
":",
"raise",
"SubscriptionError",
"(",
"'Subscriber already registered'",
")",
"if",
"prepend",
":",
"self",
".",
"_subscriptions",
".",
"insert",
"(",
"0",
",",
"subscriber",
")",
"else",
":",
"self",
".",
"_subscriptions",
".",
"append",
"(",
"subscriber",
")",
"return",
"SubscriptionDisposable",
"(",
"self",
",",
"subscriber",
")"
] | Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list. When prepend is True, it will be added
in front of the list. This will habe an effect in the order the
subscribers are called.
:raises SubscriptionError: if subscriber already subscribed | [
"Subscribing",
"the",
"given",
"subscriber",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/publisher.py#L45-L68 | train |
semiversus/python-broqer | broqer/publisher.py | Publisher.unsubscribe | def unsubscribe(self, subscriber: 'Subscriber') -> None:
""" Unsubscribe the given subscriber
:param subscriber: subscriber to unsubscribe
:raises SubscriptionError: if subscriber is not subscribed (anymore)
"""
# here is a special implementation which is replacing the more
# obvious one: self._subscriptions.remove(subscriber) - this will not
# work because list.remove(x) is doing comparision for equality.
# Applied to publishers this will return another publisher instead of
# a boolean result
for i, _s in enumerate(self._subscriptions):
if _s is subscriber:
self._subscriptions.pop(i)
return
raise SubscriptionError('Subscriber is not registered') | python | def unsubscribe(self, subscriber: 'Subscriber') -> None:
""" Unsubscribe the given subscriber
:param subscriber: subscriber to unsubscribe
:raises SubscriptionError: if subscriber is not subscribed (anymore)
"""
# here is a special implementation which is replacing the more
# obvious one: self._subscriptions.remove(subscriber) - this will not
# work because list.remove(x) is doing comparision for equality.
# Applied to publishers this will return another publisher instead of
# a boolean result
for i, _s in enumerate(self._subscriptions):
if _s is subscriber:
self._subscriptions.pop(i)
return
raise SubscriptionError('Subscriber is not registered') | [
"def",
"unsubscribe",
"(",
"self",
",",
"subscriber",
":",
"'Subscriber'",
")",
"->",
"None",
":",
"# here is a special implementation which is replacing the more",
"# obvious one: self._subscriptions.remove(subscriber) - this will not",
"# work because list.remove(x) is doing comparision for equality.",
"# Applied to publishers this will return another publisher instead of",
"# a boolean result",
"for",
"i",
",",
"_s",
"in",
"enumerate",
"(",
"self",
".",
"_subscriptions",
")",
":",
"if",
"_s",
"is",
"subscriber",
":",
"self",
".",
"_subscriptions",
".",
"pop",
"(",
"i",
")",
"return",
"raise",
"SubscriptionError",
"(",
"'Subscriber is not registered'",
")"
] | Unsubscribe the given subscriber
:param subscriber: subscriber to unsubscribe
:raises SubscriptionError: if subscriber is not subscribed (anymore) | [
"Unsubscribe",
"the",
"given",
"subscriber"
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/publisher.py#L70-L85 | train |
semiversus/python-broqer | broqer/publisher.py | Publisher.inherit_type | def inherit_type(self, type_cls: Type[TInherit]) \
-> Union[TInherit, 'Publisher']:
""" enables the usage of method and attribute overloading for this
publisher.
"""
self._inherited_type = type_cls
return self | python | def inherit_type(self, type_cls: Type[TInherit]) \
-> Union[TInherit, 'Publisher']:
""" enables the usage of method and attribute overloading for this
publisher.
"""
self._inherited_type = type_cls
return self | [
"def",
"inherit_type",
"(",
"self",
",",
"type_cls",
":",
"Type",
"[",
"TInherit",
"]",
")",
"->",
"Union",
"[",
"TInherit",
",",
"'Publisher'",
"]",
":",
"self",
".",
"_inherited_type",
"=",
"type_cls",
"return",
"self"
] | enables the usage of method and attribute overloading for this
publisher. | [
"enables",
"the",
"usage",
"of",
"method",
"and",
"attribute",
"overloading",
"for",
"this",
"publisher",
"."
] | 8957110b034f982451392072d9fa16761adc9c9e | https://github.com/semiversus/python-broqer/blob/8957110b034f982451392072d9fa16761adc9c9e/broqer/publisher.py#L150-L156 | train |
astropy/photutils | photutils/extern/sigma_clipping.py | _move_tuple_axes_first | def _move_tuple_axes_first(array, axis):
"""
Bottleneck can only take integer axis, not tuple, so this function
takes all the axes to be operated on and combines them into the
first dimension of the array so that we can then use axis=0
"""
# Figure out how many axes we are operating over
naxis = len(axis)
# Add remaining axes to the axis tuple
axis += tuple(i for i in range(array.ndim) if i not in axis)
# The new position of each axis is just in order
destination = tuple(range(array.ndim))
# Reorder the array so that the axes being operated on are at the beginning
array_new = np.moveaxis(array, axis, destination)
# Figure out the size of the product of the dimensions being operated on
first = np.prod(array_new.shape[:naxis])
# Collapse the dimensions being operated on into a single dimension so that
# we can then use axis=0 with the bottleneck functions
array_new = array_new.reshape((first,) + array_new.shape[naxis:])
return array_new | python | def _move_tuple_axes_first(array, axis):
"""
Bottleneck can only take integer axis, not tuple, so this function
takes all the axes to be operated on and combines them into the
first dimension of the array so that we can then use axis=0
"""
# Figure out how many axes we are operating over
naxis = len(axis)
# Add remaining axes to the axis tuple
axis += tuple(i for i in range(array.ndim) if i not in axis)
# The new position of each axis is just in order
destination = tuple(range(array.ndim))
# Reorder the array so that the axes being operated on are at the beginning
array_new = np.moveaxis(array, axis, destination)
# Figure out the size of the product of the dimensions being operated on
first = np.prod(array_new.shape[:naxis])
# Collapse the dimensions being operated on into a single dimension so that
# we can then use axis=0 with the bottleneck functions
array_new = array_new.reshape((first,) + array_new.shape[naxis:])
return array_new | [
"def",
"_move_tuple_axes_first",
"(",
"array",
",",
"axis",
")",
":",
"# Figure out how many axes we are operating over",
"naxis",
"=",
"len",
"(",
"axis",
")",
"# Add remaining axes to the axis tuple",
"axis",
"+=",
"tuple",
"(",
"i",
"for",
"i",
"in",
"range",
"(",
"array",
".",
"ndim",
")",
"if",
"i",
"not",
"in",
"axis",
")",
"# The new position of each axis is just in order",
"destination",
"=",
"tuple",
"(",
"range",
"(",
"array",
".",
"ndim",
")",
")",
"# Reorder the array so that the axes being operated on are at the beginning",
"array_new",
"=",
"np",
".",
"moveaxis",
"(",
"array",
",",
"axis",
",",
"destination",
")",
"# Figure out the size of the product of the dimensions being operated on",
"first",
"=",
"np",
".",
"prod",
"(",
"array_new",
".",
"shape",
"[",
":",
"naxis",
"]",
")",
"# Collapse the dimensions being operated on into a single dimension so that",
"# we can then use axis=0 with the bottleneck functions",
"array_new",
"=",
"array_new",
".",
"reshape",
"(",
"(",
"first",
",",
")",
"+",
"array_new",
".",
"shape",
"[",
"naxis",
":",
"]",
")",
"return",
"array_new"
] | Bottleneck can only take integer axis, not tuple, so this function
takes all the axes to be operated on and combines them into the
first dimension of the array so that we can then use axis=0 | [
"Bottleneck",
"can",
"only",
"take",
"integer",
"axis",
"not",
"tuple",
"so",
"this",
"function",
"takes",
"all",
"the",
"axes",
"to",
"be",
"operated",
"on",
"and",
"combines",
"them",
"into",
"the",
"first",
"dimension",
"of",
"the",
"array",
"so",
"that",
"we",
"can",
"then",
"use",
"axis",
"=",
"0"
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L22-L48 | train |
astropy/photutils | photutils/extern/sigma_clipping.py | _nanmean | def _nanmean(array, axis=None):
"""Bottleneck nanmean function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanmean(array, axis=axis) | python | def _nanmean(array, axis=None):
"""Bottleneck nanmean function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanmean(array, axis=axis) | [
"def",
"_nanmean",
"(",
"array",
",",
"axis",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"axis",
",",
"tuple",
")",
":",
"array",
"=",
"_move_tuple_axes_first",
"(",
"array",
",",
"axis",
"=",
"axis",
")",
"axis",
"=",
"0",
"return",
"bottleneck",
".",
"nanmean",
"(",
"array",
",",
"axis",
"=",
"axis",
")"
] | Bottleneck nanmean function that handle tuple axis. | [
"Bottleneck",
"nanmean",
"function",
"that",
"handle",
"tuple",
"axis",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L51-L57 | train |
astropy/photutils | photutils/extern/sigma_clipping.py | _nanmedian | def _nanmedian(array, axis=None):
"""Bottleneck nanmedian function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanmedian(array, axis=axis) | python | def _nanmedian(array, axis=None):
"""Bottleneck nanmedian function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanmedian(array, axis=axis) | [
"def",
"_nanmedian",
"(",
"array",
",",
"axis",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"axis",
",",
"tuple",
")",
":",
"array",
"=",
"_move_tuple_axes_first",
"(",
"array",
",",
"axis",
"=",
"axis",
")",
"axis",
"=",
"0",
"return",
"bottleneck",
".",
"nanmedian",
"(",
"array",
",",
"axis",
"=",
"axis",
")"
] | Bottleneck nanmedian function that handle tuple axis. | [
"Bottleneck",
"nanmedian",
"function",
"that",
"handle",
"tuple",
"axis",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L60-L66 | train |
astropy/photutils | photutils/extern/sigma_clipping.py | _nanstd | def _nanstd(array, axis=None, ddof=0):
"""Bottleneck nanstd function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanstd(array, axis=axis, ddof=ddof) | python | def _nanstd(array, axis=None, ddof=0):
"""Bottleneck nanstd function that handle tuple axis."""
if isinstance(axis, tuple):
array = _move_tuple_axes_first(array, axis=axis)
axis = 0
return bottleneck.nanstd(array, axis=axis, ddof=ddof) | [
"def",
"_nanstd",
"(",
"array",
",",
"axis",
"=",
"None",
",",
"ddof",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"axis",
",",
"tuple",
")",
":",
"array",
"=",
"_move_tuple_axes_first",
"(",
"array",
",",
"axis",
"=",
"axis",
")",
"axis",
"=",
"0",
"return",
"bottleneck",
".",
"nanstd",
"(",
"array",
",",
"axis",
"=",
"axis",
",",
"ddof",
"=",
"ddof",
")"
] | Bottleneck nanstd function that handle tuple axis. | [
"Bottleneck",
"nanstd",
"function",
"that",
"handle",
"tuple",
"axis",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L69-L75 | train |
astropy/photutils | photutils/extern/sigma_clipping.py | sigma_clip | def sigma_clip(data, sigma=3, sigma_lower=None, sigma_upper=None, maxiters=5,
cenfunc='median', stdfunc='std', axis=None, masked=True,
return_bounds=False, copy=True):
"""
Perform sigma-clipping on the provided data.
The data will be iterated over, each time rejecting values that are
less or more than a specified number of standard deviations from a
center value.
Clipped (rejected) pixels are those where::
data < cenfunc(data [,axis=int]) - (sigma_lower * stdfunc(data [,axis=int]))
data > cenfunc(data [,axis=int]) + (sigma_upper * stdfunc(data [,axis=int]))
Invalid data values (i.e. NaN or inf) are automatically clipped.
For an object-oriented interface to sigma clipping, see
:class:`SigmaClip`.
.. note::
`scipy.stats.sigmaclip
<https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sigmaclip.html>`_
provides a subset of the functionality in this class. Also, its
input data cannot be a masked array and it does not handle data
that contains invalid values (i.e. NaN or inf). Also note that
it uses the mean as the centering function.
If your data is a `~numpy.ndarray` with no invalid values and
you want to use the mean as the centering function with
``axis=None`` and iterate to convergence, then
`scipy.stats.sigmaclip` is ~25-30% faster than the equivalent
settings here (``sigma_clip(data, cenfunc='mean', maxiters=None,
axis=None)``).
Parameters
----------
data : array-like or `~numpy.ma.MaskedArray`
The data to be sigma clipped.
sigma : float, optional
The number of standard deviations to use for both the lower and
upper clipping limit. These limits are overridden by
``sigma_lower`` and ``sigma_upper``, if input. The default is
3.
sigma_lower : float or `None`, optional
The number of standard deviations to use as the lower bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
sigma_upper : float or `None`, optional
The number of standard deviations to use as the upper bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
maxiters : int or `None`, optional
The maximum number of sigma-clipping iterations to perform or
`None` to clip until convergence is achieved (i.e., iterate
until the last iteration clips nothing). If convergence is
achieved prior to ``maxiters`` iterations, the clipping
iterations will stop. The default is 5.
cenfunc : {'median', 'mean'} or callable, optional
The statistic or callable function/object used to compute the
center value for the clipping. If set to ``'median'`` or
``'mean'`` then having the optional `bottleneck`_ package
installed will result in the best performance. If using a
callable function/object and the ``axis`` keyword is used, then
it must be callable that can ignore NaNs (e.g. `numpy.nanmean`)
and has an ``axis`` keyword to return an array with axis
dimension(s) removed. The default is ``'median'``.
.. _bottleneck: https://github.com/kwgoodman/bottleneck
stdfunc : {'std'} or callable, optional
The statistic or callable function/object used to compute the
standard deviation about the center value. If set to ``'std'``
then having the optional `bottleneck`_ package installed will
result in the best performance. If using a callable
function/object and the ``axis`` keyword is used, then it must
be callable that can ignore NaNs (e.g. `numpy.nanstd`) and has
an ``axis`` keyword to return an array with axis dimension(s)
removed. The default is ``'std'``.
axis : `None` or int or tuple of int, optional
The axis or axes along which to sigma clip the data. If `None`,
then the flattened data will be used. ``axis`` is passed to the
``cenfunc`` and ``stdfunc``. The default is `None`.
masked : bool, optional
If `True`, then a `~numpy.ma.MaskedArray` is returned, where the
mask is `True` for clipped values. If `False`, then a
`~numpy.ndarray` and the minimum and maximum clipping thresholds
are returned. The default is `True`.
return_bounds : bool, optional
If `True`, then the minimum and maximum clipping bounds are also
returned.
copy : bool, optional
If `True`, then the ``data`` array will be copied. If `False`
and ``masked=True``, then the returned masked array data will
contain the same array as the input ``data`` (if ``data`` is a
`~numpy.ndarray` or `~numpy.ma.MaskedArray`). The default is
`True`.
Returns
-------
result : flexible
If ``masked=True``, then a `~numpy.ma.MaskedArray` is returned,
where the mask is `True` for clipped values. If
``masked=False``, then a `~numpy.ndarray` is returned.
If ``return_bounds=True``, then in addition to the (masked)
array above, the minimum and maximum clipping bounds are
returned.
If ``masked=False`` and ``axis=None``, then the output array is
a flattened 1D `~numpy.ndarray` where the clipped values have
been removed. If ``return_bounds=True`` then the returned
minimum and maximum thresholds are scalars.
If ``masked=False`` and ``axis`` is specified, then the output
`~numpy.ndarray` will have the same shape as the input ``data``
and contain ``np.nan`` where values were clipped. If
``return_bounds=True`` then the returned minimum and maximum
clipping thresholds will be be `~numpy.ndarray`\\s.
See Also
--------
SigmaClip, sigma_clipped_stats
Examples
--------
This example uses a data array of random variates from a Gaussian
distribution. We clip all points that are more than 2 sample
standard deviations from the median. The result is a masked array,
where the mask is `True` for clipped data::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import randn
>>> randvar = randn(10000)
>>> filtered_data = sigma_clip(randvar, sigma=2, maxiters=5)
This example clips all points that are more than 3 sigma relative to
the sample *mean*, clips until convergence, returns an unmasked
`~numpy.ndarray`, and does not copy the data::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import randn
>>> from numpy import mean
>>> randvar = randn(10000)
>>> filtered_data = sigma_clip(randvar, sigma=3, maxiters=None,
... cenfunc=mean, masked=False, copy=False)
This example sigma clips along one axis::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import normal
>>> from numpy import arange, diag, ones
>>> data = arange(5) + normal(0., 0.05, (5, 5)) + diag(ones(5))
>>> filtered_data = sigma_clip(data, sigma=2.3, axis=0)
Note that along the other axis, no points would be clipped, as the
standard deviation is higher.
"""
sigclip = SigmaClip(sigma=sigma, sigma_lower=sigma_lower,
sigma_upper=sigma_upper, maxiters=maxiters,
cenfunc=cenfunc, stdfunc=stdfunc)
return sigclip(data, axis=axis, masked=masked,
return_bounds=return_bounds, copy=copy) | python | def sigma_clip(data, sigma=3, sigma_lower=None, sigma_upper=None, maxiters=5,
cenfunc='median', stdfunc='std', axis=None, masked=True,
return_bounds=False, copy=True):
"""
Perform sigma-clipping on the provided data.
The data will be iterated over, each time rejecting values that are
less or more than a specified number of standard deviations from a
center value.
Clipped (rejected) pixels are those where::
data < cenfunc(data [,axis=int]) - (sigma_lower * stdfunc(data [,axis=int]))
data > cenfunc(data [,axis=int]) + (sigma_upper * stdfunc(data [,axis=int]))
Invalid data values (i.e. NaN or inf) are automatically clipped.
For an object-oriented interface to sigma clipping, see
:class:`SigmaClip`.
.. note::
`scipy.stats.sigmaclip
<https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sigmaclip.html>`_
provides a subset of the functionality in this class. Also, its
input data cannot be a masked array and it does not handle data
that contains invalid values (i.e. NaN or inf). Also note that
it uses the mean as the centering function.
If your data is a `~numpy.ndarray` with no invalid values and
you want to use the mean as the centering function with
``axis=None`` and iterate to convergence, then
`scipy.stats.sigmaclip` is ~25-30% faster than the equivalent
settings here (``sigma_clip(data, cenfunc='mean', maxiters=None,
axis=None)``).
Parameters
----------
data : array-like or `~numpy.ma.MaskedArray`
The data to be sigma clipped.
sigma : float, optional
The number of standard deviations to use for both the lower and
upper clipping limit. These limits are overridden by
``sigma_lower`` and ``sigma_upper``, if input. The default is
3.
sigma_lower : float or `None`, optional
The number of standard deviations to use as the lower bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
sigma_upper : float or `None`, optional
The number of standard deviations to use as the upper bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
maxiters : int or `None`, optional
The maximum number of sigma-clipping iterations to perform or
`None` to clip until convergence is achieved (i.e., iterate
until the last iteration clips nothing). If convergence is
achieved prior to ``maxiters`` iterations, the clipping
iterations will stop. The default is 5.
cenfunc : {'median', 'mean'} or callable, optional
The statistic or callable function/object used to compute the
center value for the clipping. If set to ``'median'`` or
``'mean'`` then having the optional `bottleneck`_ package
installed will result in the best performance. If using a
callable function/object and the ``axis`` keyword is used, then
it must be callable that can ignore NaNs (e.g. `numpy.nanmean`)
and has an ``axis`` keyword to return an array with axis
dimension(s) removed. The default is ``'median'``.
.. _bottleneck: https://github.com/kwgoodman/bottleneck
stdfunc : {'std'} or callable, optional
The statistic or callable function/object used to compute the
standard deviation about the center value. If set to ``'std'``
then having the optional `bottleneck`_ package installed will
result in the best performance. If using a callable
function/object and the ``axis`` keyword is used, then it must
be callable that can ignore NaNs (e.g. `numpy.nanstd`) and has
an ``axis`` keyword to return an array with axis dimension(s)
removed. The default is ``'std'``.
axis : `None` or int or tuple of int, optional
The axis or axes along which to sigma clip the data. If `None`,
then the flattened data will be used. ``axis`` is passed to the
``cenfunc`` and ``stdfunc``. The default is `None`.
masked : bool, optional
If `True`, then a `~numpy.ma.MaskedArray` is returned, where the
mask is `True` for clipped values. If `False`, then a
`~numpy.ndarray` and the minimum and maximum clipping thresholds
are returned. The default is `True`.
return_bounds : bool, optional
If `True`, then the minimum and maximum clipping bounds are also
returned.
copy : bool, optional
If `True`, then the ``data`` array will be copied. If `False`
and ``masked=True``, then the returned masked array data will
contain the same array as the input ``data`` (if ``data`` is a
`~numpy.ndarray` or `~numpy.ma.MaskedArray`). The default is
`True`.
Returns
-------
result : flexible
If ``masked=True``, then a `~numpy.ma.MaskedArray` is returned,
where the mask is `True` for clipped values. If
``masked=False``, then a `~numpy.ndarray` is returned.
If ``return_bounds=True``, then in addition to the (masked)
array above, the minimum and maximum clipping bounds are
returned.
If ``masked=False`` and ``axis=None``, then the output array is
a flattened 1D `~numpy.ndarray` where the clipped values have
been removed. If ``return_bounds=True`` then the returned
minimum and maximum thresholds are scalars.
If ``masked=False`` and ``axis`` is specified, then the output
`~numpy.ndarray` will have the same shape as the input ``data``
and contain ``np.nan`` where values were clipped. If
``return_bounds=True`` then the returned minimum and maximum
clipping thresholds will be be `~numpy.ndarray`\\s.
See Also
--------
SigmaClip, sigma_clipped_stats
Examples
--------
This example uses a data array of random variates from a Gaussian
distribution. We clip all points that are more than 2 sample
standard deviations from the median. The result is a masked array,
where the mask is `True` for clipped data::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import randn
>>> randvar = randn(10000)
>>> filtered_data = sigma_clip(randvar, sigma=2, maxiters=5)
This example clips all points that are more than 3 sigma relative to
the sample *mean*, clips until convergence, returns an unmasked
`~numpy.ndarray`, and does not copy the data::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import randn
>>> from numpy import mean
>>> randvar = randn(10000)
>>> filtered_data = sigma_clip(randvar, sigma=3, maxiters=None,
... cenfunc=mean, masked=False, copy=False)
This example sigma clips along one axis::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import normal
>>> from numpy import arange, diag, ones
>>> data = arange(5) + normal(0., 0.05, (5, 5)) + diag(ones(5))
>>> filtered_data = sigma_clip(data, sigma=2.3, axis=0)
Note that along the other axis, no points would be clipped, as the
standard deviation is higher.
"""
sigclip = SigmaClip(sigma=sigma, sigma_lower=sigma_lower,
sigma_upper=sigma_upper, maxiters=maxiters,
cenfunc=cenfunc, stdfunc=stdfunc)
return sigclip(data, axis=axis, masked=masked,
return_bounds=return_bounds, copy=copy) | [
"def",
"sigma_clip",
"(",
"data",
",",
"sigma",
"=",
"3",
",",
"sigma_lower",
"=",
"None",
",",
"sigma_upper",
"=",
"None",
",",
"maxiters",
"=",
"5",
",",
"cenfunc",
"=",
"'median'",
",",
"stdfunc",
"=",
"'std'",
",",
"axis",
"=",
"None",
",",
"masked",
"=",
"True",
",",
"return_bounds",
"=",
"False",
",",
"copy",
"=",
"True",
")",
":",
"sigclip",
"=",
"SigmaClip",
"(",
"sigma",
"=",
"sigma",
",",
"sigma_lower",
"=",
"sigma_lower",
",",
"sigma_upper",
"=",
"sigma_upper",
",",
"maxiters",
"=",
"maxiters",
",",
"cenfunc",
"=",
"cenfunc",
",",
"stdfunc",
"=",
"stdfunc",
")",
"return",
"sigclip",
"(",
"data",
",",
"axis",
"=",
"axis",
",",
"masked",
"=",
"masked",
",",
"return_bounds",
"=",
"return_bounds",
",",
"copy",
"=",
"copy",
")"
] | Perform sigma-clipping on the provided data.
The data will be iterated over, each time rejecting values that are
less or more than a specified number of standard deviations from a
center value.
Clipped (rejected) pixels are those where::
data < cenfunc(data [,axis=int]) - (sigma_lower * stdfunc(data [,axis=int]))
data > cenfunc(data [,axis=int]) + (sigma_upper * stdfunc(data [,axis=int]))
Invalid data values (i.e. NaN or inf) are automatically clipped.
For an object-oriented interface to sigma clipping, see
:class:`SigmaClip`.
.. note::
`scipy.stats.sigmaclip
<https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sigmaclip.html>`_
provides a subset of the functionality in this class. Also, its
input data cannot be a masked array and it does not handle data
that contains invalid values (i.e. NaN or inf). Also note that
it uses the mean as the centering function.
If your data is a `~numpy.ndarray` with no invalid values and
you want to use the mean as the centering function with
``axis=None`` and iterate to convergence, then
`scipy.stats.sigmaclip` is ~25-30% faster than the equivalent
settings here (``sigma_clip(data, cenfunc='mean', maxiters=None,
axis=None)``).
Parameters
----------
data : array-like or `~numpy.ma.MaskedArray`
The data to be sigma clipped.
sigma : float, optional
The number of standard deviations to use for both the lower and
upper clipping limit. These limits are overridden by
``sigma_lower`` and ``sigma_upper``, if input. The default is
3.
sigma_lower : float or `None`, optional
The number of standard deviations to use as the lower bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
sigma_upper : float or `None`, optional
The number of standard deviations to use as the upper bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
maxiters : int or `None`, optional
The maximum number of sigma-clipping iterations to perform or
`None` to clip until convergence is achieved (i.e., iterate
until the last iteration clips nothing). If convergence is
achieved prior to ``maxiters`` iterations, the clipping
iterations will stop. The default is 5.
cenfunc : {'median', 'mean'} or callable, optional
The statistic or callable function/object used to compute the
center value for the clipping. If set to ``'median'`` or
``'mean'`` then having the optional `bottleneck`_ package
installed will result in the best performance. If using a
callable function/object and the ``axis`` keyword is used, then
it must be callable that can ignore NaNs (e.g. `numpy.nanmean`)
and has an ``axis`` keyword to return an array with axis
dimension(s) removed. The default is ``'median'``.
.. _bottleneck: https://github.com/kwgoodman/bottleneck
stdfunc : {'std'} or callable, optional
The statistic or callable function/object used to compute the
standard deviation about the center value. If set to ``'std'``
then having the optional `bottleneck`_ package installed will
result in the best performance. If using a callable
function/object and the ``axis`` keyword is used, then it must
be callable that can ignore NaNs (e.g. `numpy.nanstd`) and has
an ``axis`` keyword to return an array with axis dimension(s)
removed. The default is ``'std'``.
axis : `None` or int or tuple of int, optional
The axis or axes along which to sigma clip the data. If `None`,
then the flattened data will be used. ``axis`` is passed to the
``cenfunc`` and ``stdfunc``. The default is `None`.
masked : bool, optional
If `True`, then a `~numpy.ma.MaskedArray` is returned, where the
mask is `True` for clipped values. If `False`, then a
`~numpy.ndarray` and the minimum and maximum clipping thresholds
are returned. The default is `True`.
return_bounds : bool, optional
If `True`, then the minimum and maximum clipping bounds are also
returned.
copy : bool, optional
If `True`, then the ``data`` array will be copied. If `False`
and ``masked=True``, then the returned masked array data will
contain the same array as the input ``data`` (if ``data`` is a
`~numpy.ndarray` or `~numpy.ma.MaskedArray`). The default is
`True`.
Returns
-------
result : flexible
If ``masked=True``, then a `~numpy.ma.MaskedArray` is returned,
where the mask is `True` for clipped values. If
``masked=False``, then a `~numpy.ndarray` is returned.
If ``return_bounds=True``, then in addition to the (masked)
array above, the minimum and maximum clipping bounds are
returned.
If ``masked=False`` and ``axis=None``, then the output array is
a flattened 1D `~numpy.ndarray` where the clipped values have
been removed. If ``return_bounds=True`` then the returned
minimum and maximum thresholds are scalars.
If ``masked=False`` and ``axis`` is specified, then the output
`~numpy.ndarray` will have the same shape as the input ``data``
and contain ``np.nan`` where values were clipped. If
``return_bounds=True`` then the returned minimum and maximum
clipping thresholds will be be `~numpy.ndarray`\\s.
See Also
--------
SigmaClip, sigma_clipped_stats
Examples
--------
This example uses a data array of random variates from a Gaussian
distribution. We clip all points that are more than 2 sample
standard deviations from the median. The result is a masked array,
where the mask is `True` for clipped data::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import randn
>>> randvar = randn(10000)
>>> filtered_data = sigma_clip(randvar, sigma=2, maxiters=5)
This example clips all points that are more than 3 sigma relative to
the sample *mean*, clips until convergence, returns an unmasked
`~numpy.ndarray`, and does not copy the data::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import randn
>>> from numpy import mean
>>> randvar = randn(10000)
>>> filtered_data = sigma_clip(randvar, sigma=3, maxiters=None,
... cenfunc=mean, masked=False, copy=False)
This example sigma clips along one axis::
>>> from astropy.stats import sigma_clip
>>> from numpy.random import normal
>>> from numpy import arange, diag, ones
>>> data = arange(5) + normal(0., 0.05, (5, 5)) + diag(ones(5))
>>> filtered_data = sigma_clip(data, sigma=2.3, axis=0)
Note that along the other axis, no points would be clipped, as the
standard deviation is higher. | [
"Perform",
"sigma",
"-",
"clipping",
"on",
"the",
"provided",
"data",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L467-L640 | train |
astropy/photutils | photutils/extern/sigma_clipping.py | sigma_clipped_stats | def sigma_clipped_stats(data, mask=None, mask_value=None, sigma=3.0,
sigma_lower=None, sigma_upper=None, maxiters=5,
cenfunc='median', stdfunc='std', std_ddof=0,
axis=None):
"""
Calculate sigma-clipped statistics on the provided data.
Parameters
----------
data : array-like or `~numpy.ma.MaskedArray`
Data array or object that can be converted to an array.
mask : `numpy.ndarray` (bool), optional
A boolean mask with the same shape as ``data``, where a `True`
value indicates the corresponding element of ``data`` is masked.
Masked pixels are excluded when computing the statistics.
mask_value : float, optional
A data value (e.g., ``0.0``) that is ignored when computing the
statistics. ``mask_value`` will be masked in addition to any
input ``mask``.
sigma : float, optional
The number of standard deviations to use for both the lower and
upper clipping limit. These limits are overridden by
``sigma_lower`` and ``sigma_upper``, if input. The default is
3.
sigma_lower : float or `None`, optional
The number of standard deviations to use as the lower bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
sigma_upper : float or `None`, optional
The number of standard deviations to use as the upper bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
maxiters : int or `None`, optional
The maximum number of sigma-clipping iterations to perform or
`None` to clip until convergence is achieved (i.e., iterate
until the last iteration clips nothing). If convergence is
achieved prior to ``maxiters`` iterations, the clipping
iterations will stop. The default is 5.
cenfunc : {'median', 'mean'} or callable, optional
The statistic or callable function/object used to compute the
center value for the clipping. If set to ``'median'`` or
``'mean'`` then having the optional `bottleneck`_ package
installed will result in the best performance. If using a
callable function/object and the ``axis`` keyword is used, then
it must be callable that can ignore NaNs (e.g. `numpy.nanmean`)
and has an ``axis`` keyword to return an array with axis
dimension(s) removed. The default is ``'median'``.
.. _bottleneck: https://github.com/kwgoodman/bottleneck
stdfunc : {'std'} or callable, optional
The statistic or callable function/object used to compute the
standard deviation about the center value. If set to ``'std'``
then having the optional `bottleneck`_ package installed will
result in the best performance. If using a callable
function/object and the ``axis`` keyword is used, then it must
be callable that can ignore NaNs (e.g. `numpy.nanstd`) and has
an ``axis`` keyword to return an array with axis dimension(s)
removed. The default is ``'std'``.
std_ddof : int, optional
The delta degrees of freedom for the standard deviation
calculation. The divisor used in the calculation is ``N -
std_ddof``, where ``N`` represents the number of elements. The
default is 0.
axis : `None` or int or tuple of int, optional
The axis or axes along which to sigma clip the data. If `None`,
then the flattened data will be used. ``axis`` is passed
to the ``cenfunc`` and ``stdfunc``. The default is `None`.
Returns
-------
mean, median, stddev : float
The mean, median, and standard deviation of the sigma-clipped
data.
See Also
--------
SigmaClip, sigma_clip
"""
if mask is not None:
data = np.ma.MaskedArray(data, mask)
if mask_value is not None:
data = np.ma.masked_values(data, mask_value)
sigclip = SigmaClip(sigma=sigma, sigma_lower=sigma_lower,
sigma_upper=sigma_upper, maxiters=maxiters,
cenfunc=cenfunc, stdfunc=stdfunc)
data_clipped = sigclip(data, axis=axis, masked=False, return_bounds=False,
copy=False)
if HAS_BOTTLENECK:
mean = _nanmean(data_clipped, axis=axis)
median = _nanmedian(data_clipped, axis=axis)
std = _nanstd(data_clipped, ddof=std_ddof, axis=axis)
else: # pragma: no cover
mean = np.nanmean(data_clipped, axis=axis)
median = np.nanmedian(data_clipped, axis=axis)
std = np.nanstd(data_clipped, ddof=std_ddof, axis=axis)
return mean, median, std | python | def sigma_clipped_stats(data, mask=None, mask_value=None, sigma=3.0,
sigma_lower=None, sigma_upper=None, maxiters=5,
cenfunc='median', stdfunc='std', std_ddof=0,
axis=None):
"""
Calculate sigma-clipped statistics on the provided data.
Parameters
----------
data : array-like or `~numpy.ma.MaskedArray`
Data array or object that can be converted to an array.
mask : `numpy.ndarray` (bool), optional
A boolean mask with the same shape as ``data``, where a `True`
value indicates the corresponding element of ``data`` is masked.
Masked pixels are excluded when computing the statistics.
mask_value : float, optional
A data value (e.g., ``0.0``) that is ignored when computing the
statistics. ``mask_value`` will be masked in addition to any
input ``mask``.
sigma : float, optional
The number of standard deviations to use for both the lower and
upper clipping limit. These limits are overridden by
``sigma_lower`` and ``sigma_upper``, if input. The default is
3.
sigma_lower : float or `None`, optional
The number of standard deviations to use as the lower bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
sigma_upper : float or `None`, optional
The number of standard deviations to use as the upper bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
maxiters : int or `None`, optional
The maximum number of sigma-clipping iterations to perform or
`None` to clip until convergence is achieved (i.e., iterate
until the last iteration clips nothing). If convergence is
achieved prior to ``maxiters`` iterations, the clipping
iterations will stop. The default is 5.
cenfunc : {'median', 'mean'} or callable, optional
The statistic or callable function/object used to compute the
center value for the clipping. If set to ``'median'`` or
``'mean'`` then having the optional `bottleneck`_ package
installed will result in the best performance. If using a
callable function/object and the ``axis`` keyword is used, then
it must be callable that can ignore NaNs (e.g. `numpy.nanmean`)
and has an ``axis`` keyword to return an array with axis
dimension(s) removed. The default is ``'median'``.
.. _bottleneck: https://github.com/kwgoodman/bottleneck
stdfunc : {'std'} or callable, optional
The statistic or callable function/object used to compute the
standard deviation about the center value. If set to ``'std'``
then having the optional `bottleneck`_ package installed will
result in the best performance. If using a callable
function/object and the ``axis`` keyword is used, then it must
be callable that can ignore NaNs (e.g. `numpy.nanstd`) and has
an ``axis`` keyword to return an array with axis dimension(s)
removed. The default is ``'std'``.
std_ddof : int, optional
The delta degrees of freedom for the standard deviation
calculation. The divisor used in the calculation is ``N -
std_ddof``, where ``N`` represents the number of elements. The
default is 0.
axis : `None` or int or tuple of int, optional
The axis or axes along which to sigma clip the data. If `None`,
then the flattened data will be used. ``axis`` is passed
to the ``cenfunc`` and ``stdfunc``. The default is `None`.
Returns
-------
mean, median, stddev : float
The mean, median, and standard deviation of the sigma-clipped
data.
See Also
--------
SigmaClip, sigma_clip
"""
if mask is not None:
data = np.ma.MaskedArray(data, mask)
if mask_value is not None:
data = np.ma.masked_values(data, mask_value)
sigclip = SigmaClip(sigma=sigma, sigma_lower=sigma_lower,
sigma_upper=sigma_upper, maxiters=maxiters,
cenfunc=cenfunc, stdfunc=stdfunc)
data_clipped = sigclip(data, axis=axis, masked=False, return_bounds=False,
copy=False)
if HAS_BOTTLENECK:
mean = _nanmean(data_clipped, axis=axis)
median = _nanmedian(data_clipped, axis=axis)
std = _nanstd(data_clipped, ddof=std_ddof, axis=axis)
else: # pragma: no cover
mean = np.nanmean(data_clipped, axis=axis)
median = np.nanmedian(data_clipped, axis=axis)
std = np.nanstd(data_clipped, ddof=std_ddof, axis=axis)
return mean, median, std | [
"def",
"sigma_clipped_stats",
"(",
"data",
",",
"mask",
"=",
"None",
",",
"mask_value",
"=",
"None",
",",
"sigma",
"=",
"3.0",
",",
"sigma_lower",
"=",
"None",
",",
"sigma_upper",
"=",
"None",
",",
"maxiters",
"=",
"5",
",",
"cenfunc",
"=",
"'median'",
",",
"stdfunc",
"=",
"'std'",
",",
"std_ddof",
"=",
"0",
",",
"axis",
"=",
"None",
")",
":",
"if",
"mask",
"is",
"not",
"None",
":",
"data",
"=",
"np",
".",
"ma",
".",
"MaskedArray",
"(",
"data",
",",
"mask",
")",
"if",
"mask_value",
"is",
"not",
"None",
":",
"data",
"=",
"np",
".",
"ma",
".",
"masked_values",
"(",
"data",
",",
"mask_value",
")",
"sigclip",
"=",
"SigmaClip",
"(",
"sigma",
"=",
"sigma",
",",
"sigma_lower",
"=",
"sigma_lower",
",",
"sigma_upper",
"=",
"sigma_upper",
",",
"maxiters",
"=",
"maxiters",
",",
"cenfunc",
"=",
"cenfunc",
",",
"stdfunc",
"=",
"stdfunc",
")",
"data_clipped",
"=",
"sigclip",
"(",
"data",
",",
"axis",
"=",
"axis",
",",
"masked",
"=",
"False",
",",
"return_bounds",
"=",
"False",
",",
"copy",
"=",
"False",
")",
"if",
"HAS_BOTTLENECK",
":",
"mean",
"=",
"_nanmean",
"(",
"data_clipped",
",",
"axis",
"=",
"axis",
")",
"median",
"=",
"_nanmedian",
"(",
"data_clipped",
",",
"axis",
"=",
"axis",
")",
"std",
"=",
"_nanstd",
"(",
"data_clipped",
",",
"ddof",
"=",
"std_ddof",
",",
"axis",
"=",
"axis",
")",
"else",
":",
"# pragma: no cover",
"mean",
"=",
"np",
".",
"nanmean",
"(",
"data_clipped",
",",
"axis",
"=",
"axis",
")",
"median",
"=",
"np",
".",
"nanmedian",
"(",
"data_clipped",
",",
"axis",
"=",
"axis",
")",
"std",
"=",
"np",
".",
"nanstd",
"(",
"data_clipped",
",",
"ddof",
"=",
"std_ddof",
",",
"axis",
"=",
"axis",
")",
"return",
"mean",
",",
"median",
",",
"std"
] | Calculate sigma-clipped statistics on the provided data.
Parameters
----------
data : array-like or `~numpy.ma.MaskedArray`
Data array or object that can be converted to an array.
mask : `numpy.ndarray` (bool), optional
A boolean mask with the same shape as ``data``, where a `True`
value indicates the corresponding element of ``data`` is masked.
Masked pixels are excluded when computing the statistics.
mask_value : float, optional
A data value (e.g., ``0.0``) that is ignored when computing the
statistics. ``mask_value`` will be masked in addition to any
input ``mask``.
sigma : float, optional
The number of standard deviations to use for both the lower and
upper clipping limit. These limits are overridden by
``sigma_lower`` and ``sigma_upper``, if input. The default is
3.
sigma_lower : float or `None`, optional
The number of standard deviations to use as the lower bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
sigma_upper : float or `None`, optional
The number of standard deviations to use as the upper bound for
the clipping limit. If `None` then the value of ``sigma`` is
used. The default is `None`.
maxiters : int or `None`, optional
The maximum number of sigma-clipping iterations to perform or
`None` to clip until convergence is achieved (i.e., iterate
until the last iteration clips nothing). If convergence is
achieved prior to ``maxiters`` iterations, the clipping
iterations will stop. The default is 5.
cenfunc : {'median', 'mean'} or callable, optional
The statistic or callable function/object used to compute the
center value for the clipping. If set to ``'median'`` or
``'mean'`` then having the optional `bottleneck`_ package
installed will result in the best performance. If using a
callable function/object and the ``axis`` keyword is used, then
it must be callable that can ignore NaNs (e.g. `numpy.nanmean`)
and has an ``axis`` keyword to return an array with axis
dimension(s) removed. The default is ``'median'``.
.. _bottleneck: https://github.com/kwgoodman/bottleneck
stdfunc : {'std'} or callable, optional
The statistic or callable function/object used to compute the
standard deviation about the center value. If set to ``'std'``
then having the optional `bottleneck`_ package installed will
result in the best performance. If using a callable
function/object and the ``axis`` keyword is used, then it must
be callable that can ignore NaNs (e.g. `numpy.nanstd`) and has
an ``axis`` keyword to return an array with axis dimension(s)
removed. The default is ``'std'``.
std_ddof : int, optional
The delta degrees of freedom for the standard deviation
calculation. The divisor used in the calculation is ``N -
std_ddof``, where ``N`` represents the number of elements. The
default is 0.
axis : `None` or int or tuple of int, optional
The axis or axes along which to sigma clip the data. If `None`,
then the flattened data will be used. ``axis`` is passed
to the ``cenfunc`` and ``stdfunc``. The default is `None`.
Returns
-------
mean, median, stddev : float
The mean, median, and standard deviation of the sigma-clipped
data.
See Also
--------
SigmaClip, sigma_clip | [
"Calculate",
"sigma",
"-",
"clipped",
"statistics",
"on",
"the",
"provided",
"data",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L644-L753 | train |
astropy/photutils | photutils/extern/sigma_clipping.py | SigmaClip._sigmaclip_noaxis | def _sigmaclip_noaxis(self, data, masked=True, return_bounds=False,
copy=True):
"""
Sigma clip the data when ``axis`` is None.
In this simple case, we remove clipped elements from the
flattened array during each iteration.
"""
filtered_data = data.ravel()
# remove masked values and convert to ndarray
if isinstance(filtered_data, np.ma.MaskedArray):
filtered_data = filtered_data.data[~filtered_data.mask]
# remove invalid values
good_mask = np.isfinite(filtered_data)
if np.any(~good_mask):
filtered_data = filtered_data[good_mask]
warnings.warn('Input data contains invalid values (NaNs or '
'infs), which were automatically clipped.',
AstropyUserWarning)
nchanged = 1
iteration = 0
while nchanged != 0 and (iteration < self.maxiters):
iteration += 1
size = filtered_data.size
self._compute_bounds(filtered_data, axis=None)
filtered_data = filtered_data[(filtered_data >= self._min_value) &
(filtered_data <= self._max_value)]
nchanged = size - filtered_data.size
self._niterations = iteration
if masked:
# return a masked array and optional bounds
filtered_data = np.ma.masked_invalid(data, copy=copy)
# update the mask in place, ignoring RuntimeWarnings for
# comparisons with NaN data values
with np.errstate(invalid='ignore'):
filtered_data.mask |= np.logical_or(data < self._min_value,
data > self._max_value)
if return_bounds:
return filtered_data, self._min_value, self._max_value
else:
return filtered_data | python | def _sigmaclip_noaxis(self, data, masked=True, return_bounds=False,
copy=True):
"""
Sigma clip the data when ``axis`` is None.
In this simple case, we remove clipped elements from the
flattened array during each iteration.
"""
filtered_data = data.ravel()
# remove masked values and convert to ndarray
if isinstance(filtered_data, np.ma.MaskedArray):
filtered_data = filtered_data.data[~filtered_data.mask]
# remove invalid values
good_mask = np.isfinite(filtered_data)
if np.any(~good_mask):
filtered_data = filtered_data[good_mask]
warnings.warn('Input data contains invalid values (NaNs or '
'infs), which were automatically clipped.',
AstropyUserWarning)
nchanged = 1
iteration = 0
while nchanged != 0 and (iteration < self.maxiters):
iteration += 1
size = filtered_data.size
self._compute_bounds(filtered_data, axis=None)
filtered_data = filtered_data[(filtered_data >= self._min_value) &
(filtered_data <= self._max_value)]
nchanged = size - filtered_data.size
self._niterations = iteration
if masked:
# return a masked array and optional bounds
filtered_data = np.ma.masked_invalid(data, copy=copy)
# update the mask in place, ignoring RuntimeWarnings for
# comparisons with NaN data values
with np.errstate(invalid='ignore'):
filtered_data.mask |= np.logical_or(data < self._min_value,
data > self._max_value)
if return_bounds:
return filtered_data, self._min_value, self._max_value
else:
return filtered_data | [
"def",
"_sigmaclip_noaxis",
"(",
"self",
",",
"data",
",",
"masked",
"=",
"True",
",",
"return_bounds",
"=",
"False",
",",
"copy",
"=",
"True",
")",
":",
"filtered_data",
"=",
"data",
".",
"ravel",
"(",
")",
"# remove masked values and convert to ndarray",
"if",
"isinstance",
"(",
"filtered_data",
",",
"np",
".",
"ma",
".",
"MaskedArray",
")",
":",
"filtered_data",
"=",
"filtered_data",
".",
"data",
"[",
"~",
"filtered_data",
".",
"mask",
"]",
"# remove invalid values",
"good_mask",
"=",
"np",
".",
"isfinite",
"(",
"filtered_data",
")",
"if",
"np",
".",
"any",
"(",
"~",
"good_mask",
")",
":",
"filtered_data",
"=",
"filtered_data",
"[",
"good_mask",
"]",
"warnings",
".",
"warn",
"(",
"'Input data contains invalid values (NaNs or '",
"'infs), which were automatically clipped.'",
",",
"AstropyUserWarning",
")",
"nchanged",
"=",
"1",
"iteration",
"=",
"0",
"while",
"nchanged",
"!=",
"0",
"and",
"(",
"iteration",
"<",
"self",
".",
"maxiters",
")",
":",
"iteration",
"+=",
"1",
"size",
"=",
"filtered_data",
".",
"size",
"self",
".",
"_compute_bounds",
"(",
"filtered_data",
",",
"axis",
"=",
"None",
")",
"filtered_data",
"=",
"filtered_data",
"[",
"(",
"filtered_data",
">=",
"self",
".",
"_min_value",
")",
"&",
"(",
"filtered_data",
"<=",
"self",
".",
"_max_value",
")",
"]",
"nchanged",
"=",
"size",
"-",
"filtered_data",
".",
"size",
"self",
".",
"_niterations",
"=",
"iteration",
"if",
"masked",
":",
"# return a masked array and optional bounds",
"filtered_data",
"=",
"np",
".",
"ma",
".",
"masked_invalid",
"(",
"data",
",",
"copy",
"=",
"copy",
")",
"# update the mask in place, ignoring RuntimeWarnings for",
"# comparisons with NaN data values",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"filtered_data",
".",
"mask",
"|=",
"np",
".",
"logical_or",
"(",
"data",
"<",
"self",
".",
"_min_value",
",",
"data",
">",
"self",
".",
"_max_value",
")",
"if",
"return_bounds",
":",
"return",
"filtered_data",
",",
"self",
".",
"_min_value",
",",
"self",
".",
"_max_value",
"else",
":",
"return",
"filtered_data"
] | Sigma clip the data when ``axis`` is None.
In this simple case, we remove clipped elements from the
flattened array during each iteration. | [
"Sigma",
"clip",
"the",
"data",
"when",
"axis",
"is",
"None",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L265-L313 | train |
astropy/photutils | photutils/extern/sigma_clipping.py | SigmaClip._sigmaclip_withaxis | def _sigmaclip_withaxis(self, data, axis=None, masked=True,
return_bounds=False, copy=True):
"""
Sigma clip the data when ``axis`` is specified.
In this case, we replace clipped values with NaNs as placeholder
values.
"""
# float array type is needed to insert nans into the array
filtered_data = data.astype(float) # also makes a copy
# remove invalid values
bad_mask = ~np.isfinite(filtered_data)
if np.any(bad_mask):
filtered_data[bad_mask] = np.nan
warnings.warn('Input data contains invalid values (NaNs or '
'infs), which were automatically clipped.',
AstropyUserWarning)
# remove masked values and convert to plain ndarray
if isinstance(filtered_data, np.ma.MaskedArray):
filtered_data = np.ma.masked_invalid(filtered_data).astype(float)
filtered_data = filtered_data.filled(np.nan)
# convert negative axis/axes
if not isiterable(axis):
axis = (axis,)
axis = tuple(filtered_data.ndim + n if n < 0 else n for n in axis)
# define the shape of min/max arrays so that they can be broadcast
# with the data
mshape = tuple(1 if dim in axis else size
for dim, size in enumerate(filtered_data.shape))
nchanged = 1
iteration = 0
while nchanged != 0 and (iteration < self.maxiters):
iteration += 1
n_nan = np.count_nonzero(np.isnan(filtered_data))
self._compute_bounds(filtered_data, axis=axis)
if not np.isscalar(self._min_value):
self._min_value = self._min_value.reshape(mshape)
self._max_value = self._max_value.reshape(mshape)
with np.errstate(invalid='ignore'):
filtered_data[(filtered_data < self._min_value) |
(filtered_data > self._max_value)] = np.nan
nchanged = n_nan - np.count_nonzero(np.isnan(filtered_data))
self._niterations = iteration
if masked:
# create an output masked array
if copy:
filtered_data = np.ma.masked_invalid(filtered_data)
else:
# ignore RuntimeWarnings for comparisons with NaN data values
with np.errstate(invalid='ignore'):
out = np.ma.masked_invalid(data, copy=False)
filtered_data = np.ma.masked_where(np.logical_or(
out < self._min_value, out > self._max_value),
out, copy=False)
if return_bounds:
return filtered_data, self._min_value, self._max_value
else:
return filtered_data | python | def _sigmaclip_withaxis(self, data, axis=None, masked=True,
return_bounds=False, copy=True):
"""
Sigma clip the data when ``axis`` is specified.
In this case, we replace clipped values with NaNs as placeholder
values.
"""
# float array type is needed to insert nans into the array
filtered_data = data.astype(float) # also makes a copy
# remove invalid values
bad_mask = ~np.isfinite(filtered_data)
if np.any(bad_mask):
filtered_data[bad_mask] = np.nan
warnings.warn('Input data contains invalid values (NaNs or '
'infs), which were automatically clipped.',
AstropyUserWarning)
# remove masked values and convert to plain ndarray
if isinstance(filtered_data, np.ma.MaskedArray):
filtered_data = np.ma.masked_invalid(filtered_data).astype(float)
filtered_data = filtered_data.filled(np.nan)
# convert negative axis/axes
if not isiterable(axis):
axis = (axis,)
axis = tuple(filtered_data.ndim + n if n < 0 else n for n in axis)
# define the shape of min/max arrays so that they can be broadcast
# with the data
mshape = tuple(1 if dim in axis else size
for dim, size in enumerate(filtered_data.shape))
nchanged = 1
iteration = 0
while nchanged != 0 and (iteration < self.maxiters):
iteration += 1
n_nan = np.count_nonzero(np.isnan(filtered_data))
self._compute_bounds(filtered_data, axis=axis)
if not np.isscalar(self._min_value):
self._min_value = self._min_value.reshape(mshape)
self._max_value = self._max_value.reshape(mshape)
with np.errstate(invalid='ignore'):
filtered_data[(filtered_data < self._min_value) |
(filtered_data > self._max_value)] = np.nan
nchanged = n_nan - np.count_nonzero(np.isnan(filtered_data))
self._niterations = iteration
if masked:
# create an output masked array
if copy:
filtered_data = np.ma.masked_invalid(filtered_data)
else:
# ignore RuntimeWarnings for comparisons with NaN data values
with np.errstate(invalid='ignore'):
out = np.ma.masked_invalid(data, copy=False)
filtered_data = np.ma.masked_where(np.logical_or(
out < self._min_value, out > self._max_value),
out, copy=False)
if return_bounds:
return filtered_data, self._min_value, self._max_value
else:
return filtered_data | [
"def",
"_sigmaclip_withaxis",
"(",
"self",
",",
"data",
",",
"axis",
"=",
"None",
",",
"masked",
"=",
"True",
",",
"return_bounds",
"=",
"False",
",",
"copy",
"=",
"True",
")",
":",
"# float array type is needed to insert nans into the array",
"filtered_data",
"=",
"data",
".",
"astype",
"(",
"float",
")",
"# also makes a copy",
"# remove invalid values",
"bad_mask",
"=",
"~",
"np",
".",
"isfinite",
"(",
"filtered_data",
")",
"if",
"np",
".",
"any",
"(",
"bad_mask",
")",
":",
"filtered_data",
"[",
"bad_mask",
"]",
"=",
"np",
".",
"nan",
"warnings",
".",
"warn",
"(",
"'Input data contains invalid values (NaNs or '",
"'infs), which were automatically clipped.'",
",",
"AstropyUserWarning",
")",
"# remove masked values and convert to plain ndarray",
"if",
"isinstance",
"(",
"filtered_data",
",",
"np",
".",
"ma",
".",
"MaskedArray",
")",
":",
"filtered_data",
"=",
"np",
".",
"ma",
".",
"masked_invalid",
"(",
"filtered_data",
")",
".",
"astype",
"(",
"float",
")",
"filtered_data",
"=",
"filtered_data",
".",
"filled",
"(",
"np",
".",
"nan",
")",
"# convert negative axis/axes",
"if",
"not",
"isiterable",
"(",
"axis",
")",
":",
"axis",
"=",
"(",
"axis",
",",
")",
"axis",
"=",
"tuple",
"(",
"filtered_data",
".",
"ndim",
"+",
"n",
"if",
"n",
"<",
"0",
"else",
"n",
"for",
"n",
"in",
"axis",
")",
"# define the shape of min/max arrays so that they can be broadcast",
"# with the data",
"mshape",
"=",
"tuple",
"(",
"1",
"if",
"dim",
"in",
"axis",
"else",
"size",
"for",
"dim",
",",
"size",
"in",
"enumerate",
"(",
"filtered_data",
".",
"shape",
")",
")",
"nchanged",
"=",
"1",
"iteration",
"=",
"0",
"while",
"nchanged",
"!=",
"0",
"and",
"(",
"iteration",
"<",
"self",
".",
"maxiters",
")",
":",
"iteration",
"+=",
"1",
"n_nan",
"=",
"np",
".",
"count_nonzero",
"(",
"np",
".",
"isnan",
"(",
"filtered_data",
")",
")",
"self",
".",
"_compute_bounds",
"(",
"filtered_data",
",",
"axis",
"=",
"axis",
")",
"if",
"not",
"np",
".",
"isscalar",
"(",
"self",
".",
"_min_value",
")",
":",
"self",
".",
"_min_value",
"=",
"self",
".",
"_min_value",
".",
"reshape",
"(",
"mshape",
")",
"self",
".",
"_max_value",
"=",
"self",
".",
"_max_value",
".",
"reshape",
"(",
"mshape",
")",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"filtered_data",
"[",
"(",
"filtered_data",
"<",
"self",
".",
"_min_value",
")",
"|",
"(",
"filtered_data",
">",
"self",
".",
"_max_value",
")",
"]",
"=",
"np",
".",
"nan",
"nchanged",
"=",
"n_nan",
"-",
"np",
".",
"count_nonzero",
"(",
"np",
".",
"isnan",
"(",
"filtered_data",
")",
")",
"self",
".",
"_niterations",
"=",
"iteration",
"if",
"masked",
":",
"# create an output masked array",
"if",
"copy",
":",
"filtered_data",
"=",
"np",
".",
"ma",
".",
"masked_invalid",
"(",
"filtered_data",
")",
"else",
":",
"# ignore RuntimeWarnings for comparisons with NaN data values",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"out",
"=",
"np",
".",
"ma",
".",
"masked_invalid",
"(",
"data",
",",
"copy",
"=",
"False",
")",
"filtered_data",
"=",
"np",
".",
"ma",
".",
"masked_where",
"(",
"np",
".",
"logical_or",
"(",
"out",
"<",
"self",
".",
"_min_value",
",",
"out",
">",
"self",
".",
"_max_value",
")",
",",
"out",
",",
"copy",
"=",
"False",
")",
"if",
"return_bounds",
":",
"return",
"filtered_data",
",",
"self",
".",
"_min_value",
",",
"self",
".",
"_max_value",
"else",
":",
"return",
"filtered_data"
] | Sigma clip the data when ``axis`` is specified.
In this case, we replace clipped values with NaNs as placeholder
values. | [
"Sigma",
"clip",
"the",
"data",
"when",
"axis",
"is",
"specified",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/extern/sigma_clipping.py#L315-L385 | train |
astropy/photutils | photutils/aperture/core.py | PixelAperture.do_photometry | def do_photometry(self, data, error=None, mask=None, method='exact',
subpixels=5, unit=None):
"""
Perform aperture photometry on the input data.
Parameters
----------
data : array_like or `~astropy.units.Quantity` instance
The 2D array on which to perform photometry. ``data``
should be background subtracted.
error : array_like or `~astropy.units.Quantity`, optional
The pixel-wise Gaussian 1-sigma errors of the input
``data``. ``error`` is assumed to include *all* sources of
error, including the Poisson error of the sources (see
`~photutils.utils.calc_total_error`) . ``error`` must have
the same shape as the input ``data``.
mask : array_like (bool), optional
A boolean mask with the same shape as ``data`` where a
`True` value indicates the corresponding element of ``data``
is masked. Masked data are excluded from all calculations.
method : {'exact', 'center', 'subpixel'}, optional
The method used to determine the overlap of the aperture on
the pixel grid. Not all options are available for all
aperture types. Note that the more precise methods are
generally slower. The following methods are available:
* ``'exact'`` (default):
The the exact fractional overlap of the aperture and
each pixel is calculated. The returned mask will
contain values between 0 and 1.
* ``'center'``:
A pixel is considered to be entirely in or out of the
aperture depending on whether its center is in or out
of the aperture. The returned mask will contain
values only of 0 (out) and 1 (in).
* ``'subpixel'``
A pixel is divided into subpixels (see the
``subpixels`` keyword), each of which are considered
to be entirely in or out of the aperture depending on
whether its center is in or out of the aperture. If
``subpixels=1``, this method is equivalent to
``'center'``. The returned mask will contain values
between 0 and 1.
subpixels : int, optional
For the ``'subpixel'`` method, resample pixels by this factor
in each dimension. That is, each pixel is divided into
``subpixels ** 2`` subpixels.
unit : `~astropy.units.UnitBase` object or str, optional
An object that represents the unit associated with the input
``data`` and ``error`` arrays. Must be a
`~astropy.units.UnitBase` object or a string parseable by
the :mod:`~astropy.units` package. If ``data`` or ``error``
already have a different unit, the input ``unit`` will not
be used and a warning will be raised.
Returns
-------
aperture_sums : `~numpy.ndarray` or `~astropy.units.Quantity`
The sums within each aperture.
aperture_sum_errs : `~numpy.ndarray` or `~astropy.units.Quantity`
The errors on the sums within each aperture.
"""
data = np.asanyarray(data)
if mask is not None:
mask = np.asanyarray(mask)
data = copy.deepcopy(data) # do not modify input data
data[mask] = 0
if error is not None:
# do not modify input data
error = copy.deepcopy(np.asanyarray(error))
error[mask] = 0.
aperture_sums = []
aperture_sum_errs = []
for mask in self.to_mask(method=method, subpixels=subpixels):
data_cutout = mask.cutout(data)
if data_cutout is None:
aperture_sums.append(np.nan)
else:
aperture_sums.append(np.sum(data_cutout * mask.data))
if error is not None:
error_cutout = mask.cutout(error)
if error_cutout is None:
aperture_sum_errs.append(np.nan)
else:
aperture_var = np.sum(error_cutout ** 2 * mask.data)
aperture_sum_errs.append(np.sqrt(aperture_var))
# handle Quantity objects and input units
aperture_sums = self._prepare_photometry_output(aperture_sums,
unit=unit)
aperture_sum_errs = self._prepare_photometry_output(aperture_sum_errs,
unit=unit)
return aperture_sums, aperture_sum_errs | python | def do_photometry(self, data, error=None, mask=None, method='exact',
subpixels=5, unit=None):
"""
Perform aperture photometry on the input data.
Parameters
----------
data : array_like or `~astropy.units.Quantity` instance
The 2D array on which to perform photometry. ``data``
should be background subtracted.
error : array_like or `~astropy.units.Quantity`, optional
The pixel-wise Gaussian 1-sigma errors of the input
``data``. ``error`` is assumed to include *all* sources of
error, including the Poisson error of the sources (see
`~photutils.utils.calc_total_error`) . ``error`` must have
the same shape as the input ``data``.
mask : array_like (bool), optional
A boolean mask with the same shape as ``data`` where a
`True` value indicates the corresponding element of ``data``
is masked. Masked data are excluded from all calculations.
method : {'exact', 'center', 'subpixel'}, optional
The method used to determine the overlap of the aperture on
the pixel grid. Not all options are available for all
aperture types. Note that the more precise methods are
generally slower. The following methods are available:
* ``'exact'`` (default):
The the exact fractional overlap of the aperture and
each pixel is calculated. The returned mask will
contain values between 0 and 1.
* ``'center'``:
A pixel is considered to be entirely in or out of the
aperture depending on whether its center is in or out
of the aperture. The returned mask will contain
values only of 0 (out) and 1 (in).
* ``'subpixel'``
A pixel is divided into subpixels (see the
``subpixels`` keyword), each of which are considered
to be entirely in or out of the aperture depending on
whether its center is in or out of the aperture. If
``subpixels=1``, this method is equivalent to
``'center'``. The returned mask will contain values
between 0 and 1.
subpixels : int, optional
For the ``'subpixel'`` method, resample pixels by this factor
in each dimension. That is, each pixel is divided into
``subpixels ** 2`` subpixels.
unit : `~astropy.units.UnitBase` object or str, optional
An object that represents the unit associated with the input
``data`` and ``error`` arrays. Must be a
`~astropy.units.UnitBase` object or a string parseable by
the :mod:`~astropy.units` package. If ``data`` or ``error``
already have a different unit, the input ``unit`` will not
be used and a warning will be raised.
Returns
-------
aperture_sums : `~numpy.ndarray` or `~astropy.units.Quantity`
The sums within each aperture.
aperture_sum_errs : `~numpy.ndarray` or `~astropy.units.Quantity`
The errors on the sums within each aperture.
"""
data = np.asanyarray(data)
if mask is not None:
mask = np.asanyarray(mask)
data = copy.deepcopy(data) # do not modify input data
data[mask] = 0
if error is not None:
# do not modify input data
error = copy.deepcopy(np.asanyarray(error))
error[mask] = 0.
aperture_sums = []
aperture_sum_errs = []
for mask in self.to_mask(method=method, subpixels=subpixels):
data_cutout = mask.cutout(data)
if data_cutout is None:
aperture_sums.append(np.nan)
else:
aperture_sums.append(np.sum(data_cutout * mask.data))
if error is not None:
error_cutout = mask.cutout(error)
if error_cutout is None:
aperture_sum_errs.append(np.nan)
else:
aperture_var = np.sum(error_cutout ** 2 * mask.data)
aperture_sum_errs.append(np.sqrt(aperture_var))
# handle Quantity objects and input units
aperture_sums = self._prepare_photometry_output(aperture_sums,
unit=unit)
aperture_sum_errs = self._prepare_photometry_output(aperture_sum_errs,
unit=unit)
return aperture_sums, aperture_sum_errs | [
"def",
"do_photometry",
"(",
"self",
",",
"data",
",",
"error",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"method",
"=",
"'exact'",
",",
"subpixels",
"=",
"5",
",",
"unit",
"=",
"None",
")",
":",
"data",
"=",
"np",
".",
"asanyarray",
"(",
"data",
")",
"if",
"mask",
"is",
"not",
"None",
":",
"mask",
"=",
"np",
".",
"asanyarray",
"(",
"mask",
")",
"data",
"=",
"copy",
".",
"deepcopy",
"(",
"data",
")",
"# do not modify input data",
"data",
"[",
"mask",
"]",
"=",
"0",
"if",
"error",
"is",
"not",
"None",
":",
"# do not modify input data",
"error",
"=",
"copy",
".",
"deepcopy",
"(",
"np",
".",
"asanyarray",
"(",
"error",
")",
")",
"error",
"[",
"mask",
"]",
"=",
"0.",
"aperture_sums",
"=",
"[",
"]",
"aperture_sum_errs",
"=",
"[",
"]",
"for",
"mask",
"in",
"self",
".",
"to_mask",
"(",
"method",
"=",
"method",
",",
"subpixels",
"=",
"subpixels",
")",
":",
"data_cutout",
"=",
"mask",
".",
"cutout",
"(",
"data",
")",
"if",
"data_cutout",
"is",
"None",
":",
"aperture_sums",
".",
"append",
"(",
"np",
".",
"nan",
")",
"else",
":",
"aperture_sums",
".",
"append",
"(",
"np",
".",
"sum",
"(",
"data_cutout",
"*",
"mask",
".",
"data",
")",
")",
"if",
"error",
"is",
"not",
"None",
":",
"error_cutout",
"=",
"mask",
".",
"cutout",
"(",
"error",
")",
"if",
"error_cutout",
"is",
"None",
":",
"aperture_sum_errs",
".",
"append",
"(",
"np",
".",
"nan",
")",
"else",
":",
"aperture_var",
"=",
"np",
".",
"sum",
"(",
"error_cutout",
"**",
"2",
"*",
"mask",
".",
"data",
")",
"aperture_sum_errs",
".",
"append",
"(",
"np",
".",
"sqrt",
"(",
"aperture_var",
")",
")",
"# handle Quantity objects and input units",
"aperture_sums",
"=",
"self",
".",
"_prepare_photometry_output",
"(",
"aperture_sums",
",",
"unit",
"=",
"unit",
")",
"aperture_sum_errs",
"=",
"self",
".",
"_prepare_photometry_output",
"(",
"aperture_sum_errs",
",",
"unit",
"=",
"unit",
")",
"return",
"aperture_sums",
",",
"aperture_sum_errs"
] | Perform aperture photometry on the input data.
Parameters
----------
data : array_like or `~astropy.units.Quantity` instance
The 2D array on which to perform photometry. ``data``
should be background subtracted.
error : array_like or `~astropy.units.Quantity`, optional
The pixel-wise Gaussian 1-sigma errors of the input
``data``. ``error`` is assumed to include *all* sources of
error, including the Poisson error of the sources (see
`~photutils.utils.calc_total_error`) . ``error`` must have
the same shape as the input ``data``.
mask : array_like (bool), optional
A boolean mask with the same shape as ``data`` where a
`True` value indicates the corresponding element of ``data``
is masked. Masked data are excluded from all calculations.
method : {'exact', 'center', 'subpixel'}, optional
The method used to determine the overlap of the aperture on
the pixel grid. Not all options are available for all
aperture types. Note that the more precise methods are
generally slower. The following methods are available:
* ``'exact'`` (default):
The the exact fractional overlap of the aperture and
each pixel is calculated. The returned mask will
contain values between 0 and 1.
* ``'center'``:
A pixel is considered to be entirely in or out of the
aperture depending on whether its center is in or out
of the aperture. The returned mask will contain
values only of 0 (out) and 1 (in).
* ``'subpixel'``
A pixel is divided into subpixels (see the
``subpixels`` keyword), each of which are considered
to be entirely in or out of the aperture depending on
whether its center is in or out of the aperture. If
``subpixels=1``, this method is equivalent to
``'center'``. The returned mask will contain values
between 0 and 1.
subpixels : int, optional
For the ``'subpixel'`` method, resample pixels by this factor
in each dimension. That is, each pixel is divided into
``subpixels ** 2`` subpixels.
unit : `~astropy.units.UnitBase` object or str, optional
An object that represents the unit associated with the input
``data`` and ``error`` arrays. Must be a
`~astropy.units.UnitBase` object or a string parseable by
the :mod:`~astropy.units` package. If ``data`` or ``error``
already have a different unit, the input ``unit`` will not
be used and a warning will be raised.
Returns
-------
aperture_sums : `~numpy.ndarray` or `~astropy.units.Quantity`
The sums within each aperture.
aperture_sum_errs : `~numpy.ndarray` or `~astropy.units.Quantity`
The errors on the sums within each aperture. | [
"Perform",
"aperture",
"photometry",
"on",
"the",
"input",
"data",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/core.py#L301-L410 | train |
astropy/photutils | photutils/aperture/core.py | PixelAperture._to_sky_params | def _to_sky_params(self, wcs, mode='all'):
"""
Convert the pixel aperture parameters to those for a sky
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transformation including distortions
(``'all'``; default) or only including only the core WCS
transformation (``'wcs'``).
Returns
-------
sky_params : dict
A dictionary of parameters for an equivalent sky aperture.
"""
sky_params = {}
x, y = np.transpose(self.positions)
sky_params['positions'] = pixel_to_skycoord(x, y, wcs, mode=mode)
# The aperture object must have a single value for each shape
# parameter so we must use a single pixel scale for all positions.
# Here, we define the scale at the WCS CRVAL position.
crval = SkyCoord([wcs.wcs.crval], frame=wcs_to_celestial_frame(wcs),
unit=wcs.wcs.cunit)
scale, angle = pixel_scale_angle_at_skycoord(crval, wcs)
params = self._params[:]
theta_key = 'theta'
if theta_key in self._params:
sky_params[theta_key] = (self.theta * u.rad) - angle.to(u.rad)
params.remove(theta_key)
param_vals = [getattr(self, param) for param in params]
for param, param_val in zip(params, param_vals):
sky_params[param] = (param_val * u.pix * scale).to(u.arcsec)
return sky_params | python | def _to_sky_params(self, wcs, mode='all'):
"""
Convert the pixel aperture parameters to those for a sky
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transformation including distortions
(``'all'``; default) or only including only the core WCS
transformation (``'wcs'``).
Returns
-------
sky_params : dict
A dictionary of parameters for an equivalent sky aperture.
"""
sky_params = {}
x, y = np.transpose(self.positions)
sky_params['positions'] = pixel_to_skycoord(x, y, wcs, mode=mode)
# The aperture object must have a single value for each shape
# parameter so we must use a single pixel scale for all positions.
# Here, we define the scale at the WCS CRVAL position.
crval = SkyCoord([wcs.wcs.crval], frame=wcs_to_celestial_frame(wcs),
unit=wcs.wcs.cunit)
scale, angle = pixel_scale_angle_at_skycoord(crval, wcs)
params = self._params[:]
theta_key = 'theta'
if theta_key in self._params:
sky_params[theta_key] = (self.theta * u.rad) - angle.to(u.rad)
params.remove(theta_key)
param_vals = [getattr(self, param) for param in params]
for param, param_val in zip(params, param_vals):
sky_params[param] = (param_val * u.pix * scale).to(u.arcsec)
return sky_params | [
"def",
"_to_sky_params",
"(",
"self",
",",
"wcs",
",",
"mode",
"=",
"'all'",
")",
":",
"sky_params",
"=",
"{",
"}",
"x",
",",
"y",
"=",
"np",
".",
"transpose",
"(",
"self",
".",
"positions",
")",
"sky_params",
"[",
"'positions'",
"]",
"=",
"pixel_to_skycoord",
"(",
"x",
",",
"y",
",",
"wcs",
",",
"mode",
"=",
"mode",
")",
"# The aperture object must have a single value for each shape",
"# parameter so we must use a single pixel scale for all positions.",
"# Here, we define the scale at the WCS CRVAL position.",
"crval",
"=",
"SkyCoord",
"(",
"[",
"wcs",
".",
"wcs",
".",
"crval",
"]",
",",
"frame",
"=",
"wcs_to_celestial_frame",
"(",
"wcs",
")",
",",
"unit",
"=",
"wcs",
".",
"wcs",
".",
"cunit",
")",
"scale",
",",
"angle",
"=",
"pixel_scale_angle_at_skycoord",
"(",
"crval",
",",
"wcs",
")",
"params",
"=",
"self",
".",
"_params",
"[",
":",
"]",
"theta_key",
"=",
"'theta'",
"if",
"theta_key",
"in",
"self",
".",
"_params",
":",
"sky_params",
"[",
"theta_key",
"]",
"=",
"(",
"self",
".",
"theta",
"*",
"u",
".",
"rad",
")",
"-",
"angle",
".",
"to",
"(",
"u",
".",
"rad",
")",
"params",
".",
"remove",
"(",
"theta_key",
")",
"param_vals",
"=",
"[",
"getattr",
"(",
"self",
",",
"param",
")",
"for",
"param",
"in",
"params",
"]",
"for",
"param",
",",
"param_val",
"in",
"zip",
"(",
"params",
",",
"param_vals",
")",
":",
"sky_params",
"[",
"param",
"]",
"=",
"(",
"param_val",
"*",
"u",
".",
"pix",
"*",
"scale",
")",
".",
"to",
"(",
"u",
".",
"arcsec",
")",
"return",
"sky_params"
] | Convert the pixel aperture parameters to those for a sky
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transformation including distortions
(``'all'``; default) or only including only the core WCS
transformation (``'wcs'``).
Returns
-------
sky_params : dict
A dictionary of parameters for an equivalent sky aperture. | [
"Convert",
"the",
"pixel",
"aperture",
"parameters",
"to",
"those",
"for",
"a",
"sky",
"aperture",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/core.py#L526-L568 | train |
astropy/photutils | photutils/aperture/core.py | SkyAperture._to_pixel_params | def _to_pixel_params(self, wcs, mode='all'):
"""
Convert the sky aperture parameters to those for a pixel
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transformation including distortions
(``'all'``; default) or only including only the core WCS
transformation (``'wcs'``).
Returns
-------
pixel_params : dict
A dictionary of parameters for an equivalent pixel aperture.
"""
pixel_params = {}
x, y = skycoord_to_pixel(self.positions, wcs, mode=mode)
pixel_params['positions'] = np.array([x, y]).transpose()
# The aperture object must have a single value for each shape
# parameter so we must use a single pixel scale for all positions.
# Here, we define the scale at the WCS CRVAL position.
crval = SkyCoord([wcs.wcs.crval], frame=wcs_to_celestial_frame(wcs),
unit=wcs.wcs.cunit)
scale, angle = pixel_scale_angle_at_skycoord(crval, wcs)
params = self._params[:]
theta_key = 'theta'
if theta_key in self._params:
pixel_params[theta_key] = (self.theta + angle).to(u.radian).value
params.remove(theta_key)
param_vals = [getattr(self, param) for param in params]
if param_vals[0].unit.physical_type == 'angle':
for param, param_val in zip(params, param_vals):
pixel_params[param] = (param_val / scale).to(u.pixel).value
else: # pixels
for param, param_val in zip(params, param_vals):
pixel_params[param] = param_val.value
return pixel_params | python | def _to_pixel_params(self, wcs, mode='all'):
"""
Convert the sky aperture parameters to those for a pixel
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transformation including distortions
(``'all'``; default) or only including only the core WCS
transformation (``'wcs'``).
Returns
-------
pixel_params : dict
A dictionary of parameters for an equivalent pixel aperture.
"""
pixel_params = {}
x, y = skycoord_to_pixel(self.positions, wcs, mode=mode)
pixel_params['positions'] = np.array([x, y]).transpose()
# The aperture object must have a single value for each shape
# parameter so we must use a single pixel scale for all positions.
# Here, we define the scale at the WCS CRVAL position.
crval = SkyCoord([wcs.wcs.crval], frame=wcs_to_celestial_frame(wcs),
unit=wcs.wcs.cunit)
scale, angle = pixel_scale_angle_at_skycoord(crval, wcs)
params = self._params[:]
theta_key = 'theta'
if theta_key in self._params:
pixel_params[theta_key] = (self.theta + angle).to(u.radian).value
params.remove(theta_key)
param_vals = [getattr(self, param) for param in params]
if param_vals[0].unit.physical_type == 'angle':
for param, param_val in zip(params, param_vals):
pixel_params[param] = (param_val / scale).to(u.pixel).value
else: # pixels
for param, param_val in zip(params, param_vals):
pixel_params[param] = param_val.value
return pixel_params | [
"def",
"_to_pixel_params",
"(",
"self",
",",
"wcs",
",",
"mode",
"=",
"'all'",
")",
":",
"pixel_params",
"=",
"{",
"}",
"x",
",",
"y",
"=",
"skycoord_to_pixel",
"(",
"self",
".",
"positions",
",",
"wcs",
",",
"mode",
"=",
"mode",
")",
"pixel_params",
"[",
"'positions'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"x",
",",
"y",
"]",
")",
".",
"transpose",
"(",
")",
"# The aperture object must have a single value for each shape",
"# parameter so we must use a single pixel scale for all positions.",
"# Here, we define the scale at the WCS CRVAL position.",
"crval",
"=",
"SkyCoord",
"(",
"[",
"wcs",
".",
"wcs",
".",
"crval",
"]",
",",
"frame",
"=",
"wcs_to_celestial_frame",
"(",
"wcs",
")",
",",
"unit",
"=",
"wcs",
".",
"wcs",
".",
"cunit",
")",
"scale",
",",
"angle",
"=",
"pixel_scale_angle_at_skycoord",
"(",
"crval",
",",
"wcs",
")",
"params",
"=",
"self",
".",
"_params",
"[",
":",
"]",
"theta_key",
"=",
"'theta'",
"if",
"theta_key",
"in",
"self",
".",
"_params",
":",
"pixel_params",
"[",
"theta_key",
"]",
"=",
"(",
"self",
".",
"theta",
"+",
"angle",
")",
".",
"to",
"(",
"u",
".",
"radian",
")",
".",
"value",
"params",
".",
"remove",
"(",
"theta_key",
")",
"param_vals",
"=",
"[",
"getattr",
"(",
"self",
",",
"param",
")",
"for",
"param",
"in",
"params",
"]",
"if",
"param_vals",
"[",
"0",
"]",
".",
"unit",
".",
"physical_type",
"==",
"'angle'",
":",
"for",
"param",
",",
"param_val",
"in",
"zip",
"(",
"params",
",",
"param_vals",
")",
":",
"pixel_params",
"[",
"param",
"]",
"=",
"(",
"param_val",
"/",
"scale",
")",
".",
"to",
"(",
"u",
".",
"pixel",
")",
".",
"value",
"else",
":",
"# pixels",
"for",
"param",
",",
"param_val",
"in",
"zip",
"(",
"params",
",",
"param_vals",
")",
":",
"pixel_params",
"[",
"param",
"]",
"=",
"param_val",
".",
"value",
"return",
"pixel_params"
] | Convert the sky aperture parameters to those for a pixel
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transformation including distortions
(``'all'``; default) or only including only the core WCS
transformation (``'wcs'``).
Returns
-------
pixel_params : dict
A dictionary of parameters for an equivalent pixel aperture. | [
"Convert",
"the",
"sky",
"aperture",
"parameters",
"to",
"those",
"for",
"a",
"pixel",
"aperture",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/core.py#L601-L647 | train |
astropy/photutils | photutils/segmentation/properties.py | source_properties | def source_properties(data, segment_img, error=None, mask=None,
background=None, filter_kernel=None, wcs=None,
labels=None):
"""
Calculate photometry and morphological properties of sources defined
by a labeled segmentation image.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
The 2D array from which to calculate the source photometry and
properties. ``data`` should be background-subtracted.
Non-finite ``data`` values (e.g. NaN or inf) are automatically
masked.
segment_img : `SegmentationImage` or array_like (int)
A 2D segmentation image, either as a `SegmentationImage` object
or an `~numpy.ndarray`, with the same shape as ``data`` where
sources are labeled by different positive integer values. A
value of zero is reserved for the background.
error : array_like or `~astropy.units.Quantity`, optional
The total error array corresponding to the input ``data`` array.
``error`` is assumed to include *all* sources of error,
including the Poisson error of the sources (see
`~photutils.utils.calc_total_error`) . ``error`` must have the
same shape as the input ``data``. Non-finite ``error`` values
(e.g. NaN or inf) are not automatically masked, unless they are
at the same position of non-finite values in the input ``data``
array. Such pixels can be masked using the ``mask`` keyword.
See the Notes section below for details on the error
propagation.
mask : array_like (bool), optional
A boolean mask with the same shape as ``data`` where a `True`
value indicates the corresponding element of ``data`` is masked.
Masked data are excluded from all calculations. Non-finite
values (e.g. NaN or inf) in the input ``data`` are automatically
masked.
background : float, array_like, or `~astropy.units.Quantity`, optional
The background level that was *previously* present in the input
``data``. ``background`` may either be a scalar value or a 2D
image with the same shape as the input ``data``. Inputting the
``background`` merely allows for its properties to be measured
within each source segment. The input ``background`` does *not*
get subtracted from the input ``data``, which should already be
background-subtracted. Non-finite ``background`` values (e.g.
NaN or inf) are not automatically masked, unless they are at the
same position of non-finite values in the input ``data`` array.
Such pixels can be masked using the ``mask`` keyword.
filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional
The 2D array of the kernel used to filter the data prior to
calculating the source centroid and morphological parameters.
The kernel should be the same one used in defining the source
segments, i.e. the detection image (e.g., see
:func:`~photutils.detect_sources`). If `None`, then the
unfiltered ``data`` will be used instead.
wcs : `~astropy.wcs.WCS`
The WCS transformation to use. If `None`, then any sky-based
properties will be set to `None`.
labels : int, array-like (1D, int)
The segmentation labels for which to calculate source
properties. If `None` (default), then the properties will be
calculated for all labeled sources.
Returns
-------
output : `SourceCatalog` instance
A `SourceCatalog` instance containing the properties of each
source.
Notes
-----
`SExtractor`_'s centroid and morphological parameters are always
calculated from a filtered "detection" image, i.e. the image used to
define the segmentation image. The usual downside of the filtering
is the sources will be made more circular than they actually are.
If you wish to reproduce `SExtractor`_ centroid and morphology
results, then input a filtered and background-subtracted "detection"
image into the ``filtered_data`` keyword. If ``filtered_data`` is
`None`, then the unfiltered ``data`` will be used for the source
centroid and morphological parameters.
Negative data values (``filtered_data`` or ``data``) within the
source segment are set to zero when calculating morphological
properties based on image moments. Negative values could occur, for
example, if the segmentation image was defined from a different
image (e.g., different bandpass) or if the background was
oversubtracted. Note that `~photutils.SourceProperties.source_sum`
always includes the contribution of negative ``data`` values.
The input ``error`` is assumed to include *all* sources of error,
including the Poisson error of the sources.
`~photutils.SourceProperties.source_sum_err` is simply the
quadrature sum of the pixel-wise total errors over the non-masked
pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\sigma_{\\mathrm{tot}, i}^2}
where :math:`\\Delta F` is
`~photutils.SourceProperties.source_sum_err`, :math:`S` are the
non-masked pixels in the source segment, and
:math:`\\sigma_{\\mathrm{tot}, i}` is the input ``error`` array.
.. _SExtractor: http://www.astromatic.net/software/sextractor
See Also
--------
SegmentationImage, SourceProperties, detect_sources
Examples
--------
>>> import numpy as np
>>> from photutils import SegmentationImage, source_properties
>>> image = np.arange(16.).reshape(4, 4)
>>> print(image) # doctest: +SKIP
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]
[12. 13. 14. 15.]]
>>> segm = SegmentationImage([[1, 1, 0, 0],
... [1, 0, 0, 2],
... [0, 0, 2, 2],
... [0, 2, 2, 0]])
>>> props = source_properties(image, segm)
Print some properties of the first object (labeled with ``1`` in the
segmentation image):
>>> props[0].id # id corresponds to segment label number
1
>>> props[0].centroid # doctest: +FLOAT_CMP
<Quantity [0.8, 0.2] pix>
>>> props[0].source_sum # doctest: +FLOAT_CMP
5.0
>>> props[0].area # doctest: +FLOAT_CMP
<Quantity 3. pix2>
>>> props[0].max_value # doctest: +FLOAT_CMP
4.0
Print some properties of the second object (labeled with ``2`` in
the segmentation image):
>>> props[1].id # id corresponds to segment label number
2
>>> props[1].centroid # doctest: +FLOAT_CMP
<Quantity [2.36363636, 2.09090909] pix>
>>> props[1].perimeter # doctest: +FLOAT_CMP
<Quantity 5.41421356 pix>
>>> props[1].orientation # doctest: +FLOAT_CMP
<Quantity -0.74175931 rad>
"""
if not isinstance(segment_img, SegmentationImage):
segment_img = SegmentationImage(segment_img)
if segment_img.shape != data.shape:
raise ValueError('segment_img and data must have the same shape.')
# filter the data once, instead of repeating for each source
if filter_kernel is not None:
filtered_data = filter_data(data, filter_kernel, mode='constant',
fill_value=0.0, check_normalization=True)
else:
filtered_data = None
if labels is None:
labels = segment_img.labels
labels = np.atleast_1d(labels)
sources_props = []
for label in labels:
if label not in segment_img.labels:
warnings.warn('label {} is not in the segmentation image.'
.format(label), AstropyUserWarning)
continue # skip invalid labels
sources_props.append(SourceProperties(
data, segment_img, label, filtered_data=filtered_data,
error=error, mask=mask, background=background, wcs=wcs))
if len(sources_props) == 0:
raise ValueError('No sources are defined.')
return SourceCatalog(sources_props, wcs=wcs) | python | def source_properties(data, segment_img, error=None, mask=None,
background=None, filter_kernel=None, wcs=None,
labels=None):
"""
Calculate photometry and morphological properties of sources defined
by a labeled segmentation image.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
The 2D array from which to calculate the source photometry and
properties. ``data`` should be background-subtracted.
Non-finite ``data`` values (e.g. NaN or inf) are automatically
masked.
segment_img : `SegmentationImage` or array_like (int)
A 2D segmentation image, either as a `SegmentationImage` object
or an `~numpy.ndarray`, with the same shape as ``data`` where
sources are labeled by different positive integer values. A
value of zero is reserved for the background.
error : array_like or `~astropy.units.Quantity`, optional
The total error array corresponding to the input ``data`` array.
``error`` is assumed to include *all* sources of error,
including the Poisson error of the sources (see
`~photutils.utils.calc_total_error`) . ``error`` must have the
same shape as the input ``data``. Non-finite ``error`` values
(e.g. NaN or inf) are not automatically masked, unless they are
at the same position of non-finite values in the input ``data``
array. Such pixels can be masked using the ``mask`` keyword.
See the Notes section below for details on the error
propagation.
mask : array_like (bool), optional
A boolean mask with the same shape as ``data`` where a `True`
value indicates the corresponding element of ``data`` is masked.
Masked data are excluded from all calculations. Non-finite
values (e.g. NaN or inf) in the input ``data`` are automatically
masked.
background : float, array_like, or `~astropy.units.Quantity`, optional
The background level that was *previously* present in the input
``data``. ``background`` may either be a scalar value or a 2D
image with the same shape as the input ``data``. Inputting the
``background`` merely allows for its properties to be measured
within each source segment. The input ``background`` does *not*
get subtracted from the input ``data``, which should already be
background-subtracted. Non-finite ``background`` values (e.g.
NaN or inf) are not automatically masked, unless they are at the
same position of non-finite values in the input ``data`` array.
Such pixels can be masked using the ``mask`` keyword.
filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional
The 2D array of the kernel used to filter the data prior to
calculating the source centroid and morphological parameters.
The kernel should be the same one used in defining the source
segments, i.e. the detection image (e.g., see
:func:`~photutils.detect_sources`). If `None`, then the
unfiltered ``data`` will be used instead.
wcs : `~astropy.wcs.WCS`
The WCS transformation to use. If `None`, then any sky-based
properties will be set to `None`.
labels : int, array-like (1D, int)
The segmentation labels for which to calculate source
properties. If `None` (default), then the properties will be
calculated for all labeled sources.
Returns
-------
output : `SourceCatalog` instance
A `SourceCatalog` instance containing the properties of each
source.
Notes
-----
`SExtractor`_'s centroid and morphological parameters are always
calculated from a filtered "detection" image, i.e. the image used to
define the segmentation image. The usual downside of the filtering
is the sources will be made more circular than they actually are.
If you wish to reproduce `SExtractor`_ centroid and morphology
results, then input a filtered and background-subtracted "detection"
image into the ``filtered_data`` keyword. If ``filtered_data`` is
`None`, then the unfiltered ``data`` will be used for the source
centroid and morphological parameters.
Negative data values (``filtered_data`` or ``data``) within the
source segment are set to zero when calculating morphological
properties based on image moments. Negative values could occur, for
example, if the segmentation image was defined from a different
image (e.g., different bandpass) or if the background was
oversubtracted. Note that `~photutils.SourceProperties.source_sum`
always includes the contribution of negative ``data`` values.
The input ``error`` is assumed to include *all* sources of error,
including the Poisson error of the sources.
`~photutils.SourceProperties.source_sum_err` is simply the
quadrature sum of the pixel-wise total errors over the non-masked
pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\sigma_{\\mathrm{tot}, i}^2}
where :math:`\\Delta F` is
`~photutils.SourceProperties.source_sum_err`, :math:`S` are the
non-masked pixels in the source segment, and
:math:`\\sigma_{\\mathrm{tot}, i}` is the input ``error`` array.
.. _SExtractor: http://www.astromatic.net/software/sextractor
See Also
--------
SegmentationImage, SourceProperties, detect_sources
Examples
--------
>>> import numpy as np
>>> from photutils import SegmentationImage, source_properties
>>> image = np.arange(16.).reshape(4, 4)
>>> print(image) # doctest: +SKIP
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]
[12. 13. 14. 15.]]
>>> segm = SegmentationImage([[1, 1, 0, 0],
... [1, 0, 0, 2],
... [0, 0, 2, 2],
... [0, 2, 2, 0]])
>>> props = source_properties(image, segm)
Print some properties of the first object (labeled with ``1`` in the
segmentation image):
>>> props[0].id # id corresponds to segment label number
1
>>> props[0].centroid # doctest: +FLOAT_CMP
<Quantity [0.8, 0.2] pix>
>>> props[0].source_sum # doctest: +FLOAT_CMP
5.0
>>> props[0].area # doctest: +FLOAT_CMP
<Quantity 3. pix2>
>>> props[0].max_value # doctest: +FLOAT_CMP
4.0
Print some properties of the second object (labeled with ``2`` in
the segmentation image):
>>> props[1].id # id corresponds to segment label number
2
>>> props[1].centroid # doctest: +FLOAT_CMP
<Quantity [2.36363636, 2.09090909] pix>
>>> props[1].perimeter # doctest: +FLOAT_CMP
<Quantity 5.41421356 pix>
>>> props[1].orientation # doctest: +FLOAT_CMP
<Quantity -0.74175931 rad>
"""
if not isinstance(segment_img, SegmentationImage):
segment_img = SegmentationImage(segment_img)
if segment_img.shape != data.shape:
raise ValueError('segment_img and data must have the same shape.')
# filter the data once, instead of repeating for each source
if filter_kernel is not None:
filtered_data = filter_data(data, filter_kernel, mode='constant',
fill_value=0.0, check_normalization=True)
else:
filtered_data = None
if labels is None:
labels = segment_img.labels
labels = np.atleast_1d(labels)
sources_props = []
for label in labels:
if label not in segment_img.labels:
warnings.warn('label {} is not in the segmentation image.'
.format(label), AstropyUserWarning)
continue # skip invalid labels
sources_props.append(SourceProperties(
data, segment_img, label, filtered_data=filtered_data,
error=error, mask=mask, background=background, wcs=wcs))
if len(sources_props) == 0:
raise ValueError('No sources are defined.')
return SourceCatalog(sources_props, wcs=wcs) | [
"def",
"source_properties",
"(",
"data",
",",
"segment_img",
",",
"error",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"background",
"=",
"None",
",",
"filter_kernel",
"=",
"None",
",",
"wcs",
"=",
"None",
",",
"labels",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"segment_img",
",",
"SegmentationImage",
")",
":",
"segment_img",
"=",
"SegmentationImage",
"(",
"segment_img",
")",
"if",
"segment_img",
".",
"shape",
"!=",
"data",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"'segment_img and data must have the same shape.'",
")",
"# filter the data once, instead of repeating for each source",
"if",
"filter_kernel",
"is",
"not",
"None",
":",
"filtered_data",
"=",
"filter_data",
"(",
"data",
",",
"filter_kernel",
",",
"mode",
"=",
"'constant'",
",",
"fill_value",
"=",
"0.0",
",",
"check_normalization",
"=",
"True",
")",
"else",
":",
"filtered_data",
"=",
"None",
"if",
"labels",
"is",
"None",
":",
"labels",
"=",
"segment_img",
".",
"labels",
"labels",
"=",
"np",
".",
"atleast_1d",
"(",
"labels",
")",
"sources_props",
"=",
"[",
"]",
"for",
"label",
"in",
"labels",
":",
"if",
"label",
"not",
"in",
"segment_img",
".",
"labels",
":",
"warnings",
".",
"warn",
"(",
"'label {} is not in the segmentation image.'",
".",
"format",
"(",
"label",
")",
",",
"AstropyUserWarning",
")",
"continue",
"# skip invalid labels",
"sources_props",
".",
"append",
"(",
"SourceProperties",
"(",
"data",
",",
"segment_img",
",",
"label",
",",
"filtered_data",
"=",
"filtered_data",
",",
"error",
"=",
"error",
",",
"mask",
"=",
"mask",
",",
"background",
"=",
"background",
",",
"wcs",
"=",
"wcs",
")",
")",
"if",
"len",
"(",
"sources_props",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'No sources are defined.'",
")",
"return",
"SourceCatalog",
"(",
"sources_props",
",",
"wcs",
"=",
"wcs",
")"
] | Calculate photometry and morphological properties of sources defined
by a labeled segmentation image.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
The 2D array from which to calculate the source photometry and
properties. ``data`` should be background-subtracted.
Non-finite ``data`` values (e.g. NaN or inf) are automatically
masked.
segment_img : `SegmentationImage` or array_like (int)
A 2D segmentation image, either as a `SegmentationImage` object
or an `~numpy.ndarray`, with the same shape as ``data`` where
sources are labeled by different positive integer values. A
value of zero is reserved for the background.
error : array_like or `~astropy.units.Quantity`, optional
The total error array corresponding to the input ``data`` array.
``error`` is assumed to include *all* sources of error,
including the Poisson error of the sources (see
`~photutils.utils.calc_total_error`) . ``error`` must have the
same shape as the input ``data``. Non-finite ``error`` values
(e.g. NaN or inf) are not automatically masked, unless they are
at the same position of non-finite values in the input ``data``
array. Such pixels can be masked using the ``mask`` keyword.
See the Notes section below for details on the error
propagation.
mask : array_like (bool), optional
A boolean mask with the same shape as ``data`` where a `True`
value indicates the corresponding element of ``data`` is masked.
Masked data are excluded from all calculations. Non-finite
values (e.g. NaN or inf) in the input ``data`` are automatically
masked.
background : float, array_like, or `~astropy.units.Quantity`, optional
The background level that was *previously* present in the input
``data``. ``background`` may either be a scalar value or a 2D
image with the same shape as the input ``data``. Inputting the
``background`` merely allows for its properties to be measured
within each source segment. The input ``background`` does *not*
get subtracted from the input ``data``, which should already be
background-subtracted. Non-finite ``background`` values (e.g.
NaN or inf) are not automatically masked, unless they are at the
same position of non-finite values in the input ``data`` array.
Such pixels can be masked using the ``mask`` keyword.
filter_kernel : array-like (2D) or `~astropy.convolution.Kernel2D`, optional
The 2D array of the kernel used to filter the data prior to
calculating the source centroid and morphological parameters.
The kernel should be the same one used in defining the source
segments, i.e. the detection image (e.g., see
:func:`~photutils.detect_sources`). If `None`, then the
unfiltered ``data`` will be used instead.
wcs : `~astropy.wcs.WCS`
The WCS transformation to use. If `None`, then any sky-based
properties will be set to `None`.
labels : int, array-like (1D, int)
The segmentation labels for which to calculate source
properties. If `None` (default), then the properties will be
calculated for all labeled sources.
Returns
-------
output : `SourceCatalog` instance
A `SourceCatalog` instance containing the properties of each
source.
Notes
-----
`SExtractor`_'s centroid and morphological parameters are always
calculated from a filtered "detection" image, i.e. the image used to
define the segmentation image. The usual downside of the filtering
is the sources will be made more circular than they actually are.
If you wish to reproduce `SExtractor`_ centroid and morphology
results, then input a filtered and background-subtracted "detection"
image into the ``filtered_data`` keyword. If ``filtered_data`` is
`None`, then the unfiltered ``data`` will be used for the source
centroid and morphological parameters.
Negative data values (``filtered_data`` or ``data``) within the
source segment are set to zero when calculating morphological
properties based on image moments. Negative values could occur, for
example, if the segmentation image was defined from a different
image (e.g., different bandpass) or if the background was
oversubtracted. Note that `~photutils.SourceProperties.source_sum`
always includes the contribution of negative ``data`` values.
The input ``error`` is assumed to include *all* sources of error,
including the Poisson error of the sources.
`~photutils.SourceProperties.source_sum_err` is simply the
quadrature sum of the pixel-wise total errors over the non-masked
pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\sigma_{\\mathrm{tot}, i}^2}
where :math:`\\Delta F` is
`~photutils.SourceProperties.source_sum_err`, :math:`S` are the
non-masked pixels in the source segment, and
:math:`\\sigma_{\\mathrm{tot}, i}` is the input ``error`` array.
.. _SExtractor: http://www.astromatic.net/software/sextractor
See Also
--------
SegmentationImage, SourceProperties, detect_sources
Examples
--------
>>> import numpy as np
>>> from photutils import SegmentationImage, source_properties
>>> image = np.arange(16.).reshape(4, 4)
>>> print(image) # doctest: +SKIP
[[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]
[12. 13. 14. 15.]]
>>> segm = SegmentationImage([[1, 1, 0, 0],
... [1, 0, 0, 2],
... [0, 0, 2, 2],
... [0, 2, 2, 0]])
>>> props = source_properties(image, segm)
Print some properties of the first object (labeled with ``1`` in the
segmentation image):
>>> props[0].id # id corresponds to segment label number
1
>>> props[0].centroid # doctest: +FLOAT_CMP
<Quantity [0.8, 0.2] pix>
>>> props[0].source_sum # doctest: +FLOAT_CMP
5.0
>>> props[0].area # doctest: +FLOAT_CMP
<Quantity 3. pix2>
>>> props[0].max_value # doctest: +FLOAT_CMP
4.0
Print some properties of the second object (labeled with ``2`` in
the segmentation image):
>>> props[1].id # id corresponds to segment label number
2
>>> props[1].centroid # doctest: +FLOAT_CMP
<Quantity [2.36363636, 2.09090909] pix>
>>> props[1].perimeter # doctest: +FLOAT_CMP
<Quantity 5.41421356 pix>
>>> props[1].orientation # doctest: +FLOAT_CMP
<Quantity -0.74175931 rad> | [
"Calculate",
"photometry",
"and",
"morphological",
"properties",
"of",
"sources",
"defined",
"by",
"a",
"labeled",
"segmentation",
"image",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L1223-L1412 | train |
astropy/photutils | photutils/segmentation/properties.py | _properties_table | def _properties_table(obj, columns=None, exclude_columns=None):
"""
Construct a `~astropy.table.QTable` of source properties from a
`SourceProperties` or `SourceCatalog` object.
Parameters
----------
obj : `SourceProperties` or `SourceCatalog` instance
The object containing the source properties.
columns : str or list of str, optional
Names of columns, in order, to include in the output
`~astropy.table.QTable`. The allowed column names are any
of the attributes of `SourceProperties`.
exclude_columns : str or list of str, optional
Names of columns to exclude from the default properties list
in the output `~astropy.table.QTable`.
Returns
-------
table : `~astropy.table.QTable`
A table of source properties with one row per source.
"""
# default properties
columns_all = ['id', 'xcentroid', 'ycentroid', 'sky_centroid',
'sky_centroid_icrs', 'source_sum', 'source_sum_err',
'background_sum', 'background_mean',
'background_at_centroid', 'xmin', 'xmax', 'ymin',
'ymax', 'min_value', 'max_value', 'minval_xpos',
'minval_ypos', 'maxval_xpos', 'maxval_ypos', 'area',
'equivalent_radius', 'perimeter',
'semimajor_axis_sigma', 'semiminor_axis_sigma',
'eccentricity', 'orientation', 'ellipticity',
'elongation', 'covar_sigx2', 'covar_sigxy',
'covar_sigy2', 'cxx', 'cxy', 'cyy']
table_columns = None
if exclude_columns is not None:
table_columns = [s for s in columns_all if s not in exclude_columns]
if columns is not None:
table_columns = np.atleast_1d(columns)
if table_columns is None:
table_columns = columns_all
tbl = QTable()
for column in table_columns:
values = getattr(obj, column)
if isinstance(obj, SourceProperties):
# turn scalar values into length-1 arrays because QTable
# column assignment requires an object with a length
values = np.atleast_1d(values)
# Unfortunately np.atleast_1d creates an array of SkyCoord
# instead of a SkyCoord array (Quantity does work correctly
# with np.atleast_1d). Here we make a SkyCoord array for
# the output table column.
if isinstance(values[0], SkyCoord):
values = SkyCoord(values) # length-1 SkyCoord array
tbl[column] = values
return tbl | python | def _properties_table(obj, columns=None, exclude_columns=None):
"""
Construct a `~astropy.table.QTable` of source properties from a
`SourceProperties` or `SourceCatalog` object.
Parameters
----------
obj : `SourceProperties` or `SourceCatalog` instance
The object containing the source properties.
columns : str or list of str, optional
Names of columns, in order, to include in the output
`~astropy.table.QTable`. The allowed column names are any
of the attributes of `SourceProperties`.
exclude_columns : str or list of str, optional
Names of columns to exclude from the default properties list
in the output `~astropy.table.QTable`.
Returns
-------
table : `~astropy.table.QTable`
A table of source properties with one row per source.
"""
# default properties
columns_all = ['id', 'xcentroid', 'ycentroid', 'sky_centroid',
'sky_centroid_icrs', 'source_sum', 'source_sum_err',
'background_sum', 'background_mean',
'background_at_centroid', 'xmin', 'xmax', 'ymin',
'ymax', 'min_value', 'max_value', 'minval_xpos',
'minval_ypos', 'maxval_xpos', 'maxval_ypos', 'area',
'equivalent_radius', 'perimeter',
'semimajor_axis_sigma', 'semiminor_axis_sigma',
'eccentricity', 'orientation', 'ellipticity',
'elongation', 'covar_sigx2', 'covar_sigxy',
'covar_sigy2', 'cxx', 'cxy', 'cyy']
table_columns = None
if exclude_columns is not None:
table_columns = [s for s in columns_all if s not in exclude_columns]
if columns is not None:
table_columns = np.atleast_1d(columns)
if table_columns is None:
table_columns = columns_all
tbl = QTable()
for column in table_columns:
values = getattr(obj, column)
if isinstance(obj, SourceProperties):
# turn scalar values into length-1 arrays because QTable
# column assignment requires an object with a length
values = np.atleast_1d(values)
# Unfortunately np.atleast_1d creates an array of SkyCoord
# instead of a SkyCoord array (Quantity does work correctly
# with np.atleast_1d). Here we make a SkyCoord array for
# the output table column.
if isinstance(values[0], SkyCoord):
values = SkyCoord(values) # length-1 SkyCoord array
tbl[column] = values
return tbl | [
"def",
"_properties_table",
"(",
"obj",
",",
"columns",
"=",
"None",
",",
"exclude_columns",
"=",
"None",
")",
":",
"# default properties",
"columns_all",
"=",
"[",
"'id'",
",",
"'xcentroid'",
",",
"'ycentroid'",
",",
"'sky_centroid'",
",",
"'sky_centroid_icrs'",
",",
"'source_sum'",
",",
"'source_sum_err'",
",",
"'background_sum'",
",",
"'background_mean'",
",",
"'background_at_centroid'",
",",
"'xmin'",
",",
"'xmax'",
",",
"'ymin'",
",",
"'ymax'",
",",
"'min_value'",
",",
"'max_value'",
",",
"'minval_xpos'",
",",
"'minval_ypos'",
",",
"'maxval_xpos'",
",",
"'maxval_ypos'",
",",
"'area'",
",",
"'equivalent_radius'",
",",
"'perimeter'",
",",
"'semimajor_axis_sigma'",
",",
"'semiminor_axis_sigma'",
",",
"'eccentricity'",
",",
"'orientation'",
",",
"'ellipticity'",
",",
"'elongation'",
",",
"'covar_sigx2'",
",",
"'covar_sigxy'",
",",
"'covar_sigy2'",
",",
"'cxx'",
",",
"'cxy'",
",",
"'cyy'",
"]",
"table_columns",
"=",
"None",
"if",
"exclude_columns",
"is",
"not",
"None",
":",
"table_columns",
"=",
"[",
"s",
"for",
"s",
"in",
"columns_all",
"if",
"s",
"not",
"in",
"exclude_columns",
"]",
"if",
"columns",
"is",
"not",
"None",
":",
"table_columns",
"=",
"np",
".",
"atleast_1d",
"(",
"columns",
")",
"if",
"table_columns",
"is",
"None",
":",
"table_columns",
"=",
"columns_all",
"tbl",
"=",
"QTable",
"(",
")",
"for",
"column",
"in",
"table_columns",
":",
"values",
"=",
"getattr",
"(",
"obj",
",",
"column",
")",
"if",
"isinstance",
"(",
"obj",
",",
"SourceProperties",
")",
":",
"# turn scalar values into length-1 arrays because QTable",
"# column assignment requires an object with a length",
"values",
"=",
"np",
".",
"atleast_1d",
"(",
"values",
")",
"# Unfortunately np.atleast_1d creates an array of SkyCoord",
"# instead of a SkyCoord array (Quantity does work correctly",
"# with np.atleast_1d). Here we make a SkyCoord array for",
"# the output table column.",
"if",
"isinstance",
"(",
"values",
"[",
"0",
"]",
",",
"SkyCoord",
")",
":",
"values",
"=",
"SkyCoord",
"(",
"values",
")",
"# length-1 SkyCoord array",
"tbl",
"[",
"column",
"]",
"=",
"values",
"return",
"tbl"
] | Construct a `~astropy.table.QTable` of source properties from a
`SourceProperties` or `SourceCatalog` object.
Parameters
----------
obj : `SourceProperties` or `SourceCatalog` instance
The object containing the source properties.
columns : str or list of str, optional
Names of columns, in order, to include in the output
`~astropy.table.QTable`. The allowed column names are any
of the attributes of `SourceProperties`.
exclude_columns : str or list of str, optional
Names of columns to exclude from the default properties list
in the output `~astropy.table.QTable`.
Returns
-------
table : `~astropy.table.QTable`
A table of source properties with one row per source. | [
"Construct",
"a",
"~astropy",
".",
"table",
".",
"QTable",
"of",
"source",
"properties",
"from",
"a",
"SourceProperties",
"or",
"SourceCatalog",
"object",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L1609-L1673 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties._total_mask | def _total_mask(self):
"""
Combination of the _segment_mask, _input_mask, and _data_mask.
This mask is applied to ``data``, ``error``, and ``background``
inputs when calculating properties.
"""
mask = self._segment_mask | self._data_mask
if self._input_mask is not None:
mask |= self._input_mask
return mask | python | def _total_mask(self):
"""
Combination of the _segment_mask, _input_mask, and _data_mask.
This mask is applied to ``data``, ``error``, and ``background``
inputs when calculating properties.
"""
mask = self._segment_mask | self._data_mask
if self._input_mask is not None:
mask |= self._input_mask
return mask | [
"def",
"_total_mask",
"(",
"self",
")",
":",
"mask",
"=",
"self",
".",
"_segment_mask",
"|",
"self",
".",
"_data_mask",
"if",
"self",
".",
"_input_mask",
"is",
"not",
"None",
":",
"mask",
"|=",
"self",
".",
"_input_mask",
"return",
"mask"
] | Combination of the _segment_mask, _input_mask, and _data_mask.
This mask is applied to ``data``, ``error``, and ``background``
inputs when calculating properties. | [
"Combination",
"of",
"the",
"_segment_mask",
"_input_mask",
"and",
"_data_mask",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L228-L241 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.to_table | def to_table(self, columns=None, exclude_columns=None):
"""
Create a `~astropy.table.QTable` of properties.
If ``columns`` or ``exclude_columns`` are not input, then the
`~astropy.table.QTable` will include a default list of
scalar-valued properties.
Parameters
----------
columns : str or list of str, optional
Names of columns, in order, to include in the output
`~astropy.table.QTable`. The allowed column names are any
of the attributes of `SourceProperties`.
exclude_columns : str or list of str, optional
Names of columns to exclude from the default properties list
in the output `~astropy.table.QTable`.
Returns
-------
table : `~astropy.table.QTable`
A single-row table of properties of the source.
"""
return _properties_table(self, columns=columns,
exclude_columns=exclude_columns) | python | def to_table(self, columns=None, exclude_columns=None):
"""
Create a `~astropy.table.QTable` of properties.
If ``columns`` or ``exclude_columns`` are not input, then the
`~astropy.table.QTable` will include a default list of
scalar-valued properties.
Parameters
----------
columns : str or list of str, optional
Names of columns, in order, to include in the output
`~astropy.table.QTable`. The allowed column names are any
of the attributes of `SourceProperties`.
exclude_columns : str or list of str, optional
Names of columns to exclude from the default properties list
in the output `~astropy.table.QTable`.
Returns
-------
table : `~astropy.table.QTable`
A single-row table of properties of the source.
"""
return _properties_table(self, columns=columns,
exclude_columns=exclude_columns) | [
"def",
"to_table",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"exclude_columns",
"=",
"None",
")",
":",
"return",
"_properties_table",
"(",
"self",
",",
"columns",
"=",
"columns",
",",
"exclude_columns",
"=",
"exclude_columns",
")"
] | Create a `~astropy.table.QTable` of properties.
If ``columns`` or ``exclude_columns`` are not input, then the
`~astropy.table.QTable` will include a default list of
scalar-valued properties.
Parameters
----------
columns : str or list of str, optional
Names of columns, in order, to include in the output
`~astropy.table.QTable`. The allowed column names are any
of the attributes of `SourceProperties`.
exclude_columns : str or list of str, optional
Names of columns to exclude from the default properties list
in the output `~astropy.table.QTable`.
Returns
-------
table : `~astropy.table.QTable`
A single-row table of properties of the source. | [
"Create",
"a",
"~astropy",
".",
"table",
".",
"QTable",
"of",
"properties",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L330-L356 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.data_cutout_ma | def data_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the data.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf).
"""
return np.ma.masked_array(self._data[self._slice],
mask=self._total_mask) | python | def data_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the data.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf).
"""
return np.ma.masked_array(self._data[self._slice],
mask=self._total_mask) | [
"def",
"data_cutout_ma",
"(",
"self",
")",
":",
"return",
"np",
".",
"ma",
".",
"masked_array",
"(",
"self",
".",
"_data",
"[",
"self",
".",
"_slice",
"]",
",",
"mask",
"=",
"self",
".",
"_total_mask",
")"
] | A 2D `~numpy.ma.MaskedArray` cutout from the data.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf). | [
"A",
"2D",
"~numpy",
".",
"ma",
".",
"MaskedArray",
"cutout",
"from",
"the",
"data",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L368-L378 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.error_cutout_ma | def error_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the input ``error``
image.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf).
If ``error`` is `None`, then ``error_cutout_ma`` is also `None`.
"""
if self._error is None:
return None
else:
return np.ma.masked_array(self._error[self._slice],
mask=self._total_mask) | python | def error_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the input ``error``
image.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf).
If ``error`` is `None`, then ``error_cutout_ma`` is also `None`.
"""
if self._error is None:
return None
else:
return np.ma.masked_array(self._error[self._slice],
mask=self._total_mask) | [
"def",
"error_cutout_ma",
"(",
"self",
")",
":",
"if",
"self",
".",
"_error",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"np",
".",
"ma",
".",
"masked_array",
"(",
"self",
".",
"_error",
"[",
"self",
".",
"_slice",
"]",
",",
"mask",
"=",
"self",
".",
"_total_mask",
")"
] | A 2D `~numpy.ma.MaskedArray` cutout from the input ``error``
image.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf).
If ``error`` is `None`, then ``error_cutout_ma`` is also `None`. | [
"A",
"2D",
"~numpy",
".",
"ma",
".",
"MaskedArray",
"cutout",
"from",
"the",
"input",
"error",
"image",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L381-L397 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.background_cutout_ma | def background_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the input
``background``.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf).
If ``background`` is `None`, then ``background_cutout_ma`` is
also `None`.
"""
if self._background is None:
return None
else:
return np.ma.masked_array(self._background[self._slice],
mask=self._total_mask) | python | def background_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the input
``background``.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf).
If ``background`` is `None`, then ``background_cutout_ma`` is
also `None`.
"""
if self._background is None:
return None
else:
return np.ma.masked_array(self._background[self._slice],
mask=self._total_mask) | [
"def",
"background_cutout_ma",
"(",
"self",
")",
":",
"if",
"self",
".",
"_background",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"np",
".",
"ma",
".",
"masked_array",
"(",
"self",
".",
"_background",
"[",
"self",
".",
"_slice",
"]",
",",
"mask",
"=",
"self",
".",
"_total_mask",
")"
] | A 2D `~numpy.ma.MaskedArray` cutout from the input
``background``.
The mask is `True` for pixels outside of the source segment
(labeled region of interest), masked pixels from the ``mask``
input, or any non-finite ``data`` values (e.g. NaN or inf).
If ``background`` is `None`, then ``background_cutout_ma`` is
also `None`. | [
"A",
"2D",
"~numpy",
".",
"ma",
".",
"MaskedArray",
"cutout",
"from",
"the",
"input",
"background",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L400-L417 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.coords | def coords(self):
"""
A tuple of two `~numpy.ndarray` containing the ``y`` and ``x``
pixel coordinates of unmasked pixels within the source segment.
Non-finite pixel values (e.g. NaN, infs) are excluded
(automatically masked).
If all pixels are masked, ``coords`` will be a tuple of
two empty arrays.
"""
yy, xx = np.nonzero(self.data_cutout_ma)
return (yy + self._slice[0].start, xx + self._slice[1].start) | python | def coords(self):
"""
A tuple of two `~numpy.ndarray` containing the ``y`` and ``x``
pixel coordinates of unmasked pixels within the source segment.
Non-finite pixel values (e.g. NaN, infs) are excluded
(automatically masked).
If all pixels are masked, ``coords`` will be a tuple of
two empty arrays.
"""
yy, xx = np.nonzero(self.data_cutout_ma)
return (yy + self._slice[0].start, xx + self._slice[1].start) | [
"def",
"coords",
"(",
"self",
")",
":",
"yy",
",",
"xx",
"=",
"np",
".",
"nonzero",
"(",
"self",
".",
"data_cutout_ma",
")",
"return",
"(",
"yy",
"+",
"self",
".",
"_slice",
"[",
"0",
"]",
".",
"start",
",",
"xx",
"+",
"self",
".",
"_slice",
"[",
"1",
"]",
".",
"start",
")"
] | A tuple of two `~numpy.ndarray` containing the ``y`` and ``x``
pixel coordinates of unmasked pixels within the source segment.
Non-finite pixel values (e.g. NaN, infs) are excluded
(automatically masked).
If all pixels are masked, ``coords`` will be a tuple of
two empty arrays. | [
"A",
"tuple",
"of",
"two",
"~numpy",
".",
"ndarray",
"containing",
"the",
"y",
"and",
"x",
"pixel",
"coordinates",
"of",
"unmasked",
"pixels",
"within",
"the",
"source",
"segment",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L442-L455 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.sky_centroid | def sky_centroid(self):
"""
The sky coordinates of the centroid within the source segment,
returned as a `~astropy.coordinates.SkyCoord` object.
The output coordinate frame is the same as the input WCS.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xcentroid.value,
self.ycentroid.value,
self._wcs, origin=0)
else:
return None | python | def sky_centroid(self):
"""
The sky coordinates of the centroid within the source segment,
returned as a `~astropy.coordinates.SkyCoord` object.
The output coordinate frame is the same as the input WCS.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xcentroid.value,
self.ycentroid.value,
self._wcs, origin=0)
else:
return None | [
"def",
"sky_centroid",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wcs",
"is",
"not",
"None",
":",
"return",
"pixel_to_skycoord",
"(",
"self",
".",
"xcentroid",
".",
"value",
",",
"self",
".",
"ycentroid",
".",
"value",
",",
"self",
".",
"_wcs",
",",
"origin",
"=",
"0",
")",
"else",
":",
"return",
"None"
] | The sky coordinates of the centroid within the source segment,
returned as a `~astropy.coordinates.SkyCoord` object.
The output coordinate frame is the same as the input WCS. | [
"The",
"sky",
"coordinates",
"of",
"the",
"centroid",
"within",
"the",
"source",
"segment",
"returned",
"as",
"a",
"~astropy",
".",
"coordinates",
".",
"SkyCoord",
"object",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L526-L539 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.sky_bbox_ll | def sky_bbox_ll(self):
"""
The sky coordinates of the lower-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmin.value - 0.5,
self.ymin.value - 0.5,
self._wcs, origin=0)
else:
return None | python | def sky_bbox_ll(self):
"""
The sky coordinates of the lower-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmin.value - 0.5,
self.ymin.value - 0.5,
self._wcs, origin=0)
else:
return None | [
"def",
"sky_bbox_ll",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wcs",
"is",
"not",
"None",
":",
"return",
"pixel_to_skycoord",
"(",
"self",
".",
"xmin",
".",
"value",
"-",
"0.5",
",",
"self",
".",
"ymin",
".",
"value",
"-",
"0.5",
",",
"self",
".",
"_wcs",
",",
"origin",
"=",
"0",
")",
"else",
":",
"return",
"None"
] | The sky coordinates of the lower-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*. | [
"The",
"sky",
"coordinates",
"of",
"the",
"lower",
"-",
"left",
"vertex",
"of",
"the",
"minimal",
"bounding",
"box",
"of",
"the",
"source",
"segment",
"returned",
"as",
"a",
"~astropy",
".",
"coordinates",
".",
"SkyCoord",
"object",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L602-L617 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.sky_bbox_ul | def sky_bbox_ul(self):
"""
The sky coordinates of the upper-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmin.value - 0.5,
self.ymax.value + 0.5,
self._wcs, origin=0)
else:
return None | python | def sky_bbox_ul(self):
"""
The sky coordinates of the upper-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmin.value - 0.5,
self.ymax.value + 0.5,
self._wcs, origin=0)
else:
return None | [
"def",
"sky_bbox_ul",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wcs",
"is",
"not",
"None",
":",
"return",
"pixel_to_skycoord",
"(",
"self",
".",
"xmin",
".",
"value",
"-",
"0.5",
",",
"self",
".",
"ymax",
".",
"value",
"+",
"0.5",
",",
"self",
".",
"_wcs",
",",
"origin",
"=",
"0",
")",
"else",
":",
"return",
"None"
] | The sky coordinates of the upper-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*. | [
"The",
"sky",
"coordinates",
"of",
"the",
"upper",
"-",
"left",
"vertex",
"of",
"the",
"minimal",
"bounding",
"box",
"of",
"the",
"source",
"segment",
"returned",
"as",
"a",
"~astropy",
".",
"coordinates",
".",
"SkyCoord",
"object",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L620-L635 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.sky_bbox_lr | def sky_bbox_lr(self):
"""
The sky coordinates of the lower-right vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmax.value + 0.5,
self.ymin.value - 0.5,
self._wcs, origin=0)
else:
return None | python | def sky_bbox_lr(self):
"""
The sky coordinates of the lower-right vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmax.value + 0.5,
self.ymin.value - 0.5,
self._wcs, origin=0)
else:
return None | [
"def",
"sky_bbox_lr",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wcs",
"is",
"not",
"None",
":",
"return",
"pixel_to_skycoord",
"(",
"self",
".",
"xmax",
".",
"value",
"+",
"0.5",
",",
"self",
".",
"ymin",
".",
"value",
"-",
"0.5",
",",
"self",
".",
"_wcs",
",",
"origin",
"=",
"0",
")",
"else",
":",
"return",
"None"
] | The sky coordinates of the lower-right vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*. | [
"The",
"sky",
"coordinates",
"of",
"the",
"lower",
"-",
"right",
"vertex",
"of",
"the",
"minimal",
"bounding",
"box",
"of",
"the",
"source",
"segment",
"returned",
"as",
"a",
"~astropy",
".",
"coordinates",
".",
"SkyCoord",
"object",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L638-L653 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.sky_bbox_ur | def sky_bbox_ur(self):
"""
The sky coordinates of the upper-right vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmax.value + 0.5,
self.ymax.value + 0.5,
self._wcs, origin=0)
else:
return None | python | def sky_bbox_ur(self):
"""
The sky coordinates of the upper-right vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*.
"""
if self._wcs is not None:
return pixel_to_skycoord(self.xmax.value + 0.5,
self.ymax.value + 0.5,
self._wcs, origin=0)
else:
return None | [
"def",
"sky_bbox_ur",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wcs",
"is",
"not",
"None",
":",
"return",
"pixel_to_skycoord",
"(",
"self",
".",
"xmax",
".",
"value",
"+",
"0.5",
",",
"self",
".",
"ymax",
".",
"value",
"+",
"0.5",
",",
"self",
".",
"_wcs",
",",
"origin",
"=",
"0",
")",
"else",
":",
"return",
"None"
] | The sky coordinates of the upper-right vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*. | [
"The",
"sky",
"coordinates",
"of",
"the",
"upper",
"-",
"right",
"vertex",
"of",
"the",
"minimal",
"bounding",
"box",
"of",
"the",
"source",
"segment",
"returned",
"as",
"a",
"~astropy",
".",
"coordinates",
".",
"SkyCoord",
"object",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L656-L671 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.min_value | def min_value(self):
"""
The minimum pixel value of the ``data`` within the source
segment.
"""
if self._is_completely_masked:
return np.nan * self._data_unit
else:
return np.min(self.values) | python | def min_value(self):
"""
The minimum pixel value of the ``data`` within the source
segment.
"""
if self._is_completely_masked:
return np.nan * self._data_unit
else:
return np.min(self.values) | [
"def",
"min_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_data_unit",
"else",
":",
"return",
"np",
".",
"min",
"(",
"self",
".",
"values",
")"
] | The minimum pixel value of the ``data`` within the source
segment. | [
"The",
"minimum",
"pixel",
"value",
"of",
"the",
"data",
"within",
"the",
"source",
"segment",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L674-L683 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.max_value | def max_value(self):
"""
The maximum pixel value of the ``data`` within the source
segment.
"""
if self._is_completely_masked:
return np.nan * self._data_unit
else:
return np.max(self.values) | python | def max_value(self):
"""
The maximum pixel value of the ``data`` within the source
segment.
"""
if self._is_completely_masked:
return np.nan * self._data_unit
else:
return np.max(self.values) | [
"def",
"max_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_data_unit",
"else",
":",
"return",
"np",
".",
"max",
"(",
"self",
".",
"values",
")"
] | The maximum pixel value of the ``data`` within the source
segment. | [
"The",
"maximum",
"pixel",
"value",
"of",
"the",
"data",
"within",
"the",
"source",
"segment",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L686-L695 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.source_sum | def source_sum(self):
"""
The sum of the unmasked ``data`` values within the source segment.
.. math:: F = \\sum_{i \\in S} (I_i - B_i)
where :math:`F` is ``source_sum``, :math:`(I_i - B_i)` is the
``data``, and :math:`S` are the unmasked pixels in the source
segment.
Non-finite pixel values (e.g. NaN, infs) are excluded
(automatically masked).
"""
if self._is_completely_masked:
return np.nan * self._data_unit # table output needs unit
else:
return np.sum(self.values) | python | def source_sum(self):
"""
The sum of the unmasked ``data`` values within the source segment.
.. math:: F = \\sum_{i \\in S} (I_i - B_i)
where :math:`F` is ``source_sum``, :math:`(I_i - B_i)` is the
``data``, and :math:`S` are the unmasked pixels in the source
segment.
Non-finite pixel values (e.g. NaN, infs) are excluded
(automatically masked).
"""
if self._is_completely_masked:
return np.nan * self._data_unit # table output needs unit
else:
return np.sum(self.values) | [
"def",
"source_sum",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_data_unit",
"# table output needs unit",
"else",
":",
"return",
"np",
".",
"sum",
"(",
"self",
".",
"values",
")"
] | The sum of the unmasked ``data`` values within the source segment.
.. math:: F = \\sum_{i \\in S} (I_i - B_i)
where :math:`F` is ``source_sum``, :math:`(I_i - B_i)` is the
``data``, and :math:`S` are the unmasked pixels in the source
segment.
Non-finite pixel values (e.g. NaN, infs) are excluded
(automatically masked). | [
"The",
"sum",
"of",
"the",
"unmasked",
"data",
"values",
"within",
"the",
"source",
"segment",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L818-L835 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.source_sum_err | def source_sum_err(self):
"""
The uncertainty of `~photutils.SourceProperties.source_sum`,
propagated from the input ``error`` array.
``source_sum_err`` is the quadrature sum of the total errors
over the non-masked pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\sigma_{\\mathrm{tot}, i}^2}
where :math:`\\Delta F` is ``source_sum_err``,
:math:`\\sigma_{\\mathrm{tot, i}}` are the pixel-wise total
errors, and :math:`S` are the non-masked pixels in the source
segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the error array.
"""
if self._error is not None:
if self._is_completely_masked:
return np.nan * self._error_unit # table output needs unit
else:
return np.sqrt(np.sum(self._error_values ** 2))
else:
return None | python | def source_sum_err(self):
"""
The uncertainty of `~photutils.SourceProperties.source_sum`,
propagated from the input ``error`` array.
``source_sum_err`` is the quadrature sum of the total errors
over the non-masked pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\sigma_{\\mathrm{tot}, i}^2}
where :math:`\\Delta F` is ``source_sum_err``,
:math:`\\sigma_{\\mathrm{tot, i}}` are the pixel-wise total
errors, and :math:`S` are the non-masked pixels in the source
segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the error array.
"""
if self._error is not None:
if self._is_completely_masked:
return np.nan * self._error_unit # table output needs unit
else:
return np.sqrt(np.sum(self._error_values ** 2))
else:
return None | [
"def",
"source_sum_err",
"(",
"self",
")",
":",
"if",
"self",
".",
"_error",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_error_unit",
"# table output needs unit",
"else",
":",
"return",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"_error_values",
"**",
"2",
")",
")",
"else",
":",
"return",
"None"
] | The uncertainty of `~photutils.SourceProperties.source_sum`,
propagated from the input ``error`` array.
``source_sum_err`` is the quadrature sum of the total errors
over the non-masked pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\sigma_{\\mathrm{tot}, i}^2}
where :math:`\\Delta F` is ``source_sum_err``,
:math:`\\sigma_{\\mathrm{tot, i}}` are the pixel-wise total
errors, and :math:`S` are the non-masked pixels in the source
segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the error array. | [
"The",
"uncertainty",
"of",
"~photutils",
".",
"SourceProperties",
".",
"source_sum",
"propagated",
"from",
"the",
"input",
"error",
"array",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L838-L865 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.background_sum | def background_sum(self):
"""
The sum of ``background`` values within the source segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the background array.
"""
if self._background is not None:
if self._is_completely_masked:
return np.nan * self._background_unit # unit for table
else:
return np.sum(self._background_values)
else:
return None | python | def background_sum(self):
"""
The sum of ``background`` values within the source segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the background array.
"""
if self._background is not None:
if self._is_completely_masked:
return np.nan * self._background_unit # unit for table
else:
return np.sum(self._background_values)
else:
return None | [
"def",
"background_sum",
"(",
"self",
")",
":",
"if",
"self",
".",
"_background",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_background_unit",
"# unit for table",
"else",
":",
"return",
"np",
".",
"sum",
"(",
"self",
".",
"_background_values",
")",
"else",
":",
"return",
"None"
] | The sum of ``background`` values within the source segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the background array. | [
"The",
"sum",
"of",
"background",
"values",
"within",
"the",
"source",
"segment",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L868-L883 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.background_mean | def background_mean(self):
"""
The mean of ``background`` values within the source segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the background array.
"""
if self._background is not None:
if self._is_completely_masked:
return np.nan * self._background_unit # unit for table
else:
return np.mean(self._background_values)
else:
return None | python | def background_mean(self):
"""
The mean of ``background`` values within the source segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the background array.
"""
if self._background is not None:
if self._is_completely_masked:
return np.nan * self._background_unit # unit for table
else:
return np.mean(self._background_values)
else:
return None | [
"def",
"background_mean",
"(",
"self",
")",
":",
"if",
"self",
".",
"_background",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_background_unit",
"# unit for table",
"else",
":",
"return",
"np",
".",
"mean",
"(",
"self",
".",
"_background_values",
")",
"else",
":",
"return",
"None"
] | The mean of ``background`` values within the source segment.
Pixel values that are masked in the input ``data``, including
any non-finite pixel values (i.e. NaN, infs) that are
automatically masked, are also masked in the background array. | [
"The",
"mean",
"of",
"background",
"values",
"within",
"the",
"source",
"segment",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L886-L901 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.background_at_centroid | def background_at_centroid(self):
"""
The value of the ``background`` at the position of the source
centroid.
The background value at fractional position values are
determined using bilinear interpolation.
"""
from scipy.ndimage import map_coordinates
if self._background is not None:
# centroid can still be NaN if all data values are <= 0
if (self._is_completely_masked or
np.any(~np.isfinite(self.centroid))):
return np.nan * self._background_unit # unit for table
else:
value = map_coordinates(self._background,
[[self.ycentroid.value],
[self.xcentroid.value]], order=1,
mode='nearest')[0]
return value * self._background_unit
else:
return None | python | def background_at_centroid(self):
"""
The value of the ``background`` at the position of the source
centroid.
The background value at fractional position values are
determined using bilinear interpolation.
"""
from scipy.ndimage import map_coordinates
if self._background is not None:
# centroid can still be NaN if all data values are <= 0
if (self._is_completely_masked or
np.any(~np.isfinite(self.centroid))):
return np.nan * self._background_unit # unit for table
else:
value = map_coordinates(self._background,
[[self.ycentroid.value],
[self.xcentroid.value]], order=1,
mode='nearest')[0]
return value * self._background_unit
else:
return None | [
"def",
"background_at_centroid",
"(",
"self",
")",
":",
"from",
"scipy",
".",
"ndimage",
"import",
"map_coordinates",
"if",
"self",
".",
"_background",
"is",
"not",
"None",
":",
"# centroid can still be NaN if all data values are <= 0",
"if",
"(",
"self",
".",
"_is_completely_masked",
"or",
"np",
".",
"any",
"(",
"~",
"np",
".",
"isfinite",
"(",
"self",
".",
"centroid",
")",
")",
")",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_background_unit",
"# unit for table",
"else",
":",
"value",
"=",
"map_coordinates",
"(",
"self",
".",
"_background",
",",
"[",
"[",
"self",
".",
"ycentroid",
".",
"value",
"]",
",",
"[",
"self",
".",
"xcentroid",
".",
"value",
"]",
"]",
",",
"order",
"=",
"1",
",",
"mode",
"=",
"'nearest'",
")",
"[",
"0",
"]",
"return",
"value",
"*",
"self",
".",
"_background_unit",
"else",
":",
"return",
"None"
] | The value of the ``background`` at the position of the source
centroid.
The background value at fractional position values are
determined using bilinear interpolation. | [
"The",
"value",
"of",
"the",
"background",
"at",
"the",
"position",
"of",
"the",
"source",
"centroid",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L904-L928 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.perimeter | def perimeter(self):
"""
The total perimeter of the source segment, approximated lines
through the centers of the border pixels using a 4-connectivity.
If any masked pixels make holes within the source segment, then
the perimeter around the inner hole (e.g. an annulus) will also
contribute to the total perimeter.
"""
if self._is_completely_masked:
return np.nan * u.pix # unit for table
else:
from skimage.measure import perimeter
return perimeter(~self._total_mask, neighbourhood=4) * u.pix | python | def perimeter(self):
"""
The total perimeter of the source segment, approximated lines
through the centers of the border pixels using a 4-connectivity.
If any masked pixels make holes within the source segment, then
the perimeter around the inner hole (e.g. an annulus) will also
contribute to the total perimeter.
"""
if self._is_completely_masked:
return np.nan * u.pix # unit for table
else:
from skimage.measure import perimeter
return perimeter(~self._total_mask, neighbourhood=4) * u.pix | [
"def",
"perimeter",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"u",
".",
"pix",
"# unit for table",
"else",
":",
"from",
"skimage",
".",
"measure",
"import",
"perimeter",
"return",
"perimeter",
"(",
"~",
"self",
".",
"_total_mask",
",",
"neighbourhood",
"=",
"4",
")",
"*",
"u",
".",
"pix"
] | The total perimeter of the source segment, approximated lines
through the centers of the border pixels using a 4-connectivity.
If any masked pixels make holes within the source segment, then
the perimeter around the inner hole (e.g. an annulus) will also
contribute to the total perimeter. | [
"The",
"total",
"perimeter",
"of",
"the",
"source",
"segment",
"approximated",
"lines",
"through",
"the",
"centers",
"of",
"the",
"border",
"pixels",
"using",
"a",
"4",
"-",
"connectivity",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L957-L971 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.inertia_tensor | def inertia_tensor(self):
"""
The inertia tensor of the source for the rotation around its
center of mass.
"""
mu = self.moments_central
a = mu[0, 2]
b = -mu[1, 1]
c = mu[2, 0]
return np.array([[a, b], [b, c]]) * u.pix**2 | python | def inertia_tensor(self):
"""
The inertia tensor of the source for the rotation around its
center of mass.
"""
mu = self.moments_central
a = mu[0, 2]
b = -mu[1, 1]
c = mu[2, 0]
return np.array([[a, b], [b, c]]) * u.pix**2 | [
"def",
"inertia_tensor",
"(",
"self",
")",
":",
"mu",
"=",
"self",
".",
"moments_central",
"a",
"=",
"mu",
"[",
"0",
",",
"2",
"]",
"b",
"=",
"-",
"mu",
"[",
"1",
",",
"1",
"]",
"c",
"=",
"mu",
"[",
"2",
",",
"0",
"]",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"a",
",",
"b",
"]",
",",
"[",
"b",
",",
"c",
"]",
"]",
")",
"*",
"u",
".",
"pix",
"**",
"2"
] | The inertia tensor of the source for the rotation around its
center of mass. | [
"The",
"inertia",
"tensor",
"of",
"the",
"source",
"for",
"the",
"rotation",
"around",
"its",
"center",
"of",
"mass",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L974-L984 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.covariance | def covariance(self):
"""
The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source.
"""
mu = self.moments_central
if mu[0, 0] != 0:
m = mu / mu[0, 0]
covariance = self._check_covariance(
np.array([[m[0, 2], m[1, 1]], [m[1, 1], m[2, 0]]]))
return covariance * u.pix**2
else:
return np.empty((2, 2)) * np.nan * u.pix**2 | python | def covariance(self):
"""
The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source.
"""
mu = self.moments_central
if mu[0, 0] != 0:
m = mu / mu[0, 0]
covariance = self._check_covariance(
np.array([[m[0, 2], m[1, 1]], [m[1, 1], m[2, 0]]]))
return covariance * u.pix**2
else:
return np.empty((2, 2)) * np.nan * u.pix**2 | [
"def",
"covariance",
"(",
"self",
")",
":",
"mu",
"=",
"self",
".",
"moments_central",
"if",
"mu",
"[",
"0",
",",
"0",
"]",
"!=",
"0",
":",
"m",
"=",
"mu",
"/",
"mu",
"[",
"0",
",",
"0",
"]",
"covariance",
"=",
"self",
".",
"_check_covariance",
"(",
"np",
".",
"array",
"(",
"[",
"[",
"m",
"[",
"0",
",",
"2",
"]",
",",
"m",
"[",
"1",
",",
"1",
"]",
"]",
",",
"[",
"m",
"[",
"1",
",",
"1",
"]",
",",
"m",
"[",
"2",
",",
"0",
"]",
"]",
"]",
")",
")",
"return",
"covariance",
"*",
"u",
".",
"pix",
"**",
"2",
"else",
":",
"return",
"np",
".",
"empty",
"(",
"(",
"2",
",",
"2",
")",
")",
"*",
"np",
".",
"nan",
"*",
"u",
".",
"pix",
"**",
"2"
] | The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source. | [
"The",
"covariance",
"matrix",
"of",
"the",
"2D",
"Gaussian",
"function",
"that",
"has",
"the",
"same",
"second",
"-",
"order",
"moments",
"as",
"the",
"source",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L987-L1000 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.covariance_eigvals | def covariance_eigvals(self):
"""
The two eigenvalues of the `covariance` matrix in decreasing
order.
"""
if not np.isnan(np.sum(self.covariance)):
eigvals = np.linalg.eigvals(self.covariance)
if np.any(eigvals < 0): # negative variance
return (np.nan, np.nan) * u.pix**2 # pragma: no cover
return (np.max(eigvals), np.min(eigvals)) * u.pix**2
else:
return (np.nan, np.nan) * u.pix**2 | python | def covariance_eigvals(self):
"""
The two eigenvalues of the `covariance` matrix in decreasing
order.
"""
if not np.isnan(np.sum(self.covariance)):
eigvals = np.linalg.eigvals(self.covariance)
if np.any(eigvals < 0): # negative variance
return (np.nan, np.nan) * u.pix**2 # pragma: no cover
return (np.max(eigvals), np.min(eigvals)) * u.pix**2
else:
return (np.nan, np.nan) * u.pix**2 | [
"def",
"covariance_eigvals",
"(",
"self",
")",
":",
"if",
"not",
"np",
".",
"isnan",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"covariance",
")",
")",
":",
"eigvals",
"=",
"np",
".",
"linalg",
".",
"eigvals",
"(",
"self",
".",
"covariance",
")",
"if",
"np",
".",
"any",
"(",
"eigvals",
"<",
"0",
")",
":",
"# negative variance",
"return",
"(",
"np",
".",
"nan",
",",
"np",
".",
"nan",
")",
"*",
"u",
".",
"pix",
"**",
"2",
"# pragma: no cover",
"return",
"(",
"np",
".",
"max",
"(",
"eigvals",
")",
",",
"np",
".",
"min",
"(",
"eigvals",
")",
")",
"*",
"u",
".",
"pix",
"**",
"2",
"else",
":",
"return",
"(",
"np",
".",
"nan",
",",
"np",
".",
"nan",
")",
"*",
"u",
".",
"pix",
"**",
"2"
] | The two eigenvalues of the `covariance` matrix in decreasing
order. | [
"The",
"two",
"eigenvalues",
"of",
"the",
"covariance",
"matrix",
"in",
"decreasing",
"order",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L1024-L1036 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.eccentricity | def eccentricity(self):
"""
The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}}
where :math:`a` and :math:`b` are the lengths of the semimajor
and semiminor axes, respectively.
"""
l1, l2 = self.covariance_eigvals
if l1 == 0:
return 0. # pragma: no cover
return np.sqrt(1. - (l2 / l1)) | python | def eccentricity(self):
"""
The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}}
where :math:`a` and :math:`b` are the lengths of the semimajor
and semiminor axes, respectively.
"""
l1, l2 = self.covariance_eigvals
if l1 == 0:
return 0. # pragma: no cover
return np.sqrt(1. - (l2 / l1)) | [
"def",
"eccentricity",
"(",
"self",
")",
":",
"l1",
",",
"l2",
"=",
"self",
".",
"covariance_eigvals",
"if",
"l1",
"==",
"0",
":",
"return",
"0.",
"# pragma: no cover",
"return",
"np",
".",
"sqrt",
"(",
"1.",
"-",
"(",
"l2",
"/",
"l1",
")",
")"
] | The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}}
where :math:`a` and :math:`b` are the lengths of the semimajor
and semiminor axes, respectively. | [
"The",
"eccentricity",
"of",
"the",
"2D",
"Gaussian",
"function",
"that",
"has",
"the",
"same",
"second",
"-",
"order",
"moments",
"as",
"the",
"source",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L1061-L1078 | train |
astropy/photutils | photutils/segmentation/properties.py | SourceProperties.orientation | def orientation(self):
"""
The angle in radians between the ``x`` axis and the major axis
of the 2D Gaussian function that has the same second-order
moments as the source. The angle increases in the
counter-clockwise direction.
"""
a, b, b, c = self.covariance.flat
if a < 0 or c < 0: # negative variance
return np.nan * u.rad # pragma: no cover
return 0.5 * np.arctan2(2. * b, (a - c)) | python | def orientation(self):
"""
The angle in radians between the ``x`` axis and the major axis
of the 2D Gaussian function that has the same second-order
moments as the source. The angle increases in the
counter-clockwise direction.
"""
a, b, b, c = self.covariance.flat
if a < 0 or c < 0: # negative variance
return np.nan * u.rad # pragma: no cover
return 0.5 * np.arctan2(2. * b, (a - c)) | [
"def",
"orientation",
"(",
"self",
")",
":",
"a",
",",
"b",
",",
"b",
",",
"c",
"=",
"self",
".",
"covariance",
".",
"flat",
"if",
"a",
"<",
"0",
"or",
"c",
"<",
"0",
":",
"# negative variance",
"return",
"np",
".",
"nan",
"*",
"u",
".",
"rad",
"# pragma: no cover",
"return",
"0.5",
"*",
"np",
".",
"arctan2",
"(",
"2.",
"*",
"b",
",",
"(",
"a",
"-",
"c",
")",
")"
] | The angle in radians between the ``x`` axis and the major axis
of the 2D Gaussian function that has the same second-order
moments as the source. The angle increases in the
counter-clockwise direction. | [
"The",
"angle",
"in",
"radians",
"between",
"the",
"x",
"axis",
"and",
"the",
"major",
"axis",
"of",
"the",
"2D",
"Gaussian",
"function",
"that",
"has",
"the",
"same",
"second",
"-",
"order",
"moments",
"as",
"the",
"source",
".",
"The",
"angle",
"increases",
"in",
"the",
"counter",
"-",
"clockwise",
"direction",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L1081-L1092 | train |
astropy/photutils | photutils/utils/stats.py | _mesh_values | def _mesh_values(data, box_size):
"""
Extract all the data values in boxes of size ``box_size``.
Values from incomplete boxes, either because of the image edges or
masked pixels, are not returned.
Parameters
----------
data : 2D `~numpy.ma.MaskedArray`
The input masked array.
box_size : int
The box size.
Returns
-------
result : 2D `~numpy.ndarray`
A 2D array containing the data values in the boxes (along the x
axis).
"""
data = np.ma.asanyarray(data)
ny, nx = data.shape
nyboxes = ny // box_size
nxboxes = nx // box_size
# include only complete boxes
ny_crop = nyboxes * box_size
nx_crop = nxboxes * box_size
data = data[0:ny_crop, 0:nx_crop]
# a reshaped 2D masked array with mesh data along the x axis
data = np.ma.swapaxes(data.reshape(
nyboxes, box_size, nxboxes, box_size), 1, 2).reshape(
nyboxes * nxboxes, box_size * box_size)
# include only boxes without any masked pixels
idx = np.where(np.ma.count_masked(data, axis=1) == 0)
return data[idx] | python | def _mesh_values(data, box_size):
"""
Extract all the data values in boxes of size ``box_size``.
Values from incomplete boxes, either because of the image edges or
masked pixels, are not returned.
Parameters
----------
data : 2D `~numpy.ma.MaskedArray`
The input masked array.
box_size : int
The box size.
Returns
-------
result : 2D `~numpy.ndarray`
A 2D array containing the data values in the boxes (along the x
axis).
"""
data = np.ma.asanyarray(data)
ny, nx = data.shape
nyboxes = ny // box_size
nxboxes = nx // box_size
# include only complete boxes
ny_crop = nyboxes * box_size
nx_crop = nxboxes * box_size
data = data[0:ny_crop, 0:nx_crop]
# a reshaped 2D masked array with mesh data along the x axis
data = np.ma.swapaxes(data.reshape(
nyboxes, box_size, nxboxes, box_size), 1, 2).reshape(
nyboxes * nxboxes, box_size * box_size)
# include only boxes without any masked pixels
idx = np.where(np.ma.count_masked(data, axis=1) == 0)
return data[idx] | [
"def",
"_mesh_values",
"(",
"data",
",",
"box_size",
")",
":",
"data",
"=",
"np",
".",
"ma",
".",
"asanyarray",
"(",
"data",
")",
"ny",
",",
"nx",
"=",
"data",
".",
"shape",
"nyboxes",
"=",
"ny",
"//",
"box_size",
"nxboxes",
"=",
"nx",
"//",
"box_size",
"# include only complete boxes",
"ny_crop",
"=",
"nyboxes",
"*",
"box_size",
"nx_crop",
"=",
"nxboxes",
"*",
"box_size",
"data",
"=",
"data",
"[",
"0",
":",
"ny_crop",
",",
"0",
":",
"nx_crop",
"]",
"# a reshaped 2D masked array with mesh data along the x axis",
"data",
"=",
"np",
".",
"ma",
".",
"swapaxes",
"(",
"data",
".",
"reshape",
"(",
"nyboxes",
",",
"box_size",
",",
"nxboxes",
",",
"box_size",
")",
",",
"1",
",",
"2",
")",
".",
"reshape",
"(",
"nyboxes",
"*",
"nxboxes",
",",
"box_size",
"*",
"box_size",
")",
"# include only boxes without any masked pixels",
"idx",
"=",
"np",
".",
"where",
"(",
"np",
".",
"ma",
".",
"count_masked",
"(",
"data",
",",
"axis",
"=",
"1",
")",
"==",
"0",
")",
"return",
"data",
"[",
"idx",
"]"
] | Extract all the data values in boxes of size ``box_size``.
Values from incomplete boxes, either because of the image edges or
masked pixels, are not returned.
Parameters
----------
data : 2D `~numpy.ma.MaskedArray`
The input masked array.
box_size : int
The box size.
Returns
-------
result : 2D `~numpy.ndarray`
A 2D array containing the data values in the boxes (along the x
axis). | [
"Extract",
"all",
"the",
"data",
"values",
"in",
"boxes",
"of",
"size",
"box_size",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/utils/stats.py#L9-L50 | train |
astropy/photutils | photutils/utils/stats.py | std_blocksum | def std_blocksum(data, block_sizes, mask=None):
"""
Calculate the standard deviation of block-summed data values at
sizes of ``block_sizes``.
Values from incomplete blocks, either because of the image edges or
masked pixels, are not included.
Parameters
----------
data : array-like
The 2D array to block sum.
block_sizes : int, array-like of int
An array of integer (square) block sizes.
mask : array-like (bool), optional
A boolean mask, with the same shape as ``data``, where a `True`
value indicates the corresponding element of ``data`` is masked.
Blocks that contain *any* masked data are excluded from
calculations.
Returns
-------
result : `~numpy.ndarray`
An array of the standard deviations of the block-summed array
for the input ``block_sizes``.
"""
data = np.ma.asanyarray(data)
if mask is not None and mask is not np.ma.nomask:
mask = np.asanyarray(mask)
if data.shape != mask.shape:
raise ValueError('data and mask must have the same shape.')
data.mask |= mask
stds = []
block_sizes = np.atleast_1d(block_sizes)
for block_size in block_sizes:
mesh_values = _mesh_values(data, block_size)
block_sums = np.sum(mesh_values, axis=1)
stds.append(np.std(block_sums))
return np.array(stds) | python | def std_blocksum(data, block_sizes, mask=None):
"""
Calculate the standard deviation of block-summed data values at
sizes of ``block_sizes``.
Values from incomplete blocks, either because of the image edges or
masked pixels, are not included.
Parameters
----------
data : array-like
The 2D array to block sum.
block_sizes : int, array-like of int
An array of integer (square) block sizes.
mask : array-like (bool), optional
A boolean mask, with the same shape as ``data``, where a `True`
value indicates the corresponding element of ``data`` is masked.
Blocks that contain *any* masked data are excluded from
calculations.
Returns
-------
result : `~numpy.ndarray`
An array of the standard deviations of the block-summed array
for the input ``block_sizes``.
"""
data = np.ma.asanyarray(data)
if mask is not None and mask is not np.ma.nomask:
mask = np.asanyarray(mask)
if data.shape != mask.shape:
raise ValueError('data and mask must have the same shape.')
data.mask |= mask
stds = []
block_sizes = np.atleast_1d(block_sizes)
for block_size in block_sizes:
mesh_values = _mesh_values(data, block_size)
block_sums = np.sum(mesh_values, axis=1)
stds.append(np.std(block_sums))
return np.array(stds) | [
"def",
"std_blocksum",
"(",
"data",
",",
"block_sizes",
",",
"mask",
"=",
"None",
")",
":",
"data",
"=",
"np",
".",
"ma",
".",
"asanyarray",
"(",
"data",
")",
"if",
"mask",
"is",
"not",
"None",
"and",
"mask",
"is",
"not",
"np",
".",
"ma",
".",
"nomask",
":",
"mask",
"=",
"np",
".",
"asanyarray",
"(",
"mask",
")",
"if",
"data",
".",
"shape",
"!=",
"mask",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"'data and mask must have the same shape.'",
")",
"data",
".",
"mask",
"|=",
"mask",
"stds",
"=",
"[",
"]",
"block_sizes",
"=",
"np",
".",
"atleast_1d",
"(",
"block_sizes",
")",
"for",
"block_size",
"in",
"block_sizes",
":",
"mesh_values",
"=",
"_mesh_values",
"(",
"data",
",",
"block_size",
")",
"block_sums",
"=",
"np",
".",
"sum",
"(",
"mesh_values",
",",
"axis",
"=",
"1",
")",
"stds",
".",
"append",
"(",
"np",
".",
"std",
"(",
"block_sums",
")",
")",
"return",
"np",
".",
"array",
"(",
"stds",
")"
] | Calculate the standard deviation of block-summed data values at
sizes of ``block_sizes``.
Values from incomplete blocks, either because of the image edges or
masked pixels, are not included.
Parameters
----------
data : array-like
The 2D array to block sum.
block_sizes : int, array-like of int
An array of integer (square) block sizes.
mask : array-like (bool), optional
A boolean mask, with the same shape as ``data``, where a `True`
value indicates the corresponding element of ``data`` is masked.
Blocks that contain *any* masked data are excluded from
calculations.
Returns
-------
result : `~numpy.ndarray`
An array of the standard deviations of the block-summed array
for the input ``block_sizes``. | [
"Calculate",
"the",
"standard",
"deviation",
"of",
"block",
"-",
"summed",
"data",
"values",
"at",
"sizes",
"of",
"block_sizes",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/utils/stats.py#L53-L97 | train |
astropy/photutils | photutils/psf/photometry.py | BasicPSFPhotometry.nstar | def nstar(self, image, star_groups):
"""
Fit, as appropriate, a compound or single model to the given
``star_groups``. Groups are fitted sequentially from the
smallest to the biggest. In each iteration, ``image`` is
subtracted by the previous fitted group.
Parameters
----------
image : numpy.ndarray
Background-subtracted image.
star_groups : `~astropy.table.Table`
This table must contain the following columns: ``id``,
``group_id``, ``x_0``, ``y_0``, ``flux_0``. ``x_0`` and
``y_0`` are initial estimates of the centroids and
``flux_0`` is an initial estimate of the flux. Additionally,
columns named as ``<param_name>_0`` are required if any
other parameter in the psf model is free (i.e., the
``fixed`` attribute of that parameter is ``False``).
Returns
-------
result_tab : `~astropy.table.Table`
Astropy table that contains photometry results.
image : numpy.ndarray
Residual image.
"""
result_tab = Table()
for param_tab_name in self._pars_to_output.keys():
result_tab.add_column(Column(name=param_tab_name))
unc_tab = Table()
for param, isfixed in self.psf_model.fixed.items():
if not isfixed:
unc_tab.add_column(Column(name=param + "_unc"))
y, x = np.indices(image.shape)
star_groups = star_groups.group_by('group_id')
for n in range(len(star_groups.groups)):
group_psf = get_grouped_psf_model(self.psf_model,
star_groups.groups[n],
self._pars_to_set)
usepixel = np.zeros_like(image, dtype=np.bool)
for row in star_groups.groups[n]:
usepixel[overlap_slices(large_array_shape=image.shape,
small_array_shape=self.fitshape,
position=(row['y_0'], row['x_0']),
mode='trim')[0]] = True
fit_model = self.fitter(group_psf, x[usepixel], y[usepixel],
image[usepixel])
param_table = self._model_params2table(fit_model,
len(star_groups.groups[n]))
result_tab = vstack([result_tab, param_table])
if 'param_cov' in self.fitter.fit_info.keys():
unc_tab = vstack([unc_tab,
self._get_uncertainties(
len(star_groups.groups[n]))])
try:
from astropy.nddata.utils import NoOverlapError
except ImportError:
raise ImportError("astropy 1.1 or greater is required in "
"order to use this class.")
# do not subtract if the fitting did not go well
try:
image = subtract_psf(image, self.psf_model, param_table,
subshape=self.fitshape)
except NoOverlapError:
pass
if 'param_cov' in self.fitter.fit_info.keys():
result_tab = hstack([result_tab, unc_tab])
return result_tab, image | python | def nstar(self, image, star_groups):
"""
Fit, as appropriate, a compound or single model to the given
``star_groups``. Groups are fitted sequentially from the
smallest to the biggest. In each iteration, ``image`` is
subtracted by the previous fitted group.
Parameters
----------
image : numpy.ndarray
Background-subtracted image.
star_groups : `~astropy.table.Table`
This table must contain the following columns: ``id``,
``group_id``, ``x_0``, ``y_0``, ``flux_0``. ``x_0`` and
``y_0`` are initial estimates of the centroids and
``flux_0`` is an initial estimate of the flux. Additionally,
columns named as ``<param_name>_0`` are required if any
other parameter in the psf model is free (i.e., the
``fixed`` attribute of that parameter is ``False``).
Returns
-------
result_tab : `~astropy.table.Table`
Astropy table that contains photometry results.
image : numpy.ndarray
Residual image.
"""
result_tab = Table()
for param_tab_name in self._pars_to_output.keys():
result_tab.add_column(Column(name=param_tab_name))
unc_tab = Table()
for param, isfixed in self.psf_model.fixed.items():
if not isfixed:
unc_tab.add_column(Column(name=param + "_unc"))
y, x = np.indices(image.shape)
star_groups = star_groups.group_by('group_id')
for n in range(len(star_groups.groups)):
group_psf = get_grouped_psf_model(self.psf_model,
star_groups.groups[n],
self._pars_to_set)
usepixel = np.zeros_like(image, dtype=np.bool)
for row in star_groups.groups[n]:
usepixel[overlap_slices(large_array_shape=image.shape,
small_array_shape=self.fitshape,
position=(row['y_0'], row['x_0']),
mode='trim')[0]] = True
fit_model = self.fitter(group_psf, x[usepixel], y[usepixel],
image[usepixel])
param_table = self._model_params2table(fit_model,
len(star_groups.groups[n]))
result_tab = vstack([result_tab, param_table])
if 'param_cov' in self.fitter.fit_info.keys():
unc_tab = vstack([unc_tab,
self._get_uncertainties(
len(star_groups.groups[n]))])
try:
from astropy.nddata.utils import NoOverlapError
except ImportError:
raise ImportError("astropy 1.1 or greater is required in "
"order to use this class.")
# do not subtract if the fitting did not go well
try:
image = subtract_psf(image, self.psf_model, param_table,
subshape=self.fitshape)
except NoOverlapError:
pass
if 'param_cov' in self.fitter.fit_info.keys():
result_tab = hstack([result_tab, unc_tab])
return result_tab, image | [
"def",
"nstar",
"(",
"self",
",",
"image",
",",
"star_groups",
")",
":",
"result_tab",
"=",
"Table",
"(",
")",
"for",
"param_tab_name",
"in",
"self",
".",
"_pars_to_output",
".",
"keys",
"(",
")",
":",
"result_tab",
".",
"add_column",
"(",
"Column",
"(",
"name",
"=",
"param_tab_name",
")",
")",
"unc_tab",
"=",
"Table",
"(",
")",
"for",
"param",
",",
"isfixed",
"in",
"self",
".",
"psf_model",
".",
"fixed",
".",
"items",
"(",
")",
":",
"if",
"not",
"isfixed",
":",
"unc_tab",
".",
"add_column",
"(",
"Column",
"(",
"name",
"=",
"param",
"+",
"\"_unc\"",
")",
")",
"y",
",",
"x",
"=",
"np",
".",
"indices",
"(",
"image",
".",
"shape",
")",
"star_groups",
"=",
"star_groups",
".",
"group_by",
"(",
"'group_id'",
")",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"star_groups",
".",
"groups",
")",
")",
":",
"group_psf",
"=",
"get_grouped_psf_model",
"(",
"self",
".",
"psf_model",
",",
"star_groups",
".",
"groups",
"[",
"n",
"]",
",",
"self",
".",
"_pars_to_set",
")",
"usepixel",
"=",
"np",
".",
"zeros_like",
"(",
"image",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"for",
"row",
"in",
"star_groups",
".",
"groups",
"[",
"n",
"]",
":",
"usepixel",
"[",
"overlap_slices",
"(",
"large_array_shape",
"=",
"image",
".",
"shape",
",",
"small_array_shape",
"=",
"self",
".",
"fitshape",
",",
"position",
"=",
"(",
"row",
"[",
"'y_0'",
"]",
",",
"row",
"[",
"'x_0'",
"]",
")",
",",
"mode",
"=",
"'trim'",
")",
"[",
"0",
"]",
"]",
"=",
"True",
"fit_model",
"=",
"self",
".",
"fitter",
"(",
"group_psf",
",",
"x",
"[",
"usepixel",
"]",
",",
"y",
"[",
"usepixel",
"]",
",",
"image",
"[",
"usepixel",
"]",
")",
"param_table",
"=",
"self",
".",
"_model_params2table",
"(",
"fit_model",
",",
"len",
"(",
"star_groups",
".",
"groups",
"[",
"n",
"]",
")",
")",
"result_tab",
"=",
"vstack",
"(",
"[",
"result_tab",
",",
"param_table",
"]",
")",
"if",
"'param_cov'",
"in",
"self",
".",
"fitter",
".",
"fit_info",
".",
"keys",
"(",
")",
":",
"unc_tab",
"=",
"vstack",
"(",
"[",
"unc_tab",
",",
"self",
".",
"_get_uncertainties",
"(",
"len",
"(",
"star_groups",
".",
"groups",
"[",
"n",
"]",
")",
")",
"]",
")",
"try",
":",
"from",
"astropy",
".",
"nddata",
".",
"utils",
"import",
"NoOverlapError",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"astropy 1.1 or greater is required in \"",
"\"order to use this class.\"",
")",
"# do not subtract if the fitting did not go well",
"try",
":",
"image",
"=",
"subtract_psf",
"(",
"image",
",",
"self",
".",
"psf_model",
",",
"param_table",
",",
"subshape",
"=",
"self",
".",
"fitshape",
")",
"except",
"NoOverlapError",
":",
"pass",
"if",
"'param_cov'",
"in",
"self",
".",
"fitter",
".",
"fit_info",
".",
"keys",
"(",
")",
":",
"result_tab",
"=",
"hstack",
"(",
"[",
"result_tab",
",",
"unc_tab",
"]",
")",
"return",
"result_tab",
",",
"image"
] | Fit, as appropriate, a compound or single model to the given
``star_groups``. Groups are fitted sequentially from the
smallest to the biggest. In each iteration, ``image`` is
subtracted by the previous fitted group.
Parameters
----------
image : numpy.ndarray
Background-subtracted image.
star_groups : `~astropy.table.Table`
This table must contain the following columns: ``id``,
``group_id``, ``x_0``, ``y_0``, ``flux_0``. ``x_0`` and
``y_0`` are initial estimates of the centroids and
``flux_0`` is an initial estimate of the flux. Additionally,
columns named as ``<param_name>_0`` are required if any
other parameter in the psf model is free (i.e., the
``fixed`` attribute of that parameter is ``False``).
Returns
-------
result_tab : `~astropy.table.Table`
Astropy table that contains photometry results.
image : numpy.ndarray
Residual image. | [
"Fit",
"as",
"appropriate",
"a",
"compound",
"or",
"single",
"model",
"to",
"the",
"given",
"star_groups",
".",
"Groups",
"are",
"fitted",
"sequentially",
"from",
"the",
"smallest",
"to",
"the",
"biggest",
".",
"In",
"each",
"iteration",
"image",
"is",
"subtracted",
"by",
"the",
"previous",
"fitted",
"group",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/photometry.py#L298-L375 | train |
astropy/photutils | photutils/psf/photometry.py | BasicPSFPhotometry._get_uncertainties | def _get_uncertainties(self, star_group_size):
"""
Retrieve uncertainties on fitted parameters from the fitter
object.
Parameters
----------
star_group_size : int
Number of stars in the given group.
Returns
-------
unc_tab : `~astropy.table.Table`
Table which contains uncertainties on the fitted parameters.
The uncertainties are reported as one standard deviation.
"""
unc_tab = Table()
for param_name in self.psf_model.param_names:
if not self.psf_model.fixed[param_name]:
unc_tab.add_column(Column(name=param_name + "_unc",
data=np.empty(star_group_size)))
if 'param_cov' in self.fitter.fit_info.keys():
if self.fitter.fit_info['param_cov'] is not None:
k = 0
n_fit_params = len(unc_tab.colnames)
for i in range(star_group_size):
unc_tab[i] = np.sqrt(np.diag(
self.fitter.fit_info['param_cov'])
)[k: k + n_fit_params]
k = k + n_fit_params
return unc_tab | python | def _get_uncertainties(self, star_group_size):
"""
Retrieve uncertainties on fitted parameters from the fitter
object.
Parameters
----------
star_group_size : int
Number of stars in the given group.
Returns
-------
unc_tab : `~astropy.table.Table`
Table which contains uncertainties on the fitted parameters.
The uncertainties are reported as one standard deviation.
"""
unc_tab = Table()
for param_name in self.psf_model.param_names:
if not self.psf_model.fixed[param_name]:
unc_tab.add_column(Column(name=param_name + "_unc",
data=np.empty(star_group_size)))
if 'param_cov' in self.fitter.fit_info.keys():
if self.fitter.fit_info['param_cov'] is not None:
k = 0
n_fit_params = len(unc_tab.colnames)
for i in range(star_group_size):
unc_tab[i] = np.sqrt(np.diag(
self.fitter.fit_info['param_cov'])
)[k: k + n_fit_params]
k = k + n_fit_params
return unc_tab | [
"def",
"_get_uncertainties",
"(",
"self",
",",
"star_group_size",
")",
":",
"unc_tab",
"=",
"Table",
"(",
")",
"for",
"param_name",
"in",
"self",
".",
"psf_model",
".",
"param_names",
":",
"if",
"not",
"self",
".",
"psf_model",
".",
"fixed",
"[",
"param_name",
"]",
":",
"unc_tab",
".",
"add_column",
"(",
"Column",
"(",
"name",
"=",
"param_name",
"+",
"\"_unc\"",
",",
"data",
"=",
"np",
".",
"empty",
"(",
"star_group_size",
")",
")",
")",
"if",
"'param_cov'",
"in",
"self",
".",
"fitter",
".",
"fit_info",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"fitter",
".",
"fit_info",
"[",
"'param_cov'",
"]",
"is",
"not",
"None",
":",
"k",
"=",
"0",
"n_fit_params",
"=",
"len",
"(",
"unc_tab",
".",
"colnames",
")",
"for",
"i",
"in",
"range",
"(",
"star_group_size",
")",
":",
"unc_tab",
"[",
"i",
"]",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"diag",
"(",
"self",
".",
"fitter",
".",
"fit_info",
"[",
"'param_cov'",
"]",
")",
")",
"[",
"k",
":",
"k",
"+",
"n_fit_params",
"]",
"k",
"=",
"k",
"+",
"n_fit_params",
"return",
"unc_tab"
] | Retrieve uncertainties on fitted parameters from the fitter
object.
Parameters
----------
star_group_size : int
Number of stars in the given group.
Returns
-------
unc_tab : `~astropy.table.Table`
Table which contains uncertainties on the fitted parameters.
The uncertainties are reported as one standard deviation. | [
"Retrieve",
"uncertainties",
"on",
"fitted",
"parameters",
"from",
"the",
"fitter",
"object",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/photometry.py#L403-L435 | train |
astropy/photutils | photutils/psf/photometry.py | BasicPSFPhotometry._model_params2table | def _model_params2table(self, fit_model, star_group_size):
"""
Place fitted parameters into an astropy table.
Parameters
----------
fit_model : `astropy.modeling.Fittable2DModel` instance
PSF or PRF model to fit the data. Could be one of the models
in this package like `~photutils.psf.sandbox.DiscretePRF`,
`~photutils.psf.IntegratedGaussianPRF`, or any other
suitable 2D model.
star_group_size : int
Number of stars in the given group.
Returns
-------
param_tab : `~astropy.table.Table`
Table that contains the fitted parameters.
"""
param_tab = Table()
for param_tab_name in self._pars_to_output.keys():
param_tab.add_column(Column(name=param_tab_name,
data=np.empty(star_group_size)))
if star_group_size > 1:
for i in range(star_group_size):
for param_tab_name, param_name in self._pars_to_output.items():
param_tab[param_tab_name][i] = getattr(fit_model,
param_name +
'_' + str(i)).value
else:
for param_tab_name, param_name in self._pars_to_output.items():
param_tab[param_tab_name] = getattr(fit_model, param_name).value
return param_tab | python | def _model_params2table(self, fit_model, star_group_size):
"""
Place fitted parameters into an astropy table.
Parameters
----------
fit_model : `astropy.modeling.Fittable2DModel` instance
PSF or PRF model to fit the data. Could be one of the models
in this package like `~photutils.psf.sandbox.DiscretePRF`,
`~photutils.psf.IntegratedGaussianPRF`, or any other
suitable 2D model.
star_group_size : int
Number of stars in the given group.
Returns
-------
param_tab : `~astropy.table.Table`
Table that contains the fitted parameters.
"""
param_tab = Table()
for param_tab_name in self._pars_to_output.keys():
param_tab.add_column(Column(name=param_tab_name,
data=np.empty(star_group_size)))
if star_group_size > 1:
for i in range(star_group_size):
for param_tab_name, param_name in self._pars_to_output.items():
param_tab[param_tab_name][i] = getattr(fit_model,
param_name +
'_' + str(i)).value
else:
for param_tab_name, param_name in self._pars_to_output.items():
param_tab[param_tab_name] = getattr(fit_model, param_name).value
return param_tab | [
"def",
"_model_params2table",
"(",
"self",
",",
"fit_model",
",",
"star_group_size",
")",
":",
"param_tab",
"=",
"Table",
"(",
")",
"for",
"param_tab_name",
"in",
"self",
".",
"_pars_to_output",
".",
"keys",
"(",
")",
":",
"param_tab",
".",
"add_column",
"(",
"Column",
"(",
"name",
"=",
"param_tab_name",
",",
"data",
"=",
"np",
".",
"empty",
"(",
"star_group_size",
")",
")",
")",
"if",
"star_group_size",
">",
"1",
":",
"for",
"i",
"in",
"range",
"(",
"star_group_size",
")",
":",
"for",
"param_tab_name",
",",
"param_name",
"in",
"self",
".",
"_pars_to_output",
".",
"items",
"(",
")",
":",
"param_tab",
"[",
"param_tab_name",
"]",
"[",
"i",
"]",
"=",
"getattr",
"(",
"fit_model",
",",
"param_name",
"+",
"'_'",
"+",
"str",
"(",
"i",
")",
")",
".",
"value",
"else",
":",
"for",
"param_tab_name",
",",
"param_name",
"in",
"self",
".",
"_pars_to_output",
".",
"items",
"(",
")",
":",
"param_tab",
"[",
"param_tab_name",
"]",
"=",
"getattr",
"(",
"fit_model",
",",
"param_name",
")",
".",
"value",
"return",
"param_tab"
] | Place fitted parameters into an astropy table.
Parameters
----------
fit_model : `astropy.modeling.Fittable2DModel` instance
PSF or PRF model to fit the data. Could be one of the models
in this package like `~photutils.psf.sandbox.DiscretePRF`,
`~photutils.psf.IntegratedGaussianPRF`, or any other
suitable 2D model.
star_group_size : int
Number of stars in the given group.
Returns
-------
param_tab : `~astropy.table.Table`
Table that contains the fitted parameters. | [
"Place",
"fitted",
"parameters",
"into",
"an",
"astropy",
"table",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/photometry.py#L437-L473 | train |
astropy/photutils | photutils/psf/photometry.py | IterativelySubtractedPSFPhotometry._do_photometry | def _do_photometry(self, param_tab, n_start=1):
"""
Helper function which performs the iterations of the photometry
process.
Parameters
----------
param_names : list
Names of the columns which represent the initial guesses.
For example, ['x_0', 'y_0', 'flux_0'], for intial guesses on
the center positions and the flux.
n_start : int
Integer representing the start index of the iteration. It
is 1 if init_guesses are None, and 2 otherwise.
Returns
-------
output_table : `~astropy.table.Table` or None
Table with the photometry results, i.e., centroids and
fluxes estimations and the initial estimates used to start
the fitting process.
"""
output_table = Table()
self._define_fit_param_names()
for (init_parname, fit_parname) in zip(self._pars_to_set.keys(),
self._pars_to_output.keys()):
output_table.add_column(Column(name=init_parname))
output_table.add_column(Column(name=fit_parname))
sources = self.finder(self._residual_image)
n = n_start
while(sources is not None and
(self.niters is None or n <= self.niters)):
apertures = CircularAperture((sources['xcentroid'],
sources['ycentroid']),
r=self.aperture_radius)
sources['aperture_flux'] = aperture_photometry(
self._residual_image, apertures)['aperture_sum']
init_guess_tab = Table(names=['id', 'x_0', 'y_0', 'flux_0'],
data=[sources['id'], sources['xcentroid'],
sources['ycentroid'],
sources['aperture_flux']])
for param_tab_name, param_name in self._pars_to_set.items():
if param_tab_name not in (['x_0', 'y_0', 'flux_0']):
init_guess_tab.add_column(
Column(name=param_tab_name,
data=(getattr(self.psf_model,
param_name) *
np.ones(len(sources)))))
star_groups = self.group_maker(init_guess_tab)
table, self._residual_image = super().nstar(
self._residual_image, star_groups)
star_groups = star_groups.group_by('group_id')
table = hstack([star_groups, table])
table['iter_detected'] = n*np.ones(table['x_fit'].shape,
dtype=np.int32)
output_table = vstack([output_table, table])
# do not warn if no sources are found beyond the first iteration
with warnings.catch_warnings():
warnings.simplefilter('ignore', NoDetectionsWarning)
sources = self.finder(self._residual_image)
n += 1
return output_table | python | def _do_photometry(self, param_tab, n_start=1):
"""
Helper function which performs the iterations of the photometry
process.
Parameters
----------
param_names : list
Names of the columns which represent the initial guesses.
For example, ['x_0', 'y_0', 'flux_0'], for intial guesses on
the center positions and the flux.
n_start : int
Integer representing the start index of the iteration. It
is 1 if init_guesses are None, and 2 otherwise.
Returns
-------
output_table : `~astropy.table.Table` or None
Table with the photometry results, i.e., centroids and
fluxes estimations and the initial estimates used to start
the fitting process.
"""
output_table = Table()
self._define_fit_param_names()
for (init_parname, fit_parname) in zip(self._pars_to_set.keys(),
self._pars_to_output.keys()):
output_table.add_column(Column(name=init_parname))
output_table.add_column(Column(name=fit_parname))
sources = self.finder(self._residual_image)
n = n_start
while(sources is not None and
(self.niters is None or n <= self.niters)):
apertures = CircularAperture((sources['xcentroid'],
sources['ycentroid']),
r=self.aperture_radius)
sources['aperture_flux'] = aperture_photometry(
self._residual_image, apertures)['aperture_sum']
init_guess_tab = Table(names=['id', 'x_0', 'y_0', 'flux_0'],
data=[sources['id'], sources['xcentroid'],
sources['ycentroid'],
sources['aperture_flux']])
for param_tab_name, param_name in self._pars_to_set.items():
if param_tab_name not in (['x_0', 'y_0', 'flux_0']):
init_guess_tab.add_column(
Column(name=param_tab_name,
data=(getattr(self.psf_model,
param_name) *
np.ones(len(sources)))))
star_groups = self.group_maker(init_guess_tab)
table, self._residual_image = super().nstar(
self._residual_image, star_groups)
star_groups = star_groups.group_by('group_id')
table = hstack([star_groups, table])
table['iter_detected'] = n*np.ones(table['x_fit'].shape,
dtype=np.int32)
output_table = vstack([output_table, table])
# do not warn if no sources are found beyond the first iteration
with warnings.catch_warnings():
warnings.simplefilter('ignore', NoDetectionsWarning)
sources = self.finder(self._residual_image)
n += 1
return output_table | [
"def",
"_do_photometry",
"(",
"self",
",",
"param_tab",
",",
"n_start",
"=",
"1",
")",
":",
"output_table",
"=",
"Table",
"(",
")",
"self",
".",
"_define_fit_param_names",
"(",
")",
"for",
"(",
"init_parname",
",",
"fit_parname",
")",
"in",
"zip",
"(",
"self",
".",
"_pars_to_set",
".",
"keys",
"(",
")",
",",
"self",
".",
"_pars_to_output",
".",
"keys",
"(",
")",
")",
":",
"output_table",
".",
"add_column",
"(",
"Column",
"(",
"name",
"=",
"init_parname",
")",
")",
"output_table",
".",
"add_column",
"(",
"Column",
"(",
"name",
"=",
"fit_parname",
")",
")",
"sources",
"=",
"self",
".",
"finder",
"(",
"self",
".",
"_residual_image",
")",
"n",
"=",
"n_start",
"while",
"(",
"sources",
"is",
"not",
"None",
"and",
"(",
"self",
".",
"niters",
"is",
"None",
"or",
"n",
"<=",
"self",
".",
"niters",
")",
")",
":",
"apertures",
"=",
"CircularAperture",
"(",
"(",
"sources",
"[",
"'xcentroid'",
"]",
",",
"sources",
"[",
"'ycentroid'",
"]",
")",
",",
"r",
"=",
"self",
".",
"aperture_radius",
")",
"sources",
"[",
"'aperture_flux'",
"]",
"=",
"aperture_photometry",
"(",
"self",
".",
"_residual_image",
",",
"apertures",
")",
"[",
"'aperture_sum'",
"]",
"init_guess_tab",
"=",
"Table",
"(",
"names",
"=",
"[",
"'id'",
",",
"'x_0'",
",",
"'y_0'",
",",
"'flux_0'",
"]",
",",
"data",
"=",
"[",
"sources",
"[",
"'id'",
"]",
",",
"sources",
"[",
"'xcentroid'",
"]",
",",
"sources",
"[",
"'ycentroid'",
"]",
",",
"sources",
"[",
"'aperture_flux'",
"]",
"]",
")",
"for",
"param_tab_name",
",",
"param_name",
"in",
"self",
".",
"_pars_to_set",
".",
"items",
"(",
")",
":",
"if",
"param_tab_name",
"not",
"in",
"(",
"[",
"'x_0'",
",",
"'y_0'",
",",
"'flux_0'",
"]",
")",
":",
"init_guess_tab",
".",
"add_column",
"(",
"Column",
"(",
"name",
"=",
"param_tab_name",
",",
"data",
"=",
"(",
"getattr",
"(",
"self",
".",
"psf_model",
",",
"param_name",
")",
"*",
"np",
".",
"ones",
"(",
"len",
"(",
"sources",
")",
")",
")",
")",
")",
"star_groups",
"=",
"self",
".",
"group_maker",
"(",
"init_guess_tab",
")",
"table",
",",
"self",
".",
"_residual_image",
"=",
"super",
"(",
")",
".",
"nstar",
"(",
"self",
".",
"_residual_image",
",",
"star_groups",
")",
"star_groups",
"=",
"star_groups",
".",
"group_by",
"(",
"'group_id'",
")",
"table",
"=",
"hstack",
"(",
"[",
"star_groups",
",",
"table",
"]",
")",
"table",
"[",
"'iter_detected'",
"]",
"=",
"n",
"*",
"np",
".",
"ones",
"(",
"table",
"[",
"'x_fit'",
"]",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"output_table",
"=",
"vstack",
"(",
"[",
"output_table",
",",
"table",
"]",
")",
"# do not warn if no sources are found beyond the first iteration",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"'ignore'",
",",
"NoDetectionsWarning",
")",
"sources",
"=",
"self",
".",
"finder",
"(",
"self",
".",
"_residual_image",
")",
"n",
"+=",
"1",
"return",
"output_table"
] | Helper function which performs the iterations of the photometry
process.
Parameters
----------
param_names : list
Names of the columns which represent the initial guesses.
For example, ['x_0', 'y_0', 'flux_0'], for intial guesses on
the center positions and the flux.
n_start : int
Integer representing the start index of the iteration. It
is 1 if init_guesses are None, and 2 otherwise.
Returns
-------
output_table : `~astropy.table.Table` or None
Table with the photometry results, i.e., centroids and
fluxes estimations and the initial estimates used to start
the fitting process. | [
"Helper",
"function",
"which",
"performs",
"the",
"iterations",
"of",
"the",
"photometry",
"process",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/photometry.py#L666-L740 | train |
astropy/photutils | photutils/utils/wcs_helpers.py | pixel_scale_angle_at_skycoord | def pixel_scale_angle_at_skycoord(skycoord, wcs, offset=1. * u.arcsec):
"""
Calculate the pixel scale and WCS rotation angle at the position of
a SkyCoord coordinate.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
The SkyCoord coordinate.
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
offset : `~astropy.units.Quantity`
A small angular offset to use to compute the pixel scale and
position angle.
Returns
-------
scale : `~astropy.units.Quantity`
The pixel scale in arcsec/pixel.
angle : `~astropy.units.Quantity`
The angle (in degrees) measured counterclockwise from the
positive x axis to the "North" axis of the celestial coordinate
system.
Notes
-----
If distortions are present in the image, the x and y pixel scales
likely differ. This function computes a single pixel scale along
the North/South axis.
"""
# We take a point directly "above" (in latitude) the input position
# and convert it to pixel coordinates, then we use the pixel deltas
# between the input and offset point to calculate the pixel scale and
# angle.
# Find the coordinates as a representation object
coord = skycoord.represent_as('unitspherical')
# Add a a small perturbation in the latitude direction (since longitude
# is more difficult because it is not directly an angle)
coord_new = UnitSphericalRepresentation(coord.lon, coord.lat + offset)
coord_offset = skycoord.realize_frame(coord_new)
# Find pixel coordinates of offset coordinates and pixel deltas
x_offset, y_offset = skycoord_to_pixel(coord_offset, wcs, mode='all')
x, y = skycoord_to_pixel(skycoord, wcs, mode='all')
dx = x_offset - x
dy = y_offset - y
scale = offset.to(u.arcsec) / (np.hypot(dx, dy) * u.pixel)
angle = (np.arctan2(dy, dx) * u.radian).to(u.deg)
return scale, angle | python | def pixel_scale_angle_at_skycoord(skycoord, wcs, offset=1. * u.arcsec):
"""
Calculate the pixel scale and WCS rotation angle at the position of
a SkyCoord coordinate.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
The SkyCoord coordinate.
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
offset : `~astropy.units.Quantity`
A small angular offset to use to compute the pixel scale and
position angle.
Returns
-------
scale : `~astropy.units.Quantity`
The pixel scale in arcsec/pixel.
angle : `~astropy.units.Quantity`
The angle (in degrees) measured counterclockwise from the
positive x axis to the "North" axis of the celestial coordinate
system.
Notes
-----
If distortions are present in the image, the x and y pixel scales
likely differ. This function computes a single pixel scale along
the North/South axis.
"""
# We take a point directly "above" (in latitude) the input position
# and convert it to pixel coordinates, then we use the pixel deltas
# between the input and offset point to calculate the pixel scale and
# angle.
# Find the coordinates as a representation object
coord = skycoord.represent_as('unitspherical')
# Add a a small perturbation in the latitude direction (since longitude
# is more difficult because it is not directly an angle)
coord_new = UnitSphericalRepresentation(coord.lon, coord.lat + offset)
coord_offset = skycoord.realize_frame(coord_new)
# Find pixel coordinates of offset coordinates and pixel deltas
x_offset, y_offset = skycoord_to_pixel(coord_offset, wcs, mode='all')
x, y = skycoord_to_pixel(skycoord, wcs, mode='all')
dx = x_offset - x
dy = y_offset - y
scale = offset.to(u.arcsec) / (np.hypot(dx, dy) * u.pixel)
angle = (np.arctan2(dy, dx) * u.radian).to(u.deg)
return scale, angle | [
"def",
"pixel_scale_angle_at_skycoord",
"(",
"skycoord",
",",
"wcs",
",",
"offset",
"=",
"1.",
"*",
"u",
".",
"arcsec",
")",
":",
"# We take a point directly \"above\" (in latitude) the input position",
"# and convert it to pixel coordinates, then we use the pixel deltas",
"# between the input and offset point to calculate the pixel scale and",
"# angle.",
"# Find the coordinates as a representation object",
"coord",
"=",
"skycoord",
".",
"represent_as",
"(",
"'unitspherical'",
")",
"# Add a a small perturbation in the latitude direction (since longitude",
"# is more difficult because it is not directly an angle)",
"coord_new",
"=",
"UnitSphericalRepresentation",
"(",
"coord",
".",
"lon",
",",
"coord",
".",
"lat",
"+",
"offset",
")",
"coord_offset",
"=",
"skycoord",
".",
"realize_frame",
"(",
"coord_new",
")",
"# Find pixel coordinates of offset coordinates and pixel deltas",
"x_offset",
",",
"y_offset",
"=",
"skycoord_to_pixel",
"(",
"coord_offset",
",",
"wcs",
",",
"mode",
"=",
"'all'",
")",
"x",
",",
"y",
"=",
"skycoord_to_pixel",
"(",
"skycoord",
",",
"wcs",
",",
"mode",
"=",
"'all'",
")",
"dx",
"=",
"x_offset",
"-",
"x",
"dy",
"=",
"y_offset",
"-",
"y",
"scale",
"=",
"offset",
".",
"to",
"(",
"u",
".",
"arcsec",
")",
"/",
"(",
"np",
".",
"hypot",
"(",
"dx",
",",
"dy",
")",
"*",
"u",
".",
"pixel",
")",
"angle",
"=",
"(",
"np",
".",
"arctan2",
"(",
"dy",
",",
"dx",
")",
"*",
"u",
".",
"radian",
")",
".",
"to",
"(",
"u",
".",
"deg",
")",
"return",
"scale",
",",
"angle"
] | Calculate the pixel scale and WCS rotation angle at the position of
a SkyCoord coordinate.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
The SkyCoord coordinate.
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
offset : `~astropy.units.Quantity`
A small angular offset to use to compute the pixel scale and
position angle.
Returns
-------
scale : `~astropy.units.Quantity`
The pixel scale in arcsec/pixel.
angle : `~astropy.units.Quantity`
The angle (in degrees) measured counterclockwise from the
positive x axis to the "North" axis of the celestial coordinate
system.
Notes
-----
If distortions are present in the image, the x and y pixel scales
likely differ. This function computes a single pixel scale along
the North/South axis. | [
"Calculate",
"the",
"pixel",
"scale",
"and",
"WCS",
"rotation",
"angle",
"at",
"the",
"position",
"of",
"a",
"SkyCoord",
"coordinate",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/utils/wcs_helpers.py#L9-L62 | train |
astropy/photutils | photutils/utils/wcs_helpers.py | pixel_to_icrs_coords | def pixel_to_icrs_coords(x, y, wcs):
"""
Convert pixel coordinates to ICRS Right Ascension and Declination.
This is merely a convenience function to extract RA and Dec. from a
`~astropy.coordinates.SkyCoord` instance so they can be put in
separate columns in a `~astropy.table.Table`.
Parameters
----------
x : float or array-like
The x pixel coordinate.
y : float or array-like
The y pixel coordinate.
wcs : `~astropy.wcs.WCS`
The WCS transformation to use to convert from pixel coordinates
to ICRS world coordinates.
`~astropy.table.Table`.
Returns
-------
ra : `~astropy.units.Quantity`
The ICRS Right Ascension in degrees.
dec : `~astropy.units.Quantity`
The ICRS Declination in degrees.
"""
icrs_coords = pixel_to_skycoord(x, y, wcs).icrs
icrs_ra = icrs_coords.ra.degree * u.deg
icrs_dec = icrs_coords.dec.degree * u.deg
return icrs_ra, icrs_dec | python | def pixel_to_icrs_coords(x, y, wcs):
"""
Convert pixel coordinates to ICRS Right Ascension and Declination.
This is merely a convenience function to extract RA and Dec. from a
`~astropy.coordinates.SkyCoord` instance so they can be put in
separate columns in a `~astropy.table.Table`.
Parameters
----------
x : float or array-like
The x pixel coordinate.
y : float or array-like
The y pixel coordinate.
wcs : `~astropy.wcs.WCS`
The WCS transformation to use to convert from pixel coordinates
to ICRS world coordinates.
`~astropy.table.Table`.
Returns
-------
ra : `~astropy.units.Quantity`
The ICRS Right Ascension in degrees.
dec : `~astropy.units.Quantity`
The ICRS Declination in degrees.
"""
icrs_coords = pixel_to_skycoord(x, y, wcs).icrs
icrs_ra = icrs_coords.ra.degree * u.deg
icrs_dec = icrs_coords.dec.degree * u.deg
return icrs_ra, icrs_dec | [
"def",
"pixel_to_icrs_coords",
"(",
"x",
",",
"y",
",",
"wcs",
")",
":",
"icrs_coords",
"=",
"pixel_to_skycoord",
"(",
"x",
",",
"y",
",",
"wcs",
")",
".",
"icrs",
"icrs_ra",
"=",
"icrs_coords",
".",
"ra",
".",
"degree",
"*",
"u",
".",
"deg",
"icrs_dec",
"=",
"icrs_coords",
".",
"dec",
".",
"degree",
"*",
"u",
".",
"deg",
"return",
"icrs_ra",
",",
"icrs_dec"
] | Convert pixel coordinates to ICRS Right Ascension and Declination.
This is merely a convenience function to extract RA and Dec. from a
`~astropy.coordinates.SkyCoord` instance so they can be put in
separate columns in a `~astropy.table.Table`.
Parameters
----------
x : float or array-like
The x pixel coordinate.
y : float or array-like
The y pixel coordinate.
wcs : `~astropy.wcs.WCS`
The WCS transformation to use to convert from pixel coordinates
to ICRS world coordinates.
`~astropy.table.Table`.
Returns
-------
ra : `~astropy.units.Quantity`
The ICRS Right Ascension in degrees.
dec : `~astropy.units.Quantity`
The ICRS Declination in degrees. | [
"Convert",
"pixel",
"coordinates",
"to",
"ICRS",
"Right",
"Ascension",
"and",
"Declination",
"."
] | cc9bb4534ab76bac98cb5f374a348a2573d10401 | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/utils/wcs_helpers.py#L95-L129 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.