repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
suds-community/suds | suds/mx/literal.py | Typed.encode | def encode(self, node, content):
"""
Add (SOAP) encoding information if needed.
The encoding information is added only if the resolved type is derived
by extension. Furthermore, the xsi:type value is qualified by namespace
only if the content (tag) and referenced type are in different
namespaces.
"""
if content.type.any():
return
if not content.real.extension():
return
if content.type.resolve() == content.real:
return
ns = None
name = content.real.name
if self.xstq:
ns = content.real.namespace("ns1")
Typer.manual(node, name, ns) | python | def encode(self, node, content):
"""
Add (SOAP) encoding information if needed.
The encoding information is added only if the resolved type is derived
by extension. Furthermore, the xsi:type value is qualified by namespace
only if the content (tag) and referenced type are in different
namespaces.
"""
if content.type.any():
return
if not content.real.extension():
return
if content.type.resolve() == content.real:
return
ns = None
name = content.real.name
if self.xstq:
ns = content.real.namespace("ns1")
Typer.manual(node, name, ns) | Add (SOAP) encoding information if needed.
The encoding information is added only if the resolved type is derived
by extension. Furthermore, the xsi:type value is qualified by namespace
only if the content (tag) and referenced type are in different
namespaces. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/literal.py#L185-L205 |
suds-community/suds | suds/mx/literal.py | Typed.skip | def skip(self, content):
"""
Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
@rtype: bool
"""
if self.optional(content):
v = content.value
if v is None:
return True
if isinstance(v, (list, tuple)) and not v:
return True
return False | python | def skip(self, content):
"""
Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
@rtype: bool
"""
if self.optional(content):
v = content.value
if v is None:
return True
if isinstance(v, (list, tuple)) and not v:
return True
return False | Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
@rtype: bool | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/literal.py#L207-L226 |
suds-community/suds | tools/suds_devel/egg.py | _detect_eggs_in_folder | def _detect_eggs_in_folder(folder):
"""
Detect egg distributions located in the given folder.
Only direct folder content is considered and subfolders are not searched
recursively.
"""
eggs = {}
for x in os.listdir(folder):
zip = x.endswith(_zip_ext)
if zip:
root = x[:-len(_zip_ext)]
egg = _Egg.NONE
elif x.endswith(_egg_ext):
root = x[:-len(_egg_ext)]
if os.path.isdir(os.path.join(folder, x)):
egg = _Egg.FOLDER
else:
egg = _Egg.FILE
else:
continue
try:
info = eggs[root]
except KeyError:
eggs[root] = _Egg(os.path.join(folder, root), egg, zip)
else:
if egg is not _Egg.NONE:
info.set_egg(egg)
if zip:
info.set_zip()
return eggs.values() | python | def _detect_eggs_in_folder(folder):
"""
Detect egg distributions located in the given folder.
Only direct folder content is considered and subfolders are not searched
recursively.
"""
eggs = {}
for x in os.listdir(folder):
zip = x.endswith(_zip_ext)
if zip:
root = x[:-len(_zip_ext)]
egg = _Egg.NONE
elif x.endswith(_egg_ext):
root = x[:-len(_egg_ext)]
if os.path.isdir(os.path.join(folder, x)):
egg = _Egg.FOLDER
else:
egg = _Egg.FILE
else:
continue
try:
info = eggs[root]
except KeyError:
eggs[root] = _Egg(os.path.join(folder, root), egg, zip)
else:
if egg is not _Egg.NONE:
info.set_egg(egg)
if zip:
info.set_zip()
return eggs.values() | Detect egg distributions located in the given folder.
Only direct folder content is considered and subfolders are not searched
recursively. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/egg.py#L144-L175 |
suds-community/suds | tools/suds_devel/egg.py | _Egg.normalize | def normalize(self):
"""
Makes sure this egg distribution is stored only as an egg file.
The egg file will be created from another existing distribution format
if needed.
"""
if self.has_egg_file():
if self.has_zip():
self.__remove_zip()
else:
if self.has_egg_folder():
if not self.has_zip():
self.__zip_egg_folder()
self.__remove_egg_folder()
self.__rename_zip_to_egg() | python | def normalize(self):
"""
Makes sure this egg distribution is stored only as an egg file.
The egg file will be created from another existing distribution format
if needed.
"""
if self.has_egg_file():
if self.has_zip():
self.__remove_zip()
else:
if self.has_egg_folder():
if not self.has_zip():
self.__zip_egg_folder()
self.__remove_egg_folder()
self.__rename_zip_to_egg() | Makes sure this egg distribution is stored only as an egg file.
The egg file will be created from another existing distribution format
if needed. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/egg.py#L85-L101 |
suds-community/suds | suds/argparser.py | parse_args | def parse_args(method_name, param_defs, args, kwargs, external_param_processor,
extra_parameter_errors):
"""
Parse arguments for suds web service operation invocation functions.
Suds prepares Python function objects for invoking web service operations.
This function implements generic binding agnostic part of processing the
arguments passed when calling those function objects.
Argument parsing rules:
* Each input parameter element should be represented by single regular
Python function argument.
* At most one input parameter belonging to a single choice parameter
structure may have its value specified as something other than None.
* Positional arguments are mapped to choice group input parameters the
same as is done for a simple all/sequence group - each in turn.
Expects to be passed the web service operation's parameter definitions
(parameter name, type & optional ancestry information) in order and, based
on that, extracts the values for those parameter from the arguments
provided in the web service operation invocation call.
Ancestry information describes parameters constructed based on suds
library's automatic input parameter structure unwrapping. It is expected to
include the parameter's XSD schema 'ancestry' context, i.e. a list of all
the parent XSD schema tags containing the parameter's <element> tag. Such
ancestry context provides detailed information about how the parameter's
value is expected to be used, especially in relation to other input
parameters, e.g. at most one parameter value may be specified for
parameters directly belonging to the same choice input group.
Rules on acceptable ancestry items:
* Ancestry item's choice() method must return whether the item
represents a <choice> XSD schema tag.
* Passed ancestry items are used 'by address' internally and the same XSD
schema tag is expected to be identified by the exact same ancestry item
object during the whole argument processing.
During processing, each parameter's definition and value, together with any
additional pertinent information collected from the encountered parameter
definition structure, is passed on to the provided external parameter
processor function. There that information is expected to be used to
construct the actual binding specific web service operation invocation
request.
Raises a TypeError exception in case any argument related errors are
detected. The exceptions raised have been constructed to make them as
similar as possible to their respective exceptions raised during regular
Python function argument checking.
Does not support multiple same-named input parameters.
"""
arg_parser = _ArgParser(method_name, param_defs, external_param_processor)
return arg_parser(args, kwargs, extra_parameter_errors) | python | def parse_args(method_name, param_defs, args, kwargs, external_param_processor,
extra_parameter_errors):
"""
Parse arguments for suds web service operation invocation functions.
Suds prepares Python function objects for invoking web service operations.
This function implements generic binding agnostic part of processing the
arguments passed when calling those function objects.
Argument parsing rules:
* Each input parameter element should be represented by single regular
Python function argument.
* At most one input parameter belonging to a single choice parameter
structure may have its value specified as something other than None.
* Positional arguments are mapped to choice group input parameters the
same as is done for a simple all/sequence group - each in turn.
Expects to be passed the web service operation's parameter definitions
(parameter name, type & optional ancestry information) in order and, based
on that, extracts the values for those parameter from the arguments
provided in the web service operation invocation call.
Ancestry information describes parameters constructed based on suds
library's automatic input parameter structure unwrapping. It is expected to
include the parameter's XSD schema 'ancestry' context, i.e. a list of all
the parent XSD schema tags containing the parameter's <element> tag. Such
ancestry context provides detailed information about how the parameter's
value is expected to be used, especially in relation to other input
parameters, e.g. at most one parameter value may be specified for
parameters directly belonging to the same choice input group.
Rules on acceptable ancestry items:
* Ancestry item's choice() method must return whether the item
represents a <choice> XSD schema tag.
* Passed ancestry items are used 'by address' internally and the same XSD
schema tag is expected to be identified by the exact same ancestry item
object during the whole argument processing.
During processing, each parameter's definition and value, together with any
additional pertinent information collected from the encountered parameter
definition structure, is passed on to the provided external parameter
processor function. There that information is expected to be used to
construct the actual binding specific web service operation invocation
request.
Raises a TypeError exception in case any argument related errors are
detected. The exceptions raised have been constructed to make them as
similar as possible to their respective exceptions raised during regular
Python function argument checking.
Does not support multiple same-named input parameters.
"""
arg_parser = _ArgParser(method_name, param_defs, external_param_processor)
return arg_parser(args, kwargs, extra_parameter_errors) | Parse arguments for suds web service operation invocation functions.
Suds prepares Python function objects for invoking web service operations.
This function implements generic binding agnostic part of processing the
arguments passed when calling those function objects.
Argument parsing rules:
* Each input parameter element should be represented by single regular
Python function argument.
* At most one input parameter belonging to a single choice parameter
structure may have its value specified as something other than None.
* Positional arguments are mapped to choice group input parameters the
same as is done for a simple all/sequence group - each in turn.
Expects to be passed the web service operation's parameter definitions
(parameter name, type & optional ancestry information) in order and, based
on that, extracts the values for those parameter from the arguments
provided in the web service operation invocation call.
Ancestry information describes parameters constructed based on suds
library's automatic input parameter structure unwrapping. It is expected to
include the parameter's XSD schema 'ancestry' context, i.e. a list of all
the parent XSD schema tags containing the parameter's <element> tag. Such
ancestry context provides detailed information about how the parameter's
value is expected to be used, especially in relation to other input
parameters, e.g. at most one parameter value may be specified for
parameters directly belonging to the same choice input group.
Rules on acceptable ancestry items:
* Ancestry item's choice() method must return whether the item
represents a <choice> XSD schema tag.
* Passed ancestry items are used 'by address' internally and the same XSD
schema tag is expected to be identified by the exact same ancestry item
object during the whole argument processing.
During processing, each parameter's definition and value, together with any
additional pertinent information collected from the encountered parameter
definition structure, is passed on to the provided external parameter
processor function. There that information is expected to be used to
construct the actual binding specific web service operation invocation
request.
Raises a TypeError exception in case any argument related errors are
detected. The exceptions raised have been constructed to make them as
similar as possible to their respective exceptions raised during regular
Python function argument checking.
Does not support multiple same-named input parameters. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L29-L83 |
suds-community/suds | suds/argparser.py | _ArgParser.__all_parameters_processed | def __all_parameters_processed(self):
"""
Finish the argument processing.
Should be called after all the web service operation's parameters have
been successfully processed and, afterwards, no further parameter
processing is allowed.
Returns a 2-tuple containing the number of required & allowed
arguments.
See the _ArgParser class description for more detailed information.
"""
assert self.active()
sentinel_frame = self.__stack[0]
self.__pop_frames_above(sentinel_frame)
assert len(self.__stack) == 1
self.__pop_top_frame()
assert not self.active()
args_required = sentinel_frame.args_required()
args_allowed = sentinel_frame.args_allowed()
self.__check_for_extra_arguments(args_required, args_allowed)
return args_required, args_allowed | python | def __all_parameters_processed(self):
"""
Finish the argument processing.
Should be called after all the web service operation's parameters have
been successfully processed and, afterwards, no further parameter
processing is allowed.
Returns a 2-tuple containing the number of required & allowed
arguments.
See the _ArgParser class description for more detailed information.
"""
assert self.active()
sentinel_frame = self.__stack[0]
self.__pop_frames_above(sentinel_frame)
assert len(self.__stack) == 1
self.__pop_top_frame()
assert not self.active()
args_required = sentinel_frame.args_required()
args_allowed = sentinel_frame.args_allowed()
self.__check_for_extra_arguments(args_required, args_allowed)
return args_required, args_allowed | Finish the argument processing.
Should be called after all the web service operation's parameters have
been successfully processed and, afterwards, no further parameter
processing is allowed.
Returns a 2-tuple containing the number of required & allowed
arguments.
See the _ArgParser class description for more detailed information. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L124-L147 |
suds-community/suds | suds/argparser.py | _ArgParser.__check_for_extra_arguments | def __check_for_extra_arguments(self, args_required, args_allowed):
"""
Report an error in case any extra arguments are detected.
Does nothing if reporting extra arguments as exceptions has not been
enabled.
May only be called after the argument processing has been completed.
"""
assert not self.active()
if not self.__extra_parameter_errors:
return
if self.__kwargs:
param_name = self.__kwargs.keys()[0]
if param_name in self.__params_with_arguments:
msg = "got multiple values for parameter '%s'"
else:
msg = "got an unexpected keyword argument '%s'"
self.__error(msg % (param_name,))
if self.__args:
def plural_suffix(count):
if count == 1:
return ""
return "s"
def plural_was_were(count):
if count == 1:
return "was"
return "were"
expected = args_required
if args_required != args_allowed:
expected = "%d to %d" % (args_required, args_allowed)
given = self.__args_count
msg_parts = ["takes %s positional argument" % (expected,),
plural_suffix(expected), " but %d " % (given,),
plural_was_were(given), " given"]
self.__error("".join(msg_parts)) | python | def __check_for_extra_arguments(self, args_required, args_allowed):
"""
Report an error in case any extra arguments are detected.
Does nothing if reporting extra arguments as exceptions has not been
enabled.
May only be called after the argument processing has been completed.
"""
assert not self.active()
if not self.__extra_parameter_errors:
return
if self.__kwargs:
param_name = self.__kwargs.keys()[0]
if param_name in self.__params_with_arguments:
msg = "got multiple values for parameter '%s'"
else:
msg = "got an unexpected keyword argument '%s'"
self.__error(msg % (param_name,))
if self.__args:
def plural_suffix(count):
if count == 1:
return ""
return "s"
def plural_was_were(count):
if count == 1:
return "was"
return "were"
expected = args_required
if args_required != args_allowed:
expected = "%d to %d" % (args_required, args_allowed)
given = self.__args_count
msg_parts = ["takes %s positional argument" % (expected,),
plural_suffix(expected), " but %d " % (given,),
plural_was_were(given), " given"]
self.__error("".join(msg_parts)) | Report an error in case any extra arguments are detected.
Does nothing if reporting extra arguments as exceptions has not been
enabled.
May only be called after the argument processing has been completed. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L149-L187 |
suds-community/suds | suds/argparser.py | _ArgParser.__frame_factory | def __frame_factory(self, ancestry_item):
"""Construct a new frame representing the given ancestry item."""
frame_class = Frame
if ancestry_item is not None and ancestry_item.choice():
frame_class = ChoiceFrame
return frame_class(ancestry_item, self.__error,
self.__extra_parameter_errors) | python | def __frame_factory(self, ancestry_item):
"""Construct a new frame representing the given ancestry item."""
frame_class = Frame
if ancestry_item is not None and ancestry_item.choice():
frame_class = ChoiceFrame
return frame_class(ancestry_item, self.__error,
self.__extra_parameter_errors) | Construct a new frame representing the given ancestry item. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L198-L204 |
suds-community/suds | suds/argparser.py | _ArgParser.__get_param_value | def __get_param_value(self, name):
"""
Extract a parameter value from the remaining given arguments.
Returns a 2-tuple consisting of the following:
* Boolean indicating whether an argument has been specified for the
requested input parameter.
* Parameter value.
"""
if self.__args:
return True, self.__args.pop(0)
try:
value = self.__kwargs.pop(name)
except KeyError:
return False, None
return True, value | python | def __get_param_value(self, name):
"""
Extract a parameter value from the remaining given arguments.
Returns a 2-tuple consisting of the following:
* Boolean indicating whether an argument has been specified for the
requested input parameter.
* Parameter value.
"""
if self.__args:
return True, self.__args.pop(0)
try:
value = self.__kwargs.pop(name)
except KeyError:
return False, None
return True, value | Extract a parameter value from the remaining given arguments.
Returns a 2-tuple consisting of the following:
* Boolean indicating whether an argument has been specified for the
requested input parameter.
* Parameter value. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L206-L222 |
suds-community/suds | suds/argparser.py | _ArgParser.__in_choice_context | def __in_choice_context(self):
"""
Whether we are currently processing a choice parameter group.
This includes processing a parameter defined directly or indirectly
within such a group.
May only be called during parameter processing or the result will be
calculated based on the context left behind by the previous parameter
processing if any.
"""
for x in self.__stack:
if x.__class__ is ChoiceFrame:
return True
return False | python | def __in_choice_context(self):
"""
Whether we are currently processing a choice parameter group.
This includes processing a parameter defined directly or indirectly
within such a group.
May only be called during parameter processing or the result will be
calculated based on the context left behind by the previous parameter
processing if any.
"""
for x in self.__stack:
if x.__class__ is ChoiceFrame:
return True
return False | Whether we are currently processing a choice parameter group.
This includes processing a parameter defined directly or indirectly
within such a group.
May only be called during parameter processing or the result will be
calculated based on the context left behind by the previous parameter
processing if any. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L224-L239 |
suds-community/suds | suds/argparser.py | _ArgParser.__init_run | def __init_run(self, args, kwargs, extra_parameter_errors):
"""Initializes data for a new argument parsing run."""
assert not self.active()
self.__args = list(args)
self.__kwargs = dict(kwargs)
self.__extra_parameter_errors = extra_parameter_errors
self.__args_count = len(args) + len(kwargs)
self.__params_with_arguments = set()
self.__stack = []
self.__push_frame(None) | python | def __init_run(self, args, kwargs, extra_parameter_errors):
"""Initializes data for a new argument parsing run."""
assert not self.active()
self.__args = list(args)
self.__kwargs = dict(kwargs)
self.__extra_parameter_errors = extra_parameter_errors
self.__args_count = len(args) + len(kwargs)
self.__params_with_arguments = set()
self.__stack = []
self.__push_frame(None) | Initializes data for a new argument parsing run. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L241-L250 |
suds-community/suds | suds/argparser.py | _ArgParser.__match_ancestry | def __match_ancestry(self, ancestry):
"""
Find frames matching the given ancestry.
Returns a tuple containing the following:
* Topmost frame matching the given ancestry or the bottom-most sentry
frame if no frame matches.
* Unmatched ancestry part.
"""
stack = self.__stack
if len(stack) == 1:
return stack[0], ancestry
previous = stack[0]
for frame, n in zip(stack[1:], xrange(len(ancestry))):
if frame.id() is not ancestry[n]:
return previous, ancestry[n:]
previous = frame
return frame, ancestry[n + 1:] | python | def __match_ancestry(self, ancestry):
"""
Find frames matching the given ancestry.
Returns a tuple containing the following:
* Topmost frame matching the given ancestry or the bottom-most sentry
frame if no frame matches.
* Unmatched ancestry part.
"""
stack = self.__stack
if len(stack) == 1:
return stack[0], ancestry
previous = stack[0]
for frame, n in zip(stack[1:], xrange(len(ancestry))):
if frame.id() is not ancestry[n]:
return previous, ancestry[n:]
previous = frame
return frame, ancestry[n + 1:] | Find frames matching the given ancestry.
Returns a tuple containing the following:
* Topmost frame matching the given ancestry or the bottom-most sentry
frame if no frame matches.
* Unmatched ancestry part. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L252-L270 |
suds-community/suds | suds/argparser.py | _ArgParser.__pop_frames_above | def __pop_frames_above(self, frame):
"""Pops all the frames above, but not including the given frame."""
while self.__stack[-1] is not frame:
self.__pop_top_frame()
assert self.__stack | python | def __pop_frames_above(self, frame):
"""Pops all the frames above, but not including the given frame."""
while self.__stack[-1] is not frame:
self.__pop_top_frame()
assert self.__stack | Pops all the frames above, but not including the given frame. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L272-L276 |
suds-community/suds | suds/argparser.py | _ArgParser.__pop_top_frame | def __pop_top_frame(self):
"""Pops the top frame off the frame stack."""
popped = self.__stack.pop()
if self.__stack:
self.__stack[-1].process_subframe(popped) | python | def __pop_top_frame(self):
"""Pops the top frame off the frame stack."""
popped = self.__stack.pop()
if self.__stack:
self.__stack[-1].process_subframe(popped) | Pops the top frame off the frame stack. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L278-L282 |
suds-community/suds | suds/argparser.py | _ArgParser.__process_parameter | def __process_parameter(self, param_name, param_type, ancestry=None):
"""Collect values for a given web service operation input parameter."""
assert self.active()
param_optional = param_type.optional()
has_argument, value = self.__get_param_value(param_name)
if has_argument:
self.__params_with_arguments.add(param_name)
self.__update_context(ancestry)
self.__stack[-1].process_parameter(param_optional, value is not None)
self.__external_param_processor(param_name, param_type,
self.__in_choice_context(), value) | python | def __process_parameter(self, param_name, param_type, ancestry=None):
"""Collect values for a given web service operation input parameter."""
assert self.active()
param_optional = param_type.optional()
has_argument, value = self.__get_param_value(param_name)
if has_argument:
self.__params_with_arguments.add(param_name)
self.__update_context(ancestry)
self.__stack[-1].process_parameter(param_optional, value is not None)
self.__external_param_processor(param_name, param_type,
self.__in_choice_context(), value) | Collect values for a given web service operation input parameter. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L284-L294 |
suds-community/suds | suds/argparser.py | _ArgParser.__push_frame | def __push_frame(self, ancestry_item):
"""Push a new frame on top of the frame stack."""
frame = self.__frame_factory(ancestry_item)
self.__stack.append(frame) | python | def __push_frame(self, ancestry_item):
"""Push a new frame on top of the frame stack."""
frame = self.__frame_factory(ancestry_item)
self.__stack.append(frame) | Push a new frame on top of the frame stack. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/argparser.py#L301-L304 |
suds-community/suds | suds/store.py | DocumentStore.open | def open(self, url):
"""
Open a document at the specified URL.
The document URL's needs not contain a protocol identifier, and if it
does, that protocol identifier is ignored when looking up the store
content.
Missing documents referenced using the internal 'suds' protocol are
reported by raising an exception. For other protocols, None is returned
instead.
@param url: A document URL.
@type url: str
@return: Document content or None if not found.
@rtype: bytes
"""
protocol, location = self.__split(url)
content = self.__find(location)
if protocol == 'suds' and content is None:
raise Exception, 'location "%s" not in document store' % location
return content | python | def open(self, url):
"""
Open a document at the specified URL.
The document URL's needs not contain a protocol identifier, and if it
does, that protocol identifier is ignored when looking up the store
content.
Missing documents referenced using the internal 'suds' protocol are
reported by raising an exception. For other protocols, None is returned
instead.
@param url: A document URL.
@type url: str
@return: Document content or None if not found.
@rtype: bytes
"""
protocol, location = self.__split(url)
content = self.__find(location)
if protocol == 'suds' and content is None:
raise Exception, 'location "%s" not in document store' % location
return content | Open a document at the specified URL.
The document URL's needs not contain a protocol identifier, and if it
does, that protocol identifier is ignored when looking up the store
content.
Missing documents referenced using the internal 'suds' protocol are
reported by raising an exception. For other protocols, None is returned
instead.
@param url: A document URL.
@type url: str
@return: Document content or None if not found.
@rtype: bytes | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/store.py#L548-L570 |
suds-community/suds | setup.py | read_python_code | def read_python_code(filename):
"Returns the given Python source file's compiled content."
file = open(filename, "rt")
try:
source = file.read()
finally:
file.close()
# Python 2.6 and below did not support passing strings to exec() &
# compile() functions containing line separators other than '\n'. To
# support them we need to manually make sure such line endings get
# converted even on platforms where this is not handled by native text file
# read operations.
source = source.replace("\r\n", "\n").replace("\r", "\n")
return compile(source, filename, "exec") | python | def read_python_code(filename):
"Returns the given Python source file's compiled content."
file = open(filename, "rt")
try:
source = file.read()
finally:
file.close()
# Python 2.6 and below did not support passing strings to exec() &
# compile() functions containing line separators other than '\n'. To
# support them we need to manually make sure such line endings get
# converted even on platforms where this is not handled by native text file
# read operations.
source = source.replace("\r\n", "\n").replace("\r", "\n")
return compile(source, filename, "exec") | Returns the given Python source file's compiled content. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/setup.py#L309-L322 |
suds-community/suds | setup.py | recursive_package_list | def recursive_package_list(*packages):
"""
Returns a list of all the given packages and all their subpackages.
Given packages are expected to be found relative to this script's location.
Subpackages are detected by scanning the given packages' subfolder
hierarchy for any folders containing the '__init__.py' module. As a
consequence, namespace packages are not supported.
This is our own specialized setuptools.find_packages() replacement so we
can avoid the setuptools dependency.
"""
result = set()
todo = []
for package in packages:
folder = os.path.join(script_folder, *package.split("."))
if not os.path.isdir(folder):
raise Exception("Folder not found for package '%s'." % (package,))
todo.append((package, folder))
while todo:
package, folder = todo.pop()
if package in result:
continue
result.add(package)
for subitem in os.listdir(folder):
subpackage = ".".join((package, subitem))
subfolder = os.path.join(folder, subitem)
if not os.path.isfile(os.path.join(subfolder, "__init__.py")):
continue
todo.append((subpackage, subfolder))
return list(result) | python | def recursive_package_list(*packages):
"""
Returns a list of all the given packages and all their subpackages.
Given packages are expected to be found relative to this script's location.
Subpackages are detected by scanning the given packages' subfolder
hierarchy for any folders containing the '__init__.py' module. As a
consequence, namespace packages are not supported.
This is our own specialized setuptools.find_packages() replacement so we
can avoid the setuptools dependency.
"""
result = set()
todo = []
for package in packages:
folder = os.path.join(script_folder, *package.split("."))
if not os.path.isdir(folder):
raise Exception("Folder not found for package '%s'." % (package,))
todo.append((package, folder))
while todo:
package, folder = todo.pop()
if package in result:
continue
result.add(package)
for subitem in os.listdir(folder):
subpackage = ".".join((package, subitem))
subfolder = os.path.join(folder, subitem)
if not os.path.isfile(os.path.join(subfolder, "__init__.py")):
continue
todo.append((subpackage, subfolder))
return list(result) | Returns a list of all the given packages and all their subpackages.
Given packages are expected to be found relative to this script's location.
Subpackages are detected by scanning the given packages' subfolder
hierarchy for any folders containing the '__init__.py' module. As a
consequence, namespace packages are not supported.
This is our own specialized setuptools.find_packages() replacement so we
can avoid the setuptools dependency. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/setup.py#L324-L356 |
suds-community/suds | suds/xsd/sxbase.py | SchemaObject.multi_occurrence | def multi_occurrence(self):
"""
Get whether the node has multiple occurrences, i.e. is a I{collection}.
@return: True if it has, False if it has at most 1 occurrence.
@rtype: boolean
"""
max = self.max
if max is None:
return False
if max.isdigit():
return int(max) > 1
return max == "unbounded" | python | def multi_occurrence(self):
"""
Get whether the node has multiple occurrences, i.e. is a I{collection}.
@return: True if it has, False if it has at most 1 occurrence.
@rtype: boolean
"""
max = self.max
if max is None:
return False
if max.isdigit():
return int(max) > 1
return max == "unbounded" | Get whether the node has multiple occurrences, i.e. is a I{collection}.
@return: True if it has, False if it has at most 1 occurrence.
@rtype: boolean | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbase.py#L189-L202 |
suds-community/suds | suds/xsd/sxbase.py | SchemaObject.find | def find(self, qref, classes=[], ignore=None):
"""
Find a referenced type in self or children. Return None if not found.
Qualified references for all schema objects checked in this search will
be added to the set of ignored qualified references to avoid the find
operation going into an infinite loop in case of recursively defined
structures.
@param qref: A qualified reference.
@type qref: qref
@param classes: A collection of classes used to qualify the match.
@type classes: Collection(I{class},...), e.g. [I(class),...]
@param ignore: A set of qualified references to ignore in this search.
@type ignore: {qref,...}
@return: The referenced type.
@rtype: L{SchemaObject}
@see: L{qualify()}
"""
if not len(classes):
classes = (self.__class__,)
if ignore is None:
ignore = set()
if self.qname in ignore:
return
ignore.add(self.qname)
if self.qname == qref and self.__class__ in classes:
return self
for c in self.rawchildren:
p = c.find(qref, classes, ignore=ignore)
if p is not None:
return p | python | def find(self, qref, classes=[], ignore=None):
"""
Find a referenced type in self or children. Return None if not found.
Qualified references for all schema objects checked in this search will
be added to the set of ignored qualified references to avoid the find
operation going into an infinite loop in case of recursively defined
structures.
@param qref: A qualified reference.
@type qref: qref
@param classes: A collection of classes used to qualify the match.
@type classes: Collection(I{class},...), e.g. [I(class),...]
@param ignore: A set of qualified references to ignore in this search.
@type ignore: {qref,...}
@return: The referenced type.
@rtype: L{SchemaObject}
@see: L{qualify()}
"""
if not len(classes):
classes = (self.__class__,)
if ignore is None:
ignore = set()
if self.qname in ignore:
return
ignore.add(self.qname)
if self.qname == qref and self.__class__ in classes:
return self
for c in self.rawchildren:
p = c.find(qref, classes, ignore=ignore)
if p is not None:
return p | Find a referenced type in self or children. Return None if not found.
Qualified references for all schema objects checked in this search will
be added to the set of ignored qualified references to avoid the find
operation going into an infinite loop in case of recursively defined
structures.
@param qref: A qualified reference.
@type qref: qref
@param classes: A collection of classes used to qualify the match.
@type classes: Collection(I{class},...), e.g. [I(class),...]
@param ignore: A set of qualified references to ignore in this search.
@type ignore: {qref,...}
@return: The referenced type.
@rtype: L{SchemaObject}
@see: L{qualify()} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbase.py#L342-L374 |
suds-community/suds | suds/xsd/sxbase.py | Iter.next | def next(self):
"""
Get the next item.
@return: A tuple: the next (child, ancestry).
@rtype: (L{SchemaObject}, [L{SchemaObject},..])
@raise StopIteration: A the end.
"""
frame = self.top()
while True:
result = frame.next()
if result is None:
self.pop()
return self.next()
if isinstance(result, Content):
ancestry = [f.sx for f in self.stack]
return result, ancestry
self.push(result)
return self.next() | python | def next(self):
"""
Get the next item.
@return: A tuple: the next (child, ancestry).
@rtype: (L{SchemaObject}, [L{SchemaObject},..])
@raise StopIteration: A the end.
"""
frame = self.top()
while True:
result = frame.next()
if result is None:
self.pop()
return self.next()
if isinstance(result, Content):
ancestry = [f.sx for f in self.stack]
return result, ancestry
self.push(result)
return self.next() | Get the next item.
@return: A tuple: the next (child, ancestry).
@rtype: (L{SchemaObject}, [L{SchemaObject},..])
@raise StopIteration: A the end. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbase.py#L657-L676 |
suds-community/suds | suds/mx/core.py | Core.process | def process(self, content):
"""
Process (marshal) the tag with the specified value using the
optional type information.
@param content: The content to process.
@type content: L{Object}
"""
log.debug('processing:\n%s', content)
self.reset()
if content.tag is None:
content.tag = content.value.__class__.__name__
document = Document()
self.append(document, content)
return document.root() | python | def process(self, content):
"""
Process (marshal) the tag with the specified value using the
optional type information.
@param content: The content to process.
@type content: L{Object}
"""
log.debug('processing:\n%s', content)
self.reset()
if content.tag is None:
content.tag = content.value.__class__.__name__
document = Document()
self.append(document, content)
return document.root() | Process (marshal) the tag with the specified value using the
optional type information.
@param content: The content to process.
@type content: L{Object} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/core.py#L43-L56 |
suds-community/suds | suds/servicedefinition.py | ServiceDefinition.getprefixes | def getprefixes(self):
"""Add prefixes for each namespace referenced by parameter types."""
namespaces = []
for l in (self.params, self.types):
for t,r in l:
ns = r.namespace()
if ns[1] is None: continue
if ns[1] in namespaces: continue
if Namespace.xs(ns) or Namespace.xsd(ns):
continue
namespaces.append(ns[1])
if t == r: continue
ns = t.namespace()
if ns[1] is None: continue
if ns[1] in namespaces: continue
namespaces.append(ns[1])
i = 0
namespaces.sort()
for u in namespaces:
p = self.nextprefix()
ns = (p, u)
self.prefixes.append(ns) | python | def getprefixes(self):
"""Add prefixes for each namespace referenced by parameter types."""
namespaces = []
for l in (self.params, self.types):
for t,r in l:
ns = r.namespace()
if ns[1] is None: continue
if ns[1] in namespaces: continue
if Namespace.xs(ns) or Namespace.xsd(ns):
continue
namespaces.append(ns[1])
if t == r: continue
ns = t.namespace()
if ns[1] is None: continue
if ns[1] in namespaces: continue
namespaces.append(ns[1])
i = 0
namespaces.sort()
for u in namespaces:
p = self.nextprefix()
ns = (p, u)
self.prefixes.append(ns) | Add prefixes for each namespace referenced by parameter types. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/servicedefinition.py#L107-L128 |
suds-community/suds | suds/servicedefinition.py | ServiceDefinition.xlate | def xlate(self, type):
"""
Get a (namespace) translated I{qualified} name for specified type.
@param type: A schema type.
@type type: I{suds.xsd.sxbasic.SchemaObject}
@return: A translated I{qualified} name.
@rtype: str
"""
resolved = type.resolve()
name = resolved.name
if type.multi_occurrence():
name += '[]'
ns = resolved.namespace()
if ns[1] == self.wsdl.tns[1]:
return name
prefix = self.getprefix(ns[1])
return ':'.join((prefix, name)) | python | def xlate(self, type):
"""
Get a (namespace) translated I{qualified} name for specified type.
@param type: A schema type.
@type type: I{suds.xsd.sxbasic.SchemaObject}
@return: A translated I{qualified} name.
@rtype: str
"""
resolved = type.resolve()
name = resolved.name
if type.multi_occurrence():
name += '[]'
ns = resolved.namespace()
if ns[1] == self.wsdl.tns[1]:
return name
prefix = self.getprefix(ns[1])
return ':'.join((prefix, name)) | Get a (namespace) translated I{qualified} name for specified type.
@param type: A schema type.
@type type: I{suds.xsd.sxbasic.SchemaObject}
@return: A translated I{qualified} name.
@rtype: str | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/servicedefinition.py#L176-L192 |
suds-community/suds | suds/servicedefinition.py | ServiceDefinition.description | def description(self):
"""
Get a textual description of the service for which this object represents.
@return: A textual description.
@rtype: str
"""
s = []
indent = (lambda n : '\n%*s'%(n*3,' '))
s.append('Service ( %s ) tns="%s"' % (self.service.name, self.wsdl.tns[1]))
s.append(indent(1))
s.append('Prefixes (%d)' % len(self.prefixes))
for p in self.prefixes:
s.append(indent(2))
s.append('%s = "%s"' % p)
s.append(indent(1))
s.append('Ports (%d):' % len(self.ports))
for p in self.ports:
s.append(indent(2))
s.append('(%s)' % p[0].name)
s.append(indent(3))
s.append('Methods (%d):' % len(p[1]))
for m in p[1]:
sig = []
s.append(indent(4))
sig.append(m[0])
sig.append('(')
sig.append(', '.join("%s %s" % (self.xlate(p[1]), p[0]) for p
in m[1]))
sig.append(')')
try:
s.append(''.join(sig))
except Exception:
pass
s.append(indent(3))
s.append('Types (%d):' % len(self.types))
for t in self.types:
s.append(indent(4))
s.append(self.xlate(t[0]))
s.append('\n\n')
return ''.join(s) | python | def description(self):
"""
Get a textual description of the service for which this object represents.
@return: A textual description.
@rtype: str
"""
s = []
indent = (lambda n : '\n%*s'%(n*3,' '))
s.append('Service ( %s ) tns="%s"' % (self.service.name, self.wsdl.tns[1]))
s.append(indent(1))
s.append('Prefixes (%d)' % len(self.prefixes))
for p in self.prefixes:
s.append(indent(2))
s.append('%s = "%s"' % p)
s.append(indent(1))
s.append('Ports (%d):' % len(self.ports))
for p in self.ports:
s.append(indent(2))
s.append('(%s)' % p[0].name)
s.append(indent(3))
s.append('Methods (%d):' % len(p[1]))
for m in p[1]:
sig = []
s.append(indent(4))
sig.append(m[0])
sig.append('(')
sig.append(', '.join("%s %s" % (self.xlate(p[1]), p[0]) for p
in m[1]))
sig.append(')')
try:
s.append(''.join(sig))
except Exception:
pass
s.append(indent(3))
s.append('Types (%d):' % len(self.types))
for t in self.types:
s.append(indent(4))
s.append(self.xlate(t[0]))
s.append('\n\n')
return ''.join(s) | Get a textual description of the service for which this object represents.
@return: A textual description.
@rtype: str | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/servicedefinition.py#L194-L233 |
suds-community/suds | suds/sax/document.py | Document.append | def append(self, node):
"""
Append (set) the document root.
@param node: A root L{Element} or name used to build
the document root element.
@type node: (L{Element}|str|None)
"""
if isinstance(node, basestring):
self.__root = Element(node)
return
if isinstance(node, Element):
self.__root = node
return | python | def append(self, node):
"""
Append (set) the document root.
@param node: A root L{Element} or name used to build
the document root element.
@type node: (L{Element}|str|None)
"""
if isinstance(node, basestring):
self.__root = Element(node)
return
if isinstance(node, Element):
self.__root = node
return | Append (set) the document root.
@param node: A root L{Element} or name used to build
the document root element.
@type node: (L{Element}|str|None) | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/document.py#L48-L60 |
suds-community/suds | suds/sax/document.py | Document.getChild | def getChild(self, name, ns=None, default=None):
"""
Get a child by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@param default: Returned when child not-found.
@type default: L{Element}
@return: The requested child, or I{default} when not-found.
@rtype: L{Element}
"""
if self.__root is None:
return default
if ns is None:
prefix, name = splitPrefix(name)
if prefix is None:
ns = None
else:
ns = self.__root.resolvePrefix(prefix)
if self.__root.match(name, ns):
return self.__root
else:
return default | python | def getChild(self, name, ns=None, default=None):
"""
Get a child by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@param default: Returned when child not-found.
@type default: L{Element}
@return: The requested child, or I{default} when not-found.
@rtype: L{Element}
"""
if self.__root is None:
return default
if ns is None:
prefix, name = splitPrefix(name)
if prefix is None:
ns = None
else:
ns = self.__root.resolvePrefix(prefix)
if self.__root.match(name, ns):
return self.__root
else:
return default | Get a child by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@param default: Returned when child not-found.
@type default: L{Element}
@return: The requested child, or I{default} when not-found.
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/document.py#L62-L85 |
suds-community/suds | suds/sax/document.py | Document.childAtPath | def childAtPath(self, path):
"""
Get a child at I{path} where I{path} is a (/) separated
list of element names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The leaf node at the end of I{path}
@rtype: L{Element}
"""
if self.__root is None:
return None
if path[0] == '/':
path = path[1:]
path = path.split('/',1)
if self.getChild(path[0]) is None:
return None
if len(path) > 1:
return self.__root.childAtPath(path[1])
else:
return self.__root | python | def childAtPath(self, path):
"""
Get a child at I{path} where I{path} is a (/) separated
list of element names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The leaf node at the end of I{path}
@rtype: L{Element}
"""
if self.__root is None:
return None
if path[0] == '/':
path = path[1:]
path = path.split('/',1)
if self.getChild(path[0]) is None:
return None
if len(path) > 1:
return self.__root.childAtPath(path[1])
else:
return self.__root | Get a child at I{path} where I{path} is a (/) separated
list of element names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The leaf node at the end of I{path}
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/document.py#L87-L106 |
suds-community/suds | suds/sax/document.py | Document.childrenAtPath | def childrenAtPath(self, path):
"""
Get a list of children at I{path} where I{path} is a (/) separated
list of element names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The collection leaf nodes at the end of I{path}
@rtype: [L{Element},...]
"""
if self.__root is None:
return []
if path[0] == '/':
path = path[1:]
path = path.split('/',1)
if self.getChild(path[0]) is None:
return []
if len(path) > 1:
return self.__root.childrenAtPath(path[1])
else:
return [self.__root,] | python | def childrenAtPath(self, path):
"""
Get a list of children at I{path} where I{path} is a (/) separated
list of element names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The collection leaf nodes at the end of I{path}
@rtype: [L{Element},...]
"""
if self.__root is None:
return []
if path[0] == '/':
path = path[1:]
path = path.split('/',1)
if self.getChild(path[0]) is None:
return []
if len(path) > 1:
return self.__root.childrenAtPath(path[1])
else:
return [self.__root,] | Get a list of children at I{path} where I{path} is a (/) separated
list of element names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The collection leaf nodes at the end of I{path}
@rtype: [L{Element},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/document.py#L108-L127 |
suds-community/suds | suds/sax/document.py | Document.getChildren | def getChildren(self, name=None, ns=None):
"""
Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching children.
@rtype: [L{Element},...]
"""
if name is None:
matched = self.__root
else:
matched = self.getChild(name, ns)
if matched is None:
return []
else:
return [matched,] | python | def getChildren(self, name=None, ns=None):
"""
Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching children.
@rtype: [L{Element},...]
"""
if name is None:
matched = self.__root
else:
matched = self.getChild(name, ns)
if matched is None:
return []
else:
return [matched,] | Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching children.
@rtype: [L{Element},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/document.py#L129-L146 |
suds-community/suds | suds/sax/document.py | Document.plain | def plain(self):
"""
Get a string representation of this XML document.
@return: A I{plain} string.
@rtype: basestring
"""
s = []
s.append(self.DECL)
root = self.root()
if root is not None:
s.append(root.plain())
return ''.join(s) | python | def plain(self):
"""
Get a string representation of this XML document.
@return: A I{plain} string.
@rtype: basestring
"""
s = []
s.append(self.DECL)
root = self.root()
if root is not None:
s.append(root.plain())
return ''.join(s) | Get a string representation of this XML document.
@return: A I{plain} string.
@rtype: basestring | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/document.py#L162-L173 |
suds-community/suds | suds/xsd/schema.py | SchemaCollection.merge | def merge(self):
"""
Merge contained schemas into one.
@return: The merged schema.
@rtype: L{Schema}
"""
if self.children:
schema = self.children[0]
for s in self.children[1:]:
schema.merge(s)
return schema | python | def merge(self):
"""
Merge contained schemas into one.
@return: The merged schema.
@rtype: L{Schema}
"""
if self.children:
schema = self.children[0]
for s in self.children[1:]:
schema.merge(s)
return schema | Merge contained schemas into one.
@return: The merged schema.
@rtype: L{Schema} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/schema.py#L146-L158 |
suds-community/suds | suds/xsd/schema.py | Schema.mktns | def mktns(self):
"""
Make the schema's target namespace.
@return: namespace representation of the schema's targetNamespace
value.
@rtype: (prefix, URI)
"""
tns = self.root.get("targetNamespace")
tns_prefix = None
if tns is not None:
tns_prefix = self.root.findPrefix(tns)
return tns_prefix, tns | python | def mktns(self):
"""
Make the schema's target namespace.
@return: namespace representation of the schema's targetNamespace
value.
@rtype: (prefix, URI)
"""
tns = self.root.get("targetNamespace")
tns_prefix = None
if tns is not None:
tns_prefix = self.root.findPrefix(tns)
return tns_prefix, tns | Make the schema's target namespace.
@return: namespace representation of the schema's targetNamespace
value.
@rtype: (prefix, URI) | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/schema.py#L266-L279 |
suds-community/suds | suds/xsd/schema.py | Schema.open_imports | def open_imports(self, options, loaded_schemata):
"""
Instruct all contained L{sxbasic.Import} children to import all of
their referenced schemas. The imported schema contents are I{merged}
in.
@param options: An options dictionary.
@type options: L{options.Options}
@param loaded_schemata: Already loaded schemata cache (URL --> Schema).
@type loaded_schemata: dict
"""
for imp in self.imports:
imported = imp.open(options, loaded_schemata)
if imported is None:
continue
imported.open_imports(options, loaded_schemata)
log.debug("imported:\n%s", imported)
self.merge(imported) | python | def open_imports(self, options, loaded_schemata):
"""
Instruct all contained L{sxbasic.Import} children to import all of
their referenced schemas. The imported schema contents are I{merged}
in.
@param options: An options dictionary.
@type options: L{options.Options}
@param loaded_schemata: Already loaded schemata cache (URL --> Schema).
@type loaded_schemata: dict
"""
for imp in self.imports:
imported = imp.open(options, loaded_schemata)
if imported is None:
continue
imported.open_imports(options, loaded_schemata)
log.debug("imported:\n%s", imported)
self.merge(imported) | Instruct all contained L{sxbasic.Import} children to import all of
their referenced schemas. The imported schema contents are I{merged}
in.
@param options: An options dictionary.
@type options: L{options.Options}
@param loaded_schemata: Already loaded schemata cache (URL --> Schema).
@type loaded_schemata: dict | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/schema.py#L338-L356 |
suds-community/suds | suds/xsd/schema.py | Schema.dereference | def dereference(self):
"""Instruct all children to perform dereferencing."""
all = []
indexes = {}
for child in self.children:
child.content(all)
dependencies = {}
for x in all:
x.qualify()
midx, deps = x.dependencies()
dependencies[x] = deps
indexes[x] = midx
for x, deps in dependency_sort(dependencies):
midx = indexes.get(x)
if midx is None:
continue
d = deps[midx]
log.debug("(%s) merging %s <== %s", self.tns[1], Repr(x), Repr(d))
x.merge(d) | python | def dereference(self):
"""Instruct all children to perform dereferencing."""
all = []
indexes = {}
for child in self.children:
child.content(all)
dependencies = {}
for x in all:
x.qualify()
midx, deps = x.dependencies()
dependencies[x] = deps
indexes[x] = midx
for x, deps in dependency_sort(dependencies):
midx = indexes.get(x)
if midx is None:
continue
d = deps[midx]
log.debug("(%s) merging %s <== %s", self.tns[1], Repr(x), Repr(d))
x.merge(d) | Instruct all children to perform dereferencing. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/schema.py#L358-L376 |
suds-community/suds | suds/xsd/schema.py | Schema.instance | def instance(self, root, baseurl, loaded_schemata, options):
"""
Create and return an new schema object using the specified I{root} and
I{URL}.
@param root: A schema root node.
@type root: L{sax.element.Element}
@param baseurl: A base URL.
@type baseurl: str
@param loaded_schemata: Already loaded schemata cache (URL --> Schema).
@type loaded_schemata: dict
@param options: An options dictionary.
@type options: L{options.Options}
@return: The newly created schema object.
@rtype: L{Schema}
@note: This is only used by Import children.
"""
return Schema(root, baseurl, options, loaded_schemata) | python | def instance(self, root, baseurl, loaded_schemata, options):
"""
Create and return an new schema object using the specified I{root} and
I{URL}.
@param root: A schema root node.
@type root: L{sax.element.Element}
@param baseurl: A base URL.
@type baseurl: str
@param loaded_schemata: Already loaded schemata cache (URL --> Schema).
@type loaded_schemata: dict
@param options: An options dictionary.
@type options: L{options.Options}
@return: The newly created schema object.
@rtype: L{Schema}
@note: This is only used by Import children.
"""
return Schema(root, baseurl, options, loaded_schemata) | Create and return an new schema object using the specified I{root} and
I{URL}.
@param root: A schema root node.
@type root: L{sax.element.Element}
@param baseurl: A base URL.
@type baseurl: str
@param loaded_schemata: Already loaded schemata cache (URL --> Schema).
@type loaded_schemata: dict
@param options: An options dictionary.
@type options: L{options.Options}
@return: The newly created schema object.
@rtype: L{Schema}
@note: This is only used by Import children. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/schema.py#L428-L446 |
remind101/stacker_blueprints | stacker_blueprints/sns.py | Topics.create_sqs_policy | def create_sqs_policy(self, topic_name, topic_arn, topic_subs):
"""
This method creates the SQS policy needed for an SNS subscription. It
also takes the ARN of the SQS queue and converts it to the URL needed
for the subscription, as that takes a URL rather than the ARN.
"""
t = self.template
arn_endpoints = []
url_endpoints = []
for sub in topic_subs:
arn_endpoints.append(sub["Endpoint"])
split_endpoint = sub["Endpoint"].split(":")
queue_url = "https://%s.%s.amazonaws.com/%s/%s" % (
split_endpoint[2], # literally "sqs"
split_endpoint[3], # AWS region
split_endpoint[4], # AWS ID
split_endpoint[5], # Queue name
)
url_endpoints.append(queue_url)
policy_doc = queue_policy(topic_arn, arn_endpoints)
t.add_resource(
sqs.QueuePolicy(
topic_name + "SubPolicy",
PolicyDocument=policy_doc,
Queues=url_endpoints,
)
) | python | def create_sqs_policy(self, topic_name, topic_arn, topic_subs):
"""
This method creates the SQS policy needed for an SNS subscription. It
also takes the ARN of the SQS queue and converts it to the URL needed
for the subscription, as that takes a URL rather than the ARN.
"""
t = self.template
arn_endpoints = []
url_endpoints = []
for sub in topic_subs:
arn_endpoints.append(sub["Endpoint"])
split_endpoint = sub["Endpoint"].split(":")
queue_url = "https://%s.%s.amazonaws.com/%s/%s" % (
split_endpoint[2], # literally "sqs"
split_endpoint[3], # AWS region
split_endpoint[4], # AWS ID
split_endpoint[5], # Queue name
)
url_endpoints.append(queue_url)
policy_doc = queue_policy(topic_arn, arn_endpoints)
t.add_resource(
sqs.QueuePolicy(
topic_name + "SubPolicy",
PolicyDocument=policy_doc,
Queues=url_endpoints,
)
) | This method creates the SQS policy needed for an SNS subscription. It
also takes the ARN of the SQS queue and converts it to the URL needed
for the subscription, as that takes a URL rather than the ARN. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/sns.py#L81-L110 |
remind101/stacker_blueprints | stacker_blueprints/sns.py | Topics.create_topic | def create_topic(self, topic_name, topic_config):
"""
Creates the SNS topic, along with any subscriptions requested.
"""
topic_subs = []
t = self.template
if "Subscription" in topic_config:
topic_subs = topic_config["Subscription"]
t.add_resource(
sns.Topic.from_dict(
topic_name,
topic_config
)
)
topic_arn = Ref(topic_name)
t.add_output(
Output(topic_name + "Name", Value=GetAtt(topic_name, "TopicName"))
)
t.add_output(Output(topic_name + "Arn", Value=topic_arn))
sqs_subs = [sub for sub in topic_subs if sub["Protocol"] == "sqs"]
if sqs_subs:
self.create_sqs_policy(topic_name, topic_arn, sqs_subs) | python | def create_topic(self, topic_name, topic_config):
"""
Creates the SNS topic, along with any subscriptions requested.
"""
topic_subs = []
t = self.template
if "Subscription" in topic_config:
topic_subs = topic_config["Subscription"]
t.add_resource(
sns.Topic.from_dict(
topic_name,
topic_config
)
)
topic_arn = Ref(topic_name)
t.add_output(
Output(topic_name + "Name", Value=GetAtt(topic_name, "TopicName"))
)
t.add_output(Output(topic_name + "Arn", Value=topic_arn))
sqs_subs = [sub for sub in topic_subs if sub["Protocol"] == "sqs"]
if sqs_subs:
self.create_sqs_policy(topic_name, topic_arn, sqs_subs) | Creates the SNS topic, along with any subscriptions requested. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/sns.py#L112-L138 |
remind101/stacker_blueprints | stacker_blueprints/aws_lambda.py | get_stream_action_type | def get_stream_action_type(stream_arn):
"""Returns the awacs Action for a stream type given an arn
Args:
stream_arn (str): The Arn of the stream.
Returns:
:class:`awacs.aws.Action`: The appropriate stream type awacs Action
class
Raises:
ValueError: If the stream type doesn't match kinesis or dynamodb.
"""
stream_type_map = {
"kinesis": awacs.kinesis.Action,
"dynamodb": awacs.dynamodb.Action,
}
stream_type = stream_arn.split(":")[2]
try:
return stream_type_map[stream_type]
except KeyError:
raise ValueError(
"Invalid stream type '%s' in arn '%s'" % (stream_type, stream_arn)
) | python | def get_stream_action_type(stream_arn):
"""Returns the awacs Action for a stream type given an arn
Args:
stream_arn (str): The Arn of the stream.
Returns:
:class:`awacs.aws.Action`: The appropriate stream type awacs Action
class
Raises:
ValueError: If the stream type doesn't match kinesis or dynamodb.
"""
stream_type_map = {
"kinesis": awacs.kinesis.Action,
"dynamodb": awacs.dynamodb.Action,
}
stream_type = stream_arn.split(":")[2]
try:
return stream_type_map[stream_type]
except KeyError:
raise ValueError(
"Invalid stream type '%s' in arn '%s'" % (stream_type, stream_arn)
) | Returns the awacs Action for a stream type given an arn
Args:
stream_arn (str): The Arn of the stream.
Returns:
:class:`awacs.aws.Action`: The appropriate stream type awacs Action
class
Raises:
ValueError: If the stream type doesn't match kinesis or dynamodb. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/aws_lambda.py#L37-L62 |
remind101/stacker_blueprints | stacker_blueprints/aws_lambda.py | stream_reader_statements | def stream_reader_statements(stream_arn):
"""Returns statements to allow Lambda to read from a stream.
Handles both DynamoDB & Kinesis streams. Automatically figures out the
type of stream, and provides the correct actions from the supplied Arn.
Arg:
stream_arn (str): A kinesis or dynamodb stream arn.
Returns:
list: A list of statements.
"""
action_type = get_stream_action_type(stream_arn)
arn_parts = stream_arn.split("/")
# Cut off the last bit and replace it with a wildcard
wildcard_arn_parts = arn_parts[:-1]
wildcard_arn_parts.append("*")
wildcard_arn = "/".join(wildcard_arn_parts)
return [
Statement(
Effect=Allow,
Resource=[stream_arn],
Action=[
action_type("DescribeStream"),
action_type("GetRecords"),
action_type("GetShardIterator"),
]
),
Statement(
Effect=Allow,
Resource=[wildcard_arn],
Action=[action_type("ListStreams")]
)
] | python | def stream_reader_statements(stream_arn):
"""Returns statements to allow Lambda to read from a stream.
Handles both DynamoDB & Kinesis streams. Automatically figures out the
type of stream, and provides the correct actions from the supplied Arn.
Arg:
stream_arn (str): A kinesis or dynamodb stream arn.
Returns:
list: A list of statements.
"""
action_type = get_stream_action_type(stream_arn)
arn_parts = stream_arn.split("/")
# Cut off the last bit and replace it with a wildcard
wildcard_arn_parts = arn_parts[:-1]
wildcard_arn_parts.append("*")
wildcard_arn = "/".join(wildcard_arn_parts)
return [
Statement(
Effect=Allow,
Resource=[stream_arn],
Action=[
action_type("DescribeStream"),
action_type("GetRecords"),
action_type("GetShardIterator"),
]
),
Statement(
Effect=Allow,
Resource=[wildcard_arn],
Action=[action_type("ListStreams")]
)
] | Returns statements to allow Lambda to read from a stream.
Handles both DynamoDB & Kinesis streams. Automatically figures out the
type of stream, and provides the correct actions from the supplied Arn.
Arg:
stream_arn (str): A kinesis or dynamodb stream arn.
Returns:
list: A list of statements. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/aws_lambda.py#L65-L99 |
remind101/stacker_blueprints | stacker_blueprints/aws_lambda.py | Function.add_policy_statements | def add_policy_statements(self, statements):
"""Adds statements to the policy.
Args:
statements (:class:`awacs.aws.Statement` or list): Either a single
Statment, or a list of statements.
"""
if isinstance(statements, Statement):
statements = [statements]
self._policy_statements.extend(statements) | python | def add_policy_statements(self, statements):
"""Adds statements to the policy.
Args:
statements (:class:`awacs.aws.Statement` or list): Either a single
Statment, or a list of statements.
"""
if isinstance(statements, Statement):
statements = [statements]
self._policy_statements.extend(statements) | Adds statements to the policy.
Args:
statements (:class:`awacs.aws.Statement` or list): Either a single
Statment, or a list of statements. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/aws_lambda.py#L221-L230 |
remind101/stacker_blueprints | stacker_blueprints/aws_lambda.py | Function.generate_policy_statements | def generate_policy_statements(self):
"""Generates the policy statements for the role used by the function.
To add additional statements you can either override the
`extended_policy_statements` method to return a list of Statements
to be added to the policy, or override this method itself if you
need more control.
Returns:
list: A list of :class:`awacs.aws.Statement` objects.
"""
statements = self._policy_statements
statements.extend(
lambda_basic_execution_statements(
self.function.Ref()
)
)
extended_statements = self.extended_policy_statements()
if extended_statements:
statements.extend(extended_statements)
return statements | python | def generate_policy_statements(self):
"""Generates the policy statements for the role used by the function.
To add additional statements you can either override the
`extended_policy_statements` method to return a list of Statements
to be added to the policy, or override this method itself if you
need more control.
Returns:
list: A list of :class:`awacs.aws.Statement` objects.
"""
statements = self._policy_statements
statements.extend(
lambda_basic_execution_statements(
self.function.Ref()
)
)
extended_statements = self.extended_policy_statements()
if extended_statements:
statements.extend(extended_statements)
return statements | Generates the policy statements for the role used by the function.
To add additional statements you can either override the
`extended_policy_statements` method to return a list of Statements
to be added to the policy, or override this method itself if you
need more control.
Returns:
list: A list of :class:`awacs.aws.Statement` objects. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/aws_lambda.py#L240-L260 |
remind101/stacker_blueprints | stacker_blueprints/dynamodb.py | snake_to_camel_case | def snake_to_camel_case(name):
"""
Accept a snake_case string and return a CamelCase string.
For example::
>>> snake_to_camel_case('cidr_block')
'CidrBlock'
"""
name = name.replace("-", "_")
return "".join(word.capitalize() for word in name.split("_")) | python | def snake_to_camel_case(name):
"""
Accept a snake_case string and return a CamelCase string.
For example::
>>> snake_to_camel_case('cidr_block')
'CidrBlock'
"""
name = name.replace("-", "_")
return "".join(word.capitalize() for word in name.split("_")) | Accept a snake_case string and return a CamelCase string.
For example::
>>> snake_to_camel_case('cidr_block')
'CidrBlock' | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/dynamodb.py#L39-L47 |
remind101/stacker_blueprints | stacker_blueprints/generic.py | GenericResourceCreator.setup_resource | def setup_resource(self):
""" Setting Up Resource """
template = self.template
variables = self.get_variables()
tclass = variables['Class']
tprops = variables['Properties']
output = variables['Output']
klass = load_object_from_string('troposphere.' + tclass)
instance = klass.from_dict('ResourceRefName', tprops)
template.add_resource(instance)
template.add_output(Output(
output,
Description="A reference to the object created in this blueprint",
Value=Ref(instance)
)) | python | def setup_resource(self):
""" Setting Up Resource """
template = self.template
variables = self.get_variables()
tclass = variables['Class']
tprops = variables['Properties']
output = variables['Output']
klass = load_object_from_string('troposphere.' + tclass)
instance = klass.from_dict('ResourceRefName', tprops)
template.add_resource(instance)
template.add_output(Output(
output,
Description="A reference to the object created in this blueprint",
Value=Ref(instance)
)) | Setting Up Resource | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/generic.py#L57-L75 |
remind101/stacker_blueprints | stacker_blueprints/kms.py | kms_key_policy | def kms_key_policy():
""" Creates a key policy for use of a KMS Key. """
statements = []
statements.extend(kms_key_root_statements())
return Policy(
Version="2012-10-17",
Id="root-account-access",
Statement=statements
) | python | def kms_key_policy():
""" Creates a key policy for use of a KMS Key. """
statements = []
statements.extend(kms_key_root_statements())
return Policy(
Version="2012-10-17",
Id="root-account-access",
Statement=statements
) | Creates a key policy for use of a KMS Key. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/kms.py#L40-L50 |
remind101/stacker_blueprints | stacker_blueprints/empire/policies.py | logstream_policy | def logstream_policy():
"""Policy needed for logspout -> kinesis log streaming."""
p = Policy(
Statement=[
Statement(
Effect=Allow,
Resource=["*"],
Action=[
kinesis.CreateStream, kinesis.DescribeStream,
Action(kinesis.prefix, "AddTagsToStream"),
Action(kinesis.prefix, "PutRecords")
])])
return p | python | def logstream_policy():
"""Policy needed for logspout -> kinesis log streaming."""
p = Policy(
Statement=[
Statement(
Effect=Allow,
Resource=["*"],
Action=[
kinesis.CreateStream, kinesis.DescribeStream,
Action(kinesis.prefix, "AddTagsToStream"),
Action(kinesis.prefix, "PutRecords")
])])
return p | Policy needed for logspout -> kinesis log streaming. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/empire/policies.py#L245-L257 |
remind101/stacker_blueprints | stacker_blueprints/empire/policies.py | runlogs_policy | def runlogs_policy(log_group_ref):
"""Policy needed for Empire -> Cloudwatch logs to record run output."""
p = Policy(
Statement=[
Statement(
Effect=Allow,
Resource=[
Join('', [
'arn:aws:logs:*:*:log-group:',
log_group_ref,
':log-stream:*'])],
Action=[
logs.CreateLogStream,
logs.PutLogEvents,
])])
return p | python | def runlogs_policy(log_group_ref):
"""Policy needed for Empire -> Cloudwatch logs to record run output."""
p = Policy(
Statement=[
Statement(
Effect=Allow,
Resource=[
Join('', [
'arn:aws:logs:*:*:log-group:',
log_group_ref,
':log-stream:*'])],
Action=[
logs.CreateLogStream,
logs.PutLogEvents,
])])
return p | Policy needed for Empire -> Cloudwatch logs to record run output. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/empire/policies.py#L260-L275 |
remind101/stacker_blueprints | stacker_blueprints/util.py | check_properties | def check_properties(properties, allowed_properties, resource):
"""Checks the list of properties in the properties variable against the
property list provided by the allowed_properties variable. If any property
does not match the properties in allowed_properties, a ValueError is
raised to prevent unexpected behavior when creating resources.
properties: The config (as dict) provided by the configuration file
allowed_properties: A list of strings representing the available params
for a resource.
resource: A string naming the resource in question for the error
message.
"""
for key in properties.keys():
if key not in allowed_properties:
raise ValueError(
"%s is not a valid property of %s" % (key, resource)
) | python | def check_properties(properties, allowed_properties, resource):
"""Checks the list of properties in the properties variable against the
property list provided by the allowed_properties variable. If any property
does not match the properties in allowed_properties, a ValueError is
raised to prevent unexpected behavior when creating resources.
properties: The config (as dict) provided by the configuration file
allowed_properties: A list of strings representing the available params
for a resource.
resource: A string naming the resource in question for the error
message.
"""
for key in properties.keys():
if key not in allowed_properties:
raise ValueError(
"%s is not a valid property of %s" % (key, resource)
) | Checks the list of properties in the properties variable against the
property list provided by the allowed_properties variable. If any property
does not match the properties in allowed_properties, a ValueError is
raised to prevent unexpected behavior when creating resources.
properties: The config (as dict) provided by the configuration file
allowed_properties: A list of strings representing the available params
for a resource.
resource: A string naming the resource in question for the error
message. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/util.py#L6-L22 |
remind101/stacker_blueprints | stacker_blueprints/util.py | merge_tags | def merge_tags(left, right, factory=Tags):
"""
Merge two sets of tags into a new troposphere object
Args:
left (Union[dict, troposphere.Tags]): dictionary or Tags object to be
merged with lower priority
right (Union[dict, troposphere.Tags]): dictionary or Tags object to be
merged with higher priority
factory (type): Type of object to create. Defaults to the troposphere
Tags class.
"""
if isinstance(left, Mapping):
tags = dict(left)
elif hasattr(left, 'tags'):
tags = _tags_to_dict(left.tags)
else:
tags = _tags_to_dict(left)
if isinstance(right, Mapping):
tags.update(right)
elif hasattr(left, 'tags'):
tags.update(_tags_to_dict(right.tags))
else:
tags.update(_tags_to_dict(right))
return factory(**tags) | python | def merge_tags(left, right, factory=Tags):
"""
Merge two sets of tags into a new troposphere object
Args:
left (Union[dict, troposphere.Tags]): dictionary or Tags object to be
merged with lower priority
right (Union[dict, troposphere.Tags]): dictionary or Tags object to be
merged with higher priority
factory (type): Type of object to create. Defaults to the troposphere
Tags class.
"""
if isinstance(left, Mapping):
tags = dict(left)
elif hasattr(left, 'tags'):
tags = _tags_to_dict(left.tags)
else:
tags = _tags_to_dict(left)
if isinstance(right, Mapping):
tags.update(right)
elif hasattr(left, 'tags'):
tags.update(_tags_to_dict(right.tags))
else:
tags.update(_tags_to_dict(right))
return factory(**tags) | Merge two sets of tags into a new troposphere object
Args:
left (Union[dict, troposphere.Tags]): dictionary or Tags object to be
merged with lower priority
right (Union[dict, troposphere.Tags]): dictionary or Tags object to be
merged with higher priority
factory (type): Type of object to create. Defaults to the troposphere
Tags class. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/util.py#L29-L56 |
remind101/stacker_blueprints | stacker_blueprints/route53.py | get_record_set_md5 | def get_record_set_md5(rs_name, rs_type):
"""Accept record_set Name and Type. Return MD5 sum of these values."""
rs_name = rs_name.lower()
rs_type = rs_type.upper()
# Make A and CNAME records hash to same sum to support updates.
rs_type = "ACNAME" if rs_type in ["A", "CNAME"] else rs_type
return md5(rs_name + rs_type).hexdigest() | python | def get_record_set_md5(rs_name, rs_type):
"""Accept record_set Name and Type. Return MD5 sum of these values."""
rs_name = rs_name.lower()
rs_type = rs_type.upper()
# Make A and CNAME records hash to same sum to support updates.
rs_type = "ACNAME" if rs_type in ["A", "CNAME"] else rs_type
return md5(rs_name + rs_type).hexdigest() | Accept record_set Name and Type. Return MD5 sum of these values. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L66-L72 |
remind101/stacker_blueprints | stacker_blueprints/route53.py | DNSRecords.add_hosted_zone_id_for_alias_target_if_missing | def add_hosted_zone_id_for_alias_target_if_missing(self, rs):
"""Add proper hosted zone id to record set alias target if missing."""
alias_target = getattr(rs, "AliasTarget", None)
if alias_target:
hosted_zone_id = getattr(alias_target, "HostedZoneId", None)
if not hosted_zone_id:
dns_name = alias_target.DNSName
if dns_name.endswith(CF_DOMAIN):
alias_target.HostedZoneId = CLOUDFRONT_ZONE_ID
elif dns_name.endswith(ELB_DOMAIN):
region = dns_name.split('.')[-5]
alias_target.HostedZoneId = ELB_ZONE_IDS[region]
elif dns_name in S3_WEBSITE_ZONE_IDS:
alias_target.HostedZoneId = S3_WEBSITE_ZONE_IDS[dns_name]
else:
alias_target.HostedZoneId = self.hosted_zone_id
return rs | python | def add_hosted_zone_id_for_alias_target_if_missing(self, rs):
"""Add proper hosted zone id to record set alias target if missing."""
alias_target = getattr(rs, "AliasTarget", None)
if alias_target:
hosted_zone_id = getattr(alias_target, "HostedZoneId", None)
if not hosted_zone_id:
dns_name = alias_target.DNSName
if dns_name.endswith(CF_DOMAIN):
alias_target.HostedZoneId = CLOUDFRONT_ZONE_ID
elif dns_name.endswith(ELB_DOMAIN):
region = dns_name.split('.')[-5]
alias_target.HostedZoneId = ELB_ZONE_IDS[region]
elif dns_name in S3_WEBSITE_ZONE_IDS:
alias_target.HostedZoneId = S3_WEBSITE_ZONE_IDS[dns_name]
else:
alias_target.HostedZoneId = self.hosted_zone_id
return rs | Add proper hosted zone id to record set alias target if missing. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L123-L139 |
remind101/stacker_blueprints | stacker_blueprints/route53.py | DNSRecords.create_record_set | def create_record_set(self, rs_dict):
"""Accept a record_set dict. Return a Troposphere record_set object."""
record_set_md5 = get_record_set_md5(rs_dict["Name"], rs_dict["Type"])
rs = route53.RecordSetType.from_dict(record_set_md5, rs_dict)
rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
return self.template.add_resource(rs) | python | def create_record_set(self, rs_dict):
"""Accept a record_set dict. Return a Troposphere record_set object."""
record_set_md5 = get_record_set_md5(rs_dict["Name"], rs_dict["Type"])
rs = route53.RecordSetType.from_dict(record_set_md5, rs_dict)
rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
return self.template.add_resource(rs) | Accept a record_set dict. Return a Troposphere record_set object. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L141-L147 |
remind101/stacker_blueprints | stacker_blueprints/route53.py | DNSRecords.create_record_set_group | def create_record_set_group(self, name, g_dict):
"""Accept a record_set dict. Return a Troposphere record_set object."""
rs = route53.RecordSetGroup.from_dict(name, g_dict)
rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
return self.template.add_resource(rs) | python | def create_record_set_group(self, name, g_dict):
"""Accept a record_set dict. Return a Troposphere record_set object."""
rs = route53.RecordSetGroup.from_dict(name, g_dict)
rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
return self.template.add_resource(rs) | Accept a record_set dict. Return a Troposphere record_set object. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L149-L154 |
remind101/stacker_blueprints | stacker_blueprints/route53.py | DNSRecords.create_record_sets | def create_record_sets(self, record_set_dicts):
"""Accept list of record_set dicts.
Return list of record_set objects."""
record_set_objects = []
for record_set_dict in record_set_dicts:
# pop removes the 'Enabled' key and tests if True.
if record_set_dict.pop('Enabled', True):
record_set_objects.append(
self.create_record_set(record_set_dict)
)
return record_set_objects | python | def create_record_sets(self, record_set_dicts):
"""Accept list of record_set dicts.
Return list of record_set objects."""
record_set_objects = []
for record_set_dict in record_set_dicts:
# pop removes the 'Enabled' key and tests if True.
if record_set_dict.pop('Enabled', True):
record_set_objects.append(
self.create_record_set(record_set_dict)
)
return record_set_objects | Accept list of record_set dicts.
Return list of record_set objects. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L156-L166 |
remind101/stacker_blueprints | stacker_blueprints/route53.py | DNSRecords.create_record_set_groups | def create_record_set_groups(self, record_set_group_dicts):
"""Accept list of record_set_group dicts.
Return list of record_set_group objects."""
record_set_groups = []
for name, group in record_set_group_dicts.iteritems():
# pop removes the 'Enabled' key and tests if True.
if group.pop('Enabled', True):
record_set_groups.append(
self.create_record_set_group(name, group)
)
return record_set_groups | python | def create_record_set_groups(self, record_set_group_dicts):
"""Accept list of record_set_group dicts.
Return list of record_set_group objects."""
record_set_groups = []
for name, group in record_set_group_dicts.iteritems():
# pop removes the 'Enabled' key and tests if True.
if group.pop('Enabled', True):
record_set_groups.append(
self.create_record_set_group(name, group)
)
return record_set_groups | Accept list of record_set_group dicts.
Return list of record_set_group objects. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/route53.py#L168-L178 |
remind101/stacker_blueprints | stacker_blueprints/policies.py | read_only_s3_bucket_policy_statements | def read_only_s3_bucket_policy_statements(buckets, folder="*"):
""" Read only policy an s3 bucket. """
list_buckets = [s3_arn(b) for b in buckets]
object_buckets = [s3_objects_arn(b, folder) for b in buckets]
bucket_resources = list_buckets + object_buckets
return [
Statement(
Effect=Allow,
Resource=[s3_arn("*")],
Action=[s3.ListAllMyBuckets]
),
Statement(
Effect=Allow,
Resource=bucket_resources,
Action=[Action('s3', 'Get*'), Action('s3', 'List*')]
)
] | python | def read_only_s3_bucket_policy_statements(buckets, folder="*"):
""" Read only policy an s3 bucket. """
list_buckets = [s3_arn(b) for b in buckets]
object_buckets = [s3_objects_arn(b, folder) for b in buckets]
bucket_resources = list_buckets + object_buckets
return [
Statement(
Effect=Allow,
Resource=[s3_arn("*")],
Action=[s3.ListAllMyBuckets]
),
Statement(
Effect=Allow,
Resource=bucket_resources,
Action=[Action('s3', 'Get*'), Action('s3', 'List*')]
)
] | Read only policy an s3 bucket. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L62-L80 |
remind101/stacker_blueprints | stacker_blueprints/policies.py | static_website_bucket_policy | def static_website_bucket_policy(bucket):
"""
Attach this policy directly to an S3 bucket to make it a static website.
This policy grants read access to **all unauthenticated** users.
"""
return Policy(
Statement=[
Statement(
Effect=Allow,
Principal=Principal("*"),
Action=[s3.GetObject],
Resource=[s3_objects_arn(bucket)],
)
]
) | python | def static_website_bucket_policy(bucket):
"""
Attach this policy directly to an S3 bucket to make it a static website.
This policy grants read access to **all unauthenticated** users.
"""
return Policy(
Statement=[
Statement(
Effect=Allow,
Principal=Principal("*"),
Action=[s3.GetObject],
Resource=[s3_objects_arn(bucket)],
)
]
) | Attach this policy directly to an S3 bucket to make it a static website.
This policy grants read access to **all unauthenticated** users. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L126-L140 |
remind101/stacker_blueprints | stacker_blueprints/policies.py | lambda_vpc_execution_statements | def lambda_vpc_execution_statements():
"""Allow Lambda to manipuate EC2 ENIs for VPC support."""
return [
Statement(
Effect=Allow,
Resource=['*'],
Action=[
ec2.CreateNetworkInterface,
ec2.DescribeNetworkInterfaces,
ec2.DeleteNetworkInterface,
]
)
] | python | def lambda_vpc_execution_statements():
"""Allow Lambda to manipuate EC2 ENIs for VPC support."""
return [
Statement(
Effect=Allow,
Resource=['*'],
Action=[
ec2.CreateNetworkInterface,
ec2.DescribeNetworkInterfaces,
ec2.DeleteNetworkInterface,
]
)
] | Allow Lambda to manipuate EC2 ENIs for VPC support. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L202-L214 |
remind101/stacker_blueprints | stacker_blueprints/policies.py | dynamodb_autoscaling_policy | def dynamodb_autoscaling_policy(tables):
"""Policy to allow AutoScaling a list of DynamoDB tables."""
return Policy(
Statement=[
Statement(
Effect=Allow,
Resource=dynamodb_arns(tables),
Action=[
dynamodb.DescribeTable,
dynamodb.UpdateTable,
]
),
Statement(
Effect=Allow,
Resource=['*'],
Action=[
cloudwatch.PutMetricAlarm,
cloudwatch.DescribeAlarms,
cloudwatch.GetMetricStatistics,
cloudwatch.SetAlarmState,
cloudwatch.DeleteAlarms,
]
),
]
) | python | def dynamodb_autoscaling_policy(tables):
"""Policy to allow AutoScaling a list of DynamoDB tables."""
return Policy(
Statement=[
Statement(
Effect=Allow,
Resource=dynamodb_arns(tables),
Action=[
dynamodb.DescribeTable,
dynamodb.UpdateTable,
]
),
Statement(
Effect=Allow,
Resource=['*'],
Action=[
cloudwatch.PutMetricAlarm,
cloudwatch.DescribeAlarms,
cloudwatch.GetMetricStatistics,
cloudwatch.SetAlarmState,
cloudwatch.DeleteAlarms,
]
),
]
) | Policy to allow AutoScaling a list of DynamoDB tables. | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L222-L246 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.healpix_to_lonlat | def healpix_to_lonlat(self, healpix_index, dx=None, dy=None):
"""
Convert HEALPix indices (optionally with offsets) to longitudes/latitudes
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`, optional
1-D arrays of offsets inside the HEALPix pixel, which must be in
the range [0:1] (0.5 is the center of the HEALPix pixels). If not
specified, the position at the center of the pixel is used.
Returns
-------
lon : :class:`~astropy.coordinates.Longitude`
The longitude values
lat : :class:`~astropy.coordinates.Latitude`
The latitude values
"""
return healpix_to_lonlat(healpix_index, self.nside, dx=dx, dy=dy, order=self.order) | python | def healpix_to_lonlat(self, healpix_index, dx=None, dy=None):
"""
Convert HEALPix indices (optionally with offsets) to longitudes/latitudes
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`, optional
1-D arrays of offsets inside the HEALPix pixel, which must be in
the range [0:1] (0.5 is the center of the HEALPix pixels). If not
specified, the position at the center of the pixel is used.
Returns
-------
lon : :class:`~astropy.coordinates.Longitude`
The longitude values
lat : :class:`~astropy.coordinates.Latitude`
The latitude values
"""
return healpix_to_lonlat(healpix_index, self.nside, dx=dx, dy=dy, order=self.order) | Convert HEALPix indices (optionally with offsets) to longitudes/latitudes
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`, optional
1-D arrays of offsets inside the HEALPix pixel, which must be in
the range [0:1] (0.5 is the center of the HEALPix pixels). If not
specified, the position at the center of the pixel is used.
Returns
-------
lon : :class:`~astropy.coordinates.Longitude`
The longitude values
lat : :class:`~astropy.coordinates.Latitude`
The latitude values | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L76-L96 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.lonlat_to_healpix | def lonlat_to_healpix(self, lon, lat, return_offsets=False):
"""
Convert longitudes/latitudes to HEALPix indices (optionally with offsets)
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
return_offsets : bool
If `True`, the returned values are the HEALPix pixel as well as
``dx`` and ``dy``, the fractional positions inside the pixel. If
`False` (the default), only the HEALPix pixel is returned.
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`
1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
is the center of the HEALPix pixels). This is returned if
``return_offsets`` is `True`.
"""
return lonlat_to_healpix(lon, lat, self.nside,
return_offsets=return_offsets, order=self.order) | python | def lonlat_to_healpix(self, lon, lat, return_offsets=False):
"""
Convert longitudes/latitudes to HEALPix indices (optionally with offsets)
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
return_offsets : bool
If `True`, the returned values are the HEALPix pixel as well as
``dx`` and ``dy``, the fractional positions inside the pixel. If
`False` (the default), only the HEALPix pixel is returned.
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`
1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
is the center of the HEALPix pixels). This is returned if
``return_offsets`` is `True`.
"""
return lonlat_to_healpix(lon, lat, self.nside,
return_offsets=return_offsets, order=self.order) | Convert longitudes/latitudes to HEALPix indices (optionally with offsets)
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
return_offsets : bool
If `True`, the returned values are the HEALPix pixel as well as
``dx`` and ``dy``, the fractional positions inside the pixel. If
`False` (the default), only the HEALPix pixel is returned.
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`
1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
is the center of the HEALPix pixels). This is returned if
``return_offsets`` is `True`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L98-L122 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.bilinear_interpolation_weights | def bilinear_interpolation_weights(self, lon, lat):
"""
Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as
:class:`~astropy.units.Quantity` instances with angle units.
Returns
-------
indices : `~numpy.ndarray`
2-D array with shape (4, N) giving the four indices to use for the
interpolation
weights : `~numpy.ndarray`
2-D array with shape (4, N) giving the four weights to use for the
interpolation
"""
return bilinear_interpolation_weights(lon, lat, self.nside, order=self.order) | python | def bilinear_interpolation_weights(self, lon, lat):
"""
Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as
:class:`~astropy.units.Quantity` instances with angle units.
Returns
-------
indices : `~numpy.ndarray`
2-D array with shape (4, N) giving the four indices to use for the
interpolation
weights : `~numpy.ndarray`
2-D array with shape (4, N) giving the four weights to use for the
interpolation
"""
return bilinear_interpolation_weights(lon, lat, self.nside, order=self.order) | Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as
:class:`~astropy.units.Quantity` instances with angle units.
Returns
-------
indices : `~numpy.ndarray`
2-D array with shape (4, N) giving the four indices to use for the
interpolation
weights : `~numpy.ndarray`
2-D array with shape (4, N) giving the four weights to use for the
interpolation | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L156-L176 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.interpolate_bilinear_lonlat | def interpolate_bilinear_lonlat(self, lon, lat, values):
"""
Interpolate values at specific longitudes/latitudes using bilinear interpolation
If a position does not have four neighbours, this currently returns NaN.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
values : `~numpy.ndarray`
1-D array with the values in each HEALPix pixel. This must have a
length of the form 12 * nside ** 2 (and nside is determined
automatically from this).
Returns
-------
result : `~numpy.ndarray`
1-D array of interpolated values
"""
if len(values) != self.npix:
raise ValueError('values must be an array of length {0} (got {1})'.format(self.npix, len(values)))
return interpolate_bilinear_lonlat(lon, lat, values, order=self.order) | python | def interpolate_bilinear_lonlat(self, lon, lat, values):
"""
Interpolate values at specific longitudes/latitudes using bilinear interpolation
If a position does not have four neighbours, this currently returns NaN.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
values : `~numpy.ndarray`
1-D array with the values in each HEALPix pixel. This must have a
length of the form 12 * nside ** 2 (and nside is determined
automatically from this).
Returns
-------
result : `~numpy.ndarray`
1-D array of interpolated values
"""
if len(values) != self.npix:
raise ValueError('values must be an array of length {0} (got {1})'.format(self.npix, len(values)))
return interpolate_bilinear_lonlat(lon, lat, values, order=self.order) | Interpolate values at specific longitudes/latitudes using bilinear interpolation
If a position does not have four neighbours, this currently returns NaN.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
values : `~numpy.ndarray`
1-D array with the values in each HEALPix pixel. This must have a
length of the form 12 * nside ** 2 (and nside is determined
automatically from this).
Returns
-------
result : `~numpy.ndarray`
1-D array of interpolated values | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L178-L201 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.cone_search_lonlat | def cone_search_lonlat(self, lon, lat, radius):
"""
Find all the HEALPix pixels within a given radius of a longitude/latitude.
Note that this returns all pixels that overlap, including partially, with
the search cone. This function can only be used for a single lon/lat pair at
a time, since different calls to the function may result in a different
number of matches.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude to search around
radius : :class:`~astropy.units.Quantity`
The search radius
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices.
"""
if not lon.isscalar or not lat.isscalar or not radius.isscalar:
raise ValueError('The longitude, latitude and radius must be '
'scalar Quantity objects')
return healpix_cone_search(lon, lat, radius, self.nside, order=self.order) | python | def cone_search_lonlat(self, lon, lat, radius):
"""
Find all the HEALPix pixels within a given radius of a longitude/latitude.
Note that this returns all pixels that overlap, including partially, with
the search cone. This function can only be used for a single lon/lat pair at
a time, since different calls to the function may result in a different
number of matches.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude to search around
radius : :class:`~astropy.units.Quantity`
The search radius
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices.
"""
if not lon.isscalar or not lat.isscalar or not radius.isscalar:
raise ValueError('The longitude, latitude and radius must be '
'scalar Quantity objects')
return healpix_cone_search(lon, lat, radius, self.nside, order=self.order) | Find all the HEALPix pixels within a given radius of a longitude/latitude.
Note that this returns all pixels that overlap, including partially, with
the search cone. This function can only be used for a single lon/lat pair at
a time, since different calls to the function may result in a different
number of matches.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude to search around
radius : :class:`~astropy.units.Quantity`
The search radius
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L203-L227 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.boundaries_lonlat | def boundaries_lonlat(self, healpix_index, step):
"""
Return the longitude and latitude of the edges of HEALPix pixels
This returns the longitude and latitude of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
Returns
-------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude, as 2-D arrays where the first dimension is
the same as the ``healpix_index`` input, and the second dimension has
size ``4 * step``.
"""
return boundaries_lonlat(healpix_index, step, self.nside, order=self.order) | python | def boundaries_lonlat(self, healpix_index, step):
"""
Return the longitude and latitude of the edges of HEALPix pixels
This returns the longitude and latitude of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
Returns
-------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude, as 2-D arrays where the first dimension is
the same as the ``healpix_index`` input, and the second dimension has
size ``4 * step``.
"""
return boundaries_lonlat(healpix_index, step, self.nside, order=self.order) | Return the longitude and latitude of the edges of HEALPix pixels
This returns the longitude and latitude of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
Returns
-------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude, as 2-D arrays where the first dimension is
the same as the ``healpix_index`` input, and the second dimension has
size ``4 * step``. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L229-L251 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.neighbours | def neighbours(self, healpix_index):
"""
Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
Returns
-------
neigh : `~numpy.ndarray`
Array giving the neighbours starting SW and rotating clockwise. This has
one extra dimension compared to ``healpix_index`` - the first dimension -
which is set to 8. For example if healpix_index has shape (2, 3),
``neigh`` has shape (8, 2, 3).
"""
return neighbours(healpix_index, self.nside, order=self.order) | python | def neighbours(self, healpix_index):
"""
Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
Returns
-------
neigh : `~numpy.ndarray`
Array giving the neighbours starting SW and rotating clockwise. This has
one extra dimension compared to ``healpix_index`` - the first dimension -
which is set to 8. For example if healpix_index has shape (2, 3),
``neigh`` has shape (8, 2, 3).
"""
return neighbours(healpix_index, self.nside, order=self.order) | Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
Returns
-------
neigh : `~numpy.ndarray`
Array giving the neighbours starting SW and rotating clockwise. This has
one extra dimension compared to ``healpix_index`` - the first dimension -
which is set to 8. For example if healpix_index has shape (2, 3),
``neigh`` has shape (8, 2, 3). | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L253-L270 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.healpix_to_skycoord | def healpix_to_skycoord(self, healpix_index, dx=None, dy=None):
"""
Convert HEALPix indices (optionally with offsets) to celestial coordinates.
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.healpix_to_lonlat`.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`, optional
1-D arrays of offsets inside the HEALPix pixel, which must be in
the range [0:1] (0.5 is the center of the HEALPix pixels). If not
specified, the position at the center of the pixel is used.
Returns
-------
coord : :class:`~astropy.coordinates.SkyCoord`
The resulting celestial coordinates
"""
if self.frame is None:
raise NoFrameError("healpix_to_skycoord")
lon, lat = self.healpix_to_lonlat(healpix_index, dx=dx, dy=dy)
representation = UnitSphericalRepresentation(lon, lat, copy=False)
return SkyCoord(self.frame.realize_frame(representation)) | python | def healpix_to_skycoord(self, healpix_index, dx=None, dy=None):
"""
Convert HEALPix indices (optionally with offsets) to celestial coordinates.
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.healpix_to_lonlat`.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`, optional
1-D arrays of offsets inside the HEALPix pixel, which must be in
the range [0:1] (0.5 is the center of the HEALPix pixels). If not
specified, the position at the center of the pixel is used.
Returns
-------
coord : :class:`~astropy.coordinates.SkyCoord`
The resulting celestial coordinates
"""
if self.frame is None:
raise NoFrameError("healpix_to_skycoord")
lon, lat = self.healpix_to_lonlat(healpix_index, dx=dx, dy=dy)
representation = UnitSphericalRepresentation(lon, lat, copy=False)
return SkyCoord(self.frame.realize_frame(representation)) | Convert HEALPix indices (optionally with offsets) to celestial coordinates.
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.healpix_to_lonlat`.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`, optional
1-D arrays of offsets inside the HEALPix pixel, which must be in
the range [0:1] (0.5 is the center of the HEALPix pixels). If not
specified, the position at the center of the pixel is used.
Returns
-------
coord : :class:`~astropy.coordinates.SkyCoord`
The resulting celestial coordinates | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L272-L298 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.skycoord_to_healpix | def skycoord_to_healpix(self, skycoord, return_offsets=False):
"""
Convert celestial coordinates to HEALPix indices (optionally with offsets).
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates to convert
return_offsets : bool
If `True`, the returned values are the HEALPix pixel as well as
``dx`` and ``dy``, the fractional positions inside the pixel. If
`False` (the default), only the HEALPix pixel is returned.
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`
1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
is the center of the HEALPix pixels). This is returned if
``return_offsets`` is `True`.
"""
if self.frame is None:
raise NoFrameError("skycoord_to_healpix")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.lonlat_to_healpix(lon, lat, return_offsets=return_offsets) | python | def skycoord_to_healpix(self, skycoord, return_offsets=False):
"""
Convert celestial coordinates to HEALPix indices (optionally with offsets).
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates to convert
return_offsets : bool
If `True`, the returned values are the HEALPix pixel as well as
``dx`` and ``dy``, the fractional positions inside the pixel. If
`False` (the default), only the HEALPix pixel is returned.
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`
1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
is the center of the HEALPix pixels). This is returned if
``return_offsets`` is `True`.
"""
if self.frame is None:
raise NoFrameError("skycoord_to_healpix")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.lonlat_to_healpix(lon, lat, return_offsets=return_offsets) | Convert celestial coordinates to HEALPix indices (optionally with offsets).
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates to convert
return_offsets : bool
If `True`, the returned values are the HEALPix pixel as well as
``dx`` and ``dy``, the fractional positions inside the pixel. If
`False` (the default), only the HEALPix pixel is returned.
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`
1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
is the center of the HEALPix pixels). This is returned if
``return_offsets`` is `True`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L300-L331 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.interpolate_bilinear_skycoord | def interpolate_bilinear_skycoord(self, skycoord, values):
"""
Interpolate values at specific celestial coordinates using bilinear interpolation.
If a position does not have four neighbours, this currently returns NaN.
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.interpolate_bilinear_lonlat`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates at which to interpolate
values : `~numpy.ndarray`
1-D array with the values in each HEALPix pixel. This must have a
length of the form 12 * nside ** 2 (and nside is determined
automatically from this).
Returns
-------
result : `~numpy.ndarray`
1-D array of interpolated values
"""
if self.frame is None:
raise NoFrameError("interpolate_bilinear_skycoord")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.interpolate_bilinear_lonlat(lon, lat, values) | python | def interpolate_bilinear_skycoord(self, skycoord, values):
"""
Interpolate values at specific celestial coordinates using bilinear interpolation.
If a position does not have four neighbours, this currently returns NaN.
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.interpolate_bilinear_lonlat`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates at which to interpolate
values : `~numpy.ndarray`
1-D array with the values in each HEALPix pixel. This must have a
length of the form 12 * nside ** 2 (and nside is determined
automatically from this).
Returns
-------
result : `~numpy.ndarray`
1-D array of interpolated values
"""
if self.frame is None:
raise NoFrameError("interpolate_bilinear_skycoord")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.interpolate_bilinear_lonlat(lon, lat, values) | Interpolate values at specific celestial coordinates using bilinear interpolation.
If a position does not have four neighbours, this currently returns NaN.
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.interpolate_bilinear_lonlat`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates at which to interpolate
values : `~numpy.ndarray`
1-D array with the values in each HEALPix pixel. This must have a
length of the form 12 * nside ** 2 (and nside is determined
automatically from this).
Returns
-------
result : `~numpy.ndarray`
1-D array of interpolated values | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L333-L362 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.cone_search_skycoord | def cone_search_skycoord(self, skycoord, radius):
"""
Find all the HEALPix pixels within a given radius of a celestial position.
Note that this returns all pixels that overlap, including partially,
with the search cone. This function can only be used for a single
celestial position at a time, since different calls to the function may
result in a different number of matches.
This method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame,
you can instead use :meth:`~astropy_healpix.HEALPix.cone_search_lonlat`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates to use for the cone search
radius : :class:`~astropy.units.Quantity`
The search radius
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices.
"""
if self.frame is None:
raise NoFrameError("cone_search_skycoord")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.cone_search_lonlat(lon, lat, radius) | python | def cone_search_skycoord(self, skycoord, radius):
"""
Find all the HEALPix pixels within a given radius of a celestial position.
Note that this returns all pixels that overlap, including partially,
with the search cone. This function can only be used for a single
celestial position at a time, since different calls to the function may
result in a different number of matches.
This method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame,
you can instead use :meth:`~astropy_healpix.HEALPix.cone_search_lonlat`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates to use for the cone search
radius : :class:`~astropy.units.Quantity`
The search radius
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices.
"""
if self.frame is None:
raise NoFrameError("cone_search_skycoord")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.cone_search_lonlat(lon, lat, radius) | Find all the HEALPix pixels within a given radius of a celestial position.
Note that this returns all pixels that overlap, including partially,
with the search cone. This function can only be used for a single
celestial position at a time, since different calls to the function may
result in a different number of matches.
This method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame,
you can instead use :meth:`~astropy_healpix.HEALPix.cone_search_lonlat`.
Parameters
----------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates to use for the cone search
radius : :class:`~astropy.units.Quantity`
The search radius
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L364-L394 |
astropy/astropy-healpix | astropy_healpix/high_level.py | HEALPix.boundaries_skycoord | def boundaries_skycoord(self, healpix_index, step):
"""
Return the celestial coordinates of the edges of HEALPix pixels
This returns the celestial coordinates of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
This method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame,
you can instead use :meth:`~astropy_healpix.HEALPix.boundaries_lonlat`.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
Returns
-------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates of the HEALPix pixel boundaries
"""
if self.frame is None:
raise NoFrameError("boundaries_skycoord")
lon, lat = self.boundaries_lonlat(healpix_index, step)
representation = UnitSphericalRepresentation(lon, lat, copy=False)
return SkyCoord(self.frame.realize_frame(representation)) | python | def boundaries_skycoord(self, healpix_index, step):
"""
Return the celestial coordinates of the edges of HEALPix pixels
This returns the celestial coordinates of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
This method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame,
you can instead use :meth:`~astropy_healpix.HEALPix.boundaries_lonlat`.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
Returns
-------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates of the HEALPix pixel boundaries
"""
if self.frame is None:
raise NoFrameError("boundaries_skycoord")
lon, lat = self.boundaries_lonlat(healpix_index, step)
representation = UnitSphericalRepresentation(lon, lat, copy=False)
return SkyCoord(self.frame.realize_frame(representation)) | Return the celestial coordinates of the edges of HEALPix pixels
This returns the celestial coordinates of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
This method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame,
you can instead use :meth:`~astropy_healpix.HEALPix.boundaries_lonlat`.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
Returns
-------
skycoord : :class:`~astropy.coordinates.SkyCoord`
The celestial coordinates of the HEALPix pixel boundaries | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L396-L424 |
astropy/astropy-healpix | astropy_healpix/core.py | level_to_nside | def level_to_nside(level):
"""
Find the pixel dimensions of the top-level HEALPix tiles.
This is given by ``nside = 2**level``.
Parameters
----------
level : int
The resolution level
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
"""
level = np.asarray(level, dtype=np.int64)
_validate_level(level)
return 2 ** level | python | def level_to_nside(level):
"""
Find the pixel dimensions of the top-level HEALPix tiles.
This is given by ``nside = 2**level``.
Parameters
----------
level : int
The resolution level
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
"""
level = np.asarray(level, dtype=np.int64)
_validate_level(level)
return 2 ** level | Find the pixel dimensions of the top-level HEALPix tiles.
This is given by ``nside = 2**level``.
Parameters
----------
level : int
The resolution level
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L86-L105 |
astropy/astropy-healpix | astropy_healpix/core.py | nside_to_level | def nside_to_level(nside):
"""
Find the HEALPix level for a given nside.
This is given by ``level = log2(nside)``.
This function is the inverse of `level_to_nside`.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Must be a power of two.
Returns
-------
level : int
The level of the HEALPix cells
"""
nside = np.asarray(nside, dtype=np.int64)
_validate_nside(nside)
return np.log2(nside).astype(np.int64) | python | def nside_to_level(nside):
"""
Find the HEALPix level for a given nside.
This is given by ``level = log2(nside)``.
This function is the inverse of `level_to_nside`.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Must be a power of two.
Returns
-------
level : int
The level of the HEALPix cells
"""
nside = np.asarray(nside, dtype=np.int64)
_validate_nside(nside)
return np.log2(nside).astype(np.int64) | Find the HEALPix level for a given nside.
This is given by ``level = log2(nside)``.
This function is the inverse of `level_to_nside`.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Must be a power of two.
Returns
-------
level : int
The level of the HEALPix cells | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L108-L130 |
astropy/astropy-healpix | astropy_healpix/core.py | uniq_to_level_ipix | def uniq_to_level_ipix(uniq):
"""
Convert a HEALPix cell uniq number to its (level, ipix) equivalent.
A uniq number is a 64 bits integer equaling to : ipix + 4*(4**level). Please read
this `paper <http://ivoa.net/documents/MOC/20140602/REC-MOC-1.0-20140602.pdf>`_
for more details about uniq numbers.
Parameters
----------
uniq : int
The uniq number of a HEALPix cell.
Returns
-------
level, ipix: int, int
The level and index of the HEALPix cell computed from ``uniq``.
"""
uniq = np.asarray(uniq, dtype=np.int64)
level = (np.log2(uniq//4)) // 2
level = level.astype(np.int64)
_validate_level(level)
ipix = uniq - (1 << 2*(level + 1))
_validate_npix(level, ipix)
return level, ipix | python | def uniq_to_level_ipix(uniq):
"""
Convert a HEALPix cell uniq number to its (level, ipix) equivalent.
A uniq number is a 64 bits integer equaling to : ipix + 4*(4**level). Please read
this `paper <http://ivoa.net/documents/MOC/20140602/REC-MOC-1.0-20140602.pdf>`_
for more details about uniq numbers.
Parameters
----------
uniq : int
The uniq number of a HEALPix cell.
Returns
-------
level, ipix: int, int
The level and index of the HEALPix cell computed from ``uniq``.
"""
uniq = np.asarray(uniq, dtype=np.int64)
level = (np.log2(uniq//4)) // 2
level = level.astype(np.int64)
_validate_level(level)
ipix = uniq - (1 << 2*(level + 1))
_validate_npix(level, ipix)
return level, ipix | Convert a HEALPix cell uniq number to its (level, ipix) equivalent.
A uniq number is a 64 bits integer equaling to : ipix + 4*(4**level). Please read
this `paper <http://ivoa.net/documents/MOC/20140602/REC-MOC-1.0-20140602.pdf>`_
for more details about uniq numbers.
Parameters
----------
uniq : int
The uniq number of a HEALPix cell.
Returns
-------
level, ipix: int, int
The level and index of the HEALPix cell computed from ``uniq``. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L133-L160 |
astropy/astropy-healpix | astropy_healpix/core.py | level_ipix_to_uniq | def level_ipix_to_uniq(level, ipix):
"""
Convert a level and HEALPix index into a uniq number representing the cell.
This function is the inverse of `uniq_to_level_ipix`.
Parameters
----------
level : int
The level of the HEALPix cell
ipix : int
The index of the HEALPix cell
Returns
-------
uniq : int
The uniq number representing the HEALPix cell.
"""
level = np.asarray(level, dtype=np.int64)
ipix = np.asarray(ipix, dtype=np.int64)
_validate_level(level)
_validate_npix(level, ipix)
return ipix + (1 << 2*(level + 1)) | python | def level_ipix_to_uniq(level, ipix):
"""
Convert a level and HEALPix index into a uniq number representing the cell.
This function is the inverse of `uniq_to_level_ipix`.
Parameters
----------
level : int
The level of the HEALPix cell
ipix : int
The index of the HEALPix cell
Returns
-------
uniq : int
The uniq number representing the HEALPix cell.
"""
level = np.asarray(level, dtype=np.int64)
ipix = np.asarray(ipix, dtype=np.int64)
_validate_level(level)
_validate_npix(level, ipix)
return ipix + (1 << 2*(level + 1)) | Convert a level and HEALPix index into a uniq number representing the cell.
This function is the inverse of `uniq_to_level_ipix`.
Parameters
----------
level : int
The level of the HEALPix cell
ipix : int
The index of the HEALPix cell
Returns
-------
uniq : int
The uniq number representing the HEALPix cell. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L163-L187 |
astropy/astropy-healpix | astropy_healpix/core.py | nside_to_pixel_area | def nside_to_pixel_area(nside):
"""
Find the area of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
pixel_area : :class:`~astropy.units.Quantity`
The area of the HEALPix pixels
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
npix = 12 * nside * nside
pixel_area = 4 * math.pi / npix * u.sr
return pixel_area | python | def nside_to_pixel_area(nside):
"""
Find the area of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
pixel_area : :class:`~astropy.units.Quantity`
The area of the HEALPix pixels
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
npix = 12 * nside * nside
pixel_area = 4 * math.pi / npix * u.sr
return pixel_area | Find the area of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
pixel_area : :class:`~astropy.units.Quantity`
The area of the HEALPix pixels | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L190-L209 |
astropy/astropy-healpix | astropy_healpix/core.py | nside_to_pixel_resolution | def nside_to_pixel_resolution(nside):
"""
Find the resolution of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
resolution : :class:`~astropy.units.Quantity`
The resolution of the HEALPix pixels
See also
--------
pixel_resolution_to_nside
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin) | python | def nside_to_pixel_resolution(nside):
"""
Find the resolution of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
resolution : :class:`~astropy.units.Quantity`
The resolution of the HEALPix pixels
See also
--------
pixel_resolution_to_nside
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin) | Find the resolution of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
resolution : :class:`~astropy.units.Quantity`
The resolution of the HEALPix pixels
See also
--------
pixel_resolution_to_nside | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L212-L233 |
astropy/astropy-healpix | astropy_healpix/core.py | pixel_resolution_to_nside | def pixel_resolution_to_nside(resolution, round='nearest'):
"""Find closest HEALPix nside for a given angular resolution.
This function is the inverse of `nside_to_pixel_resolution`,
for the default rounding scheme of ``round='nearest'``.
If you choose ``round='up'``, you'll get HEALPix pixels that
have at least the requested resolution (usually a bit better
due to rounding).
Pixel resolution is defined as square root of pixel area.
Parameters
----------
resolution : `~astropy.units.Quantity`
Angular resolution
round : {'up', 'nearest', 'down'}
Which way to round
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Always a power of 2.
Examples
--------
>>> from astropy import units as u
>>> from astropy_healpix import pixel_resolution_to_nside
>>> pixel_resolution_to_nside(13 * u.arcmin)
256
>>> pixel_resolution_to_nside(13 * u.arcmin, round='up')
512
"""
resolution = resolution.to(u.rad).value
pixel_area = resolution * resolution
npix = 4 * math.pi / pixel_area
nside = np.sqrt(npix / 12)
# Now we have to round to the closest ``nside``
# Since ``nside`` must be a power of two,
# we first compute the corresponding ``level = log2(nside)`
# round the level and then go back to nside
level = np.log2(nside)
if round == 'up':
level = np.ceil(level)
elif round == 'nearest':
level = np.round(level)
elif round == 'down':
level = np.floor(level)
else:
raise ValueError('Invalid value for round: {!r}'.format(round))
# For very low requested resolution (i.e. large angle values), we
# return ``level=0``, i.e. ``nside=1``, i.e. the lowest resolution
# that exists with HEALPix
level = np.clip(level.astype(int), 0, None)
return level_to_nside(level) | python | def pixel_resolution_to_nside(resolution, round='nearest'):
"""Find closest HEALPix nside for a given angular resolution.
This function is the inverse of `nside_to_pixel_resolution`,
for the default rounding scheme of ``round='nearest'``.
If you choose ``round='up'``, you'll get HEALPix pixels that
have at least the requested resolution (usually a bit better
due to rounding).
Pixel resolution is defined as square root of pixel area.
Parameters
----------
resolution : `~astropy.units.Quantity`
Angular resolution
round : {'up', 'nearest', 'down'}
Which way to round
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Always a power of 2.
Examples
--------
>>> from astropy import units as u
>>> from astropy_healpix import pixel_resolution_to_nside
>>> pixel_resolution_to_nside(13 * u.arcmin)
256
>>> pixel_resolution_to_nside(13 * u.arcmin, round='up')
512
"""
resolution = resolution.to(u.rad).value
pixel_area = resolution * resolution
npix = 4 * math.pi / pixel_area
nside = np.sqrt(npix / 12)
# Now we have to round to the closest ``nside``
# Since ``nside`` must be a power of two,
# we first compute the corresponding ``level = log2(nside)`
# round the level and then go back to nside
level = np.log2(nside)
if round == 'up':
level = np.ceil(level)
elif round == 'nearest':
level = np.round(level)
elif round == 'down':
level = np.floor(level)
else:
raise ValueError('Invalid value for round: {!r}'.format(round))
# For very low requested resolution (i.e. large angle values), we
# return ``level=0``, i.e. ``nside=1``, i.e. the lowest resolution
# that exists with HEALPix
level = np.clip(level.astype(int), 0, None)
return level_to_nside(level) | Find closest HEALPix nside for a given angular resolution.
This function is the inverse of `nside_to_pixel_resolution`,
for the default rounding scheme of ``round='nearest'``.
If you choose ``round='up'``, you'll get HEALPix pixels that
have at least the requested resolution (usually a bit better
due to rounding).
Pixel resolution is defined as square root of pixel area.
Parameters
----------
resolution : `~astropy.units.Quantity`
Angular resolution
round : {'up', 'nearest', 'down'}
Which way to round
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Always a power of 2.
Examples
--------
>>> from astropy import units as u
>>> from astropy_healpix import pixel_resolution_to_nside
>>> pixel_resolution_to_nside(13 * u.arcmin)
256
>>> pixel_resolution_to_nside(13 * u.arcmin, round='up')
512 | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L236-L295 |
astropy/astropy-healpix | astropy_healpix/core.py | nside_to_npix | def nside_to_npix(nside):
"""
Find the number of pixels corresponding to a HEALPix resolution.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
npix : int
The number of pixels in the HEALPix map.
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return 12 * nside ** 2 | python | def nside_to_npix(nside):
"""
Find the number of pixels corresponding to a HEALPix resolution.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
npix : int
The number of pixels in the HEALPix map.
"""
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return 12 * nside ** 2 | Find the number of pixels corresponding to a HEALPix resolution.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
npix : int
The number of pixels in the HEALPix map. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L298-L314 |
astropy/astropy-healpix | astropy_healpix/core.py | npix_to_nside | def npix_to_nside(npix):
"""
Find the number of pixels on the side of one of the 12 'top-level' HEALPix
tiles given a total number of pixels.
Parameters
----------
npix : int
The number of pixels in the HEALPix map.
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
"""
npix = np.asanyarray(npix, dtype=np.int64)
if not np.all(npix % 12 == 0):
raise ValueError('Number of pixels must be divisible by 12')
square_root = np.sqrt(npix / 12)
if not np.all(square_root ** 2 == npix / 12):
raise ValueError('Number of pixels is not of the form 12 * nside ** 2')
return np.round(square_root).astype(int) | python | def npix_to_nside(npix):
"""
Find the number of pixels on the side of one of the 12 'top-level' HEALPix
tiles given a total number of pixels.
Parameters
----------
npix : int
The number of pixels in the HEALPix map.
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
"""
npix = np.asanyarray(npix, dtype=np.int64)
if not np.all(npix % 12 == 0):
raise ValueError('Number of pixels must be divisible by 12')
square_root = np.sqrt(npix / 12)
if not np.all(square_root ** 2 == npix / 12):
raise ValueError('Number of pixels is not of the form 12 * nside ** 2')
return np.round(square_root).astype(int) | Find the number of pixels on the side of one of the 12 'top-level' HEALPix
tiles given a total number of pixels.
Parameters
----------
npix : int
The number of pixels in the HEALPix map.
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L317-L342 |
astropy/astropy-healpix | astropy_healpix/core.py | healpix_to_lonlat | def healpix_to_lonlat(healpix_index, nside, dx=None, dy=None, order='ring'):
"""
Convert HEALPix indices (optionally with offsets) to longitudes/latitudes.
If no offsets (``dx`` and ``dy``) are provided, the coordinates will default
to those at the center of the HEALPix pixels.
Parameters
----------
healpix_index : int or `~numpy.ndarray`
HEALPix indices (as a scalar or array)
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
dx, dy : float or `~numpy.ndarray`, optional
Offsets inside the HEALPix pixel, which must be in the range [0:1],
where 0.5 is the center of the HEALPix pixels (as scalars or arrays)
order : { 'nested' | 'ring' }, optional
Order of HEALPix pixels
Returns
-------
lon : :class:`~astropy.coordinates.Longitude`
The longitude values
lat : :class:`~astropy.coordinates.Latitude`
The latitude values
"""
_validate_nside(nside)
if _validate_order(order) == 'ring':
func = _core.healpix_ring_to_lonlat
else: # _validate_order(order) == 'nested'
func = _core.healpix_nested_to_lonlat
if dx is None:
dx = 0.5
else:
_validate_offset('x', dx)
if dy is None:
dy = 0.5
else:
_validate_offset('y', dy)
nside = np.asarray(nside, dtype=np.intc)
lon, lat = func(healpix_index, nside, dx, dy)
lon = Longitude(lon, unit=u.rad, copy=False)
lat = Latitude(lat, unit=u.rad, copy=False)
return lon, lat | python | def healpix_to_lonlat(healpix_index, nside, dx=None, dy=None, order='ring'):
"""
Convert HEALPix indices (optionally with offsets) to longitudes/latitudes.
If no offsets (``dx`` and ``dy``) are provided, the coordinates will default
to those at the center of the HEALPix pixels.
Parameters
----------
healpix_index : int or `~numpy.ndarray`
HEALPix indices (as a scalar or array)
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
dx, dy : float or `~numpy.ndarray`, optional
Offsets inside the HEALPix pixel, which must be in the range [0:1],
where 0.5 is the center of the HEALPix pixels (as scalars or arrays)
order : { 'nested' | 'ring' }, optional
Order of HEALPix pixels
Returns
-------
lon : :class:`~astropy.coordinates.Longitude`
The longitude values
lat : :class:`~astropy.coordinates.Latitude`
The latitude values
"""
_validate_nside(nside)
if _validate_order(order) == 'ring':
func = _core.healpix_ring_to_lonlat
else: # _validate_order(order) == 'nested'
func = _core.healpix_nested_to_lonlat
if dx is None:
dx = 0.5
else:
_validate_offset('x', dx)
if dy is None:
dy = 0.5
else:
_validate_offset('y', dy)
nside = np.asarray(nside, dtype=np.intc)
lon, lat = func(healpix_index, nside, dx, dy)
lon = Longitude(lon, unit=u.rad, copy=False)
lat = Latitude(lat, unit=u.rad, copy=False)
return lon, lat | Convert HEALPix indices (optionally with offsets) to longitudes/latitudes.
If no offsets (``dx`` and ``dy``) are provided, the coordinates will default
to those at the center of the HEALPix pixels.
Parameters
----------
healpix_index : int or `~numpy.ndarray`
HEALPix indices (as a scalar or array)
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
dx, dy : float or `~numpy.ndarray`, optional
Offsets inside the HEALPix pixel, which must be in the range [0:1],
where 0.5 is the center of the HEALPix pixels (as scalars or arrays)
order : { 'nested' | 'ring' }, optional
Order of HEALPix pixels
Returns
-------
lon : :class:`~astropy.coordinates.Longitude`
The longitude values
lat : :class:`~astropy.coordinates.Latitude`
The latitude values | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L345-L395 |
astropy/astropy-healpix | astropy_healpix/core.py | lonlat_to_healpix | def lonlat_to_healpix(lon, lat, nside, return_offsets=False, order='ring'):
"""
Convert longitudes/latitudes to HEALPix indices
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity`
instances with angle units.
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
return_offsets : bool, optional
If `True`, the returned values are the HEALPix pixel indices as well as
``dx`` and ``dy``, the fractional positions inside the pixels. If
`False` (the default), only the HEALPix pixel indices is returned.
Returns
-------
healpix_index : int or `~numpy.ndarray`
The HEALPix indices
dx, dy : `~numpy.ndarray`
Offsets inside the HEALPix pixel in the range [0:1], where 0.5 is the
center of the HEALPix pixels
"""
if _validate_order(order) == 'ring':
func = _core.lonlat_to_healpix_ring
else: # _validate_order(order) == 'nested'
func = _core.lonlat_to_healpix_nested
nside = np.asarray(nside, dtype=np.intc)
lon = lon.to_value(u.rad)
lat = lat.to_value(u.rad)
healpix_index, dx, dy = func(lon, lat, nside)
if return_offsets:
return healpix_index, dx, dy
else:
return healpix_index | python | def lonlat_to_healpix(lon, lat, nside, return_offsets=False, order='ring'):
"""
Convert longitudes/latitudes to HEALPix indices
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity`
instances with angle units.
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
return_offsets : bool, optional
If `True`, the returned values are the HEALPix pixel indices as well as
``dx`` and ``dy``, the fractional positions inside the pixels. If
`False` (the default), only the HEALPix pixel indices is returned.
Returns
-------
healpix_index : int or `~numpy.ndarray`
The HEALPix indices
dx, dy : `~numpy.ndarray`
Offsets inside the HEALPix pixel in the range [0:1], where 0.5 is the
center of the HEALPix pixels
"""
if _validate_order(order) == 'ring':
func = _core.lonlat_to_healpix_ring
else: # _validate_order(order) == 'nested'
func = _core.lonlat_to_healpix_nested
nside = np.asarray(nside, dtype=np.intc)
lon = lon.to_value(u.rad)
lat = lat.to_value(u.rad)
healpix_index, dx, dy = func(lon, lat, nside)
if return_offsets:
return healpix_index, dx, dy
else:
return healpix_index | Convert longitudes/latitudes to HEALPix indices
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity`
instances with angle units.
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
return_offsets : bool, optional
If `True`, the returned values are the HEALPix pixel indices as well as
``dx`` and ``dy``, the fractional positions inside the pixels. If
`False` (the default), only the HEALPix pixel indices is returned.
Returns
-------
healpix_index : int or `~numpy.ndarray`
The HEALPix indices
dx, dy : `~numpy.ndarray`
Offsets inside the HEALPix pixel in the range [0:1], where 0.5 is the
center of the HEALPix pixels | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L398-L440 |
astropy/astropy-healpix | astropy_healpix/core.py | nested_to_ring | def nested_to_ring(nested_index, nside):
"""
Convert a HEALPix 'nested' index to a HEALPix 'ring' index
Parameters
----------
nested_index : int or `~numpy.ndarray`
Healpix index using the 'nested' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
Returns
-------
ring_index : int or `~numpy.ndarray`
Healpix index using the 'ring' ordering
"""
nside = np.asarray(nside, dtype=np.intc)
return _core.nested_to_ring(nested_index, nside) | python | def nested_to_ring(nested_index, nside):
"""
Convert a HEALPix 'nested' index to a HEALPix 'ring' index
Parameters
----------
nested_index : int or `~numpy.ndarray`
Healpix index using the 'nested' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
Returns
-------
ring_index : int or `~numpy.ndarray`
Healpix index using the 'ring' ordering
"""
nside = np.asarray(nside, dtype=np.intc)
return _core.nested_to_ring(nested_index, nside) | Convert a HEALPix 'nested' index to a HEALPix 'ring' index
Parameters
----------
nested_index : int or `~numpy.ndarray`
Healpix index using the 'nested' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
Returns
-------
ring_index : int or `~numpy.ndarray`
Healpix index using the 'ring' ordering | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L443-L462 |
astropy/astropy-healpix | astropy_healpix/core.py | ring_to_nested | def ring_to_nested(ring_index, nside):
"""
Convert a HEALPix 'ring' index to a HEALPix 'nested' index
Parameters
----------
ring_index : int or `~numpy.ndarray`
Healpix index using the 'ring' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
Returns
-------
nested_index : int or `~numpy.ndarray`
Healpix index using the 'nested' ordering
"""
nside = np.asarray(nside, dtype=np.intc)
return _core.ring_to_nested(ring_index, nside) | python | def ring_to_nested(ring_index, nside):
"""
Convert a HEALPix 'ring' index to a HEALPix 'nested' index
Parameters
----------
ring_index : int or `~numpy.ndarray`
Healpix index using the 'ring' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
Returns
-------
nested_index : int or `~numpy.ndarray`
Healpix index using the 'nested' ordering
"""
nside = np.asarray(nside, dtype=np.intc)
return _core.ring_to_nested(ring_index, nside) | Convert a HEALPix 'ring' index to a HEALPix 'nested' index
Parameters
----------
ring_index : int or `~numpy.ndarray`
Healpix index using the 'ring' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
Returns
-------
nested_index : int or `~numpy.ndarray`
Healpix index using the 'nested' ordering | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L465-L484 |
astropy/astropy-healpix | astropy_healpix/core.py | bilinear_interpolation_weights | def bilinear_interpolation_weights(lon, lat, nside, order='ring'):
"""
Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity`
instances with angle units.
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
indices : `~numpy.ndarray`
2-D array with shape (4, N) giving the four indices to use for the
interpolation
weights : `~numpy.ndarray`
2-D array with shape (4, N) giving the four weights to use for the
interpolation
"""
lon = lon.to_value(u.rad)
lat = lat.to_value(u.rad)
_validate_nside(nside)
nside = np.asarray(nside, dtype=np.intc)
result = _core.bilinear_interpolation_weights(lon, lat, nside)
indices = np.stack(result[:4])
weights = np.stack(result[4:])
if _validate_order(order) == 'nested':
indices = ring_to_nested(indices, nside)
return indices, weights | python | def bilinear_interpolation_weights(lon, lat, nside, order='ring'):
"""
Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity`
instances with angle units.
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
indices : `~numpy.ndarray`
2-D array with shape (4, N) giving the four indices to use for the
interpolation
weights : `~numpy.ndarray`
2-D array with shape (4, N) giving the four weights to use for the
interpolation
"""
lon = lon.to_value(u.rad)
lat = lat.to_value(u.rad)
_validate_nside(nside)
nside = np.asarray(nside, dtype=np.intc)
result = _core.bilinear_interpolation_weights(lon, lat, nside)
indices = np.stack(result[:4])
weights = np.stack(result[4:])
if _validate_order(order) == 'nested':
indices = ring_to_nested(indices, nside)
return indices, weights | Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity`
instances with angle units.
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
indices : `~numpy.ndarray`
2-D array with shape (4, N) giving the four indices to use for the
interpolation
weights : `~numpy.ndarray`
2-D array with shape (4, N) giving the four weights to use for the
interpolation | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L487-L526 |
astropy/astropy-healpix | astropy_healpix/core.py | interpolate_bilinear_lonlat | def interpolate_bilinear_lonlat(lon, lat, values, order='ring'):
"""
Interpolate values at specific longitudes/latitudes using bilinear interpolation
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
values : `~numpy.ndarray`
Array with the values in each HEALPix pixel. The first dimension should
have length 12 * nside ** 2 (and nside is determined automatically from
this).
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
result : float `~numpy.ndarray`
The interpolated values
"""
nside = npix_to_nside(values.shape[0])
indices, weights = bilinear_interpolation_weights(lon, lat, nside, order=order)
values = values[indices]
# At this point values has shape (N, M) where both N and M might be several
# dimensions, and weights has shape (N,), so we need to transpose in order
# to benefit from broadcasting, then transpose back so that the dimension
# with length 4 is at the start again, ready for summing.
result = (values.T * weights.T).T
return result.sum(axis=0) | python | def interpolate_bilinear_lonlat(lon, lat, values, order='ring'):
"""
Interpolate values at specific longitudes/latitudes using bilinear interpolation
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
values : `~numpy.ndarray`
Array with the values in each HEALPix pixel. The first dimension should
have length 12 * nside ** 2 (and nside is determined automatically from
this).
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
result : float `~numpy.ndarray`
The interpolated values
"""
nside = npix_to_nside(values.shape[0])
indices, weights = bilinear_interpolation_weights(lon, lat, nside, order=order)
values = values[indices]
# At this point values has shape (N, M) where both N and M might be several
# dimensions, and weights has shape (N,), so we need to transpose in order
# to benefit from broadcasting, then transpose back so that the dimension
# with length 4 is at the start again, ready for summing.
result = (values.T * weights.T).T
return result.sum(axis=0) | Interpolate values at specific longitudes/latitudes using bilinear interpolation
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
values : `~numpy.ndarray`
Array with the values in each HEALPix pixel. The first dimension should
have length 12 * nside ** 2 (and nside is determined automatically from
this).
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
result : float `~numpy.ndarray`
The interpolated values | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L529-L558 |
astropy/astropy-healpix | astropy_healpix/core.py | neighbours | def neighbours(healpix_index, nside, order='ring'):
"""
Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
neigh : `~numpy.ndarray`
Array giving the neighbours starting SW and rotating clockwise. This has
one extra dimension compared to ``healpix_index`` - the first dimension -
which is set to 8. For example if healpix_index has shape (2, 3),
``neigh`` has shape (8, 2, 3).
"""
_validate_nside(nside)
nside = np.asarray(nside, dtype=np.intc)
if _validate_order(order) == 'ring':
func = _core.neighbours_ring
else: # _validate_order(order) == 'nested'
func = _core.neighbours_nested
return np.stack(func(healpix_index, nside)) | python | def neighbours(healpix_index, nside, order='ring'):
"""
Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
neigh : `~numpy.ndarray`
Array giving the neighbours starting SW and rotating clockwise. This has
one extra dimension compared to ``healpix_index`` - the first dimension -
which is set to 8. For example if healpix_index has shape (2, 3),
``neigh`` has shape (8, 2, 3).
"""
_validate_nside(nside)
nside = np.asarray(nside, dtype=np.intc)
if _validate_order(order) == 'ring':
func = _core.neighbours_ring
else: # _validate_order(order) == 'nested'
func = _core.neighbours_nested
return np.stack(func(healpix_index, nside)) | Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
neigh : `~numpy.ndarray`
Array giving the neighbours starting SW and rotating clockwise. This has
one extra dimension compared to ``healpix_index`` - the first dimension -
which is set to 8. For example if healpix_index has shape (2, 3),
``neigh`` has shape (8, 2, 3). | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L561-L592 |
astropy/astropy-healpix | astropy_healpix/core.py | healpix_cone_search | def healpix_cone_search(lon, lat, radius, nside, order='ring'):
"""
Find all the HEALPix pixels within a given radius of a longitude/latitude.
Note that this returns all pixels that overlap, including partially, with
the search cone. This function can only be used for a single lon/lat pair at
a time, since different calls to the function may result in a different
number of matches.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude to search around
radius : :class:`~astropy.units.Quantity`
The search radius
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices.
"""
lon = lon.to_value(u.deg)
lat = lat.to_value(u.deg)
radius = radius.to_value(u.deg)
_validate_nside(nside)
order = _validate_order(order)
return _core.healpix_cone_search(lon, lat, radius, nside, order) | python | def healpix_cone_search(lon, lat, radius, nside, order='ring'):
"""
Find all the HEALPix pixels within a given radius of a longitude/latitude.
Note that this returns all pixels that overlap, including partially, with
the search cone. This function can only be used for a single lon/lat pair at
a time, since different calls to the function may result in a different
number of matches.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude to search around
radius : :class:`~astropy.units.Quantity`
The search radius
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices.
"""
lon = lon.to_value(u.deg)
lat = lat.to_value(u.deg)
radius = radius.to_value(u.deg)
_validate_nside(nside)
order = _validate_order(order)
return _core.healpix_cone_search(lon, lat, radius, nside, order) | Find all the HEALPix pixels within a given radius of a longitude/latitude.
Note that this returns all pixels that overlap, including partially, with
the search cone. This function can only be used for a single lon/lat pair at
a time, since different calls to the function may result in a different
number of matches.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude to search around
radius : :class:`~astropy.units.Quantity`
The search radius
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
healpix_index : `~numpy.ndarray`
1-D array with all the matching HEALPix pixel indices. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L595-L628 |
astropy/astropy-healpix | astropy_healpix/core.py | boundaries_lonlat | def boundaries_lonlat(healpix_index, step, nside, order='ring'):
"""
Return the longitude and latitude of the edges of HEALPix pixels
This returns the longitude and latitude of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude, as 2-D arrays where the first dimension is
the same as the ``healpix_index`` input, and the second dimension has
size ``4 * step``.
"""
healpix_index = np.asarray(healpix_index, dtype=np.int64)
step = int(step)
if step < 1:
raise ValueError('step must be at least 1')
# PERF: this could be optimized by writing a Cython routine to do this to
# avoid allocating temporary arrays
frac = np.linspace(0., 1., step + 1)[:-1]
dx = np.hstack([1 - frac, np.repeat(0, step), frac, np.repeat(1, step)])
dy = np.hstack([np.repeat(1, step), 1 - frac, np.repeat(0, step), frac])
healpix_index, dx, dy = np.broadcast_arrays(healpix_index.reshape(-1, 1), dx, dy)
lon, lat = healpix_to_lonlat(healpix_index.ravel(), nside, dx.ravel(), dy.ravel(), order=order)
lon = lon.reshape(-1, 4 * step)
lat = lat.reshape(-1, 4 * step)
return lon, lat | python | def boundaries_lonlat(healpix_index, step, nside, order='ring'):
"""
Return the longitude and latitude of the edges of HEALPix pixels
This returns the longitude and latitude of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude, as 2-D arrays where the first dimension is
the same as the ``healpix_index`` input, and the second dimension has
size ``4 * step``.
"""
healpix_index = np.asarray(healpix_index, dtype=np.int64)
step = int(step)
if step < 1:
raise ValueError('step must be at least 1')
# PERF: this could be optimized by writing a Cython routine to do this to
# avoid allocating temporary arrays
frac = np.linspace(0., 1., step + 1)[:-1]
dx = np.hstack([1 - frac, np.repeat(0, step), frac, np.repeat(1, step)])
dy = np.hstack([np.repeat(1, step), 1 - frac, np.repeat(0, step), frac])
healpix_index, dx, dy = np.broadcast_arrays(healpix_index.reshape(-1, 1), dx, dy)
lon, lat = healpix_to_lonlat(healpix_index.ravel(), nside, dx.ravel(), dy.ravel(), order=order)
lon = lon.reshape(-1, 4 * step)
lat = lat.reshape(-1, 4 * step)
return lon, lat | Return the longitude and latitude of the edges of HEALPix pixels
This returns the longitude and latitude of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix pixels
step : int
The number of steps to take along each edge.
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of HEALPix pixels
Returns
-------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude, as 2-D arrays where the first dimension is
the same as the ``healpix_index`` input, and the second dimension has
size ``4 * step``. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L631-L678 |
astropy/astropy-healpix | astropy_healpix/healpy.py | nside2resol | def nside2resol(nside, arcmin=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`."""
resolution = nside_to_pixel_resolution(nside)
if arcmin:
return resolution.to(u.arcmin).value
else:
return resolution.to(u.rad).value | python | def nside2resol(nside, arcmin=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`."""
resolution = nside_to_pixel_resolution(nside)
if arcmin:
return resolution.to(u.arcmin).value
else:
return resolution.to(u.rad).value | Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L68-L74 |
astropy/astropy-healpix | astropy_healpix/healpy.py | nside2pixarea | def nside2pixarea(nside, degrees=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`."""
area = nside_to_pixel_area(nside)
if degrees:
return area.to(u.deg ** 2).value
else:
return area.to(u.sr).value | python | def nside2pixarea(nside, degrees=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`."""
area = nside_to_pixel_area(nside)
if degrees:
return area.to(u.deg ** 2).value
else:
return area.to(u.sr).value | Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L77-L83 |
astropy/astropy-healpix | astropy_healpix/healpy.py | pix2ang | def pix2ang(nside, ipix, nest=False, lonlat=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`."""
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
return _lonlat_to_healpy(lon, lat, lonlat=lonlat) | python | def pix2ang(nside, ipix, nest=False, lonlat=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`."""
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
return _lonlat_to_healpy(lon, lat, lonlat=lonlat) | Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L101-L104 |
astropy/astropy-healpix | astropy_healpix/healpy.py | ang2pix | def ang2pix(nside, theta, phi, nest=False, lonlat=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`."""
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring') | python | def ang2pix(nside, theta, phi, nest=False, lonlat=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`."""
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring') | Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L107-L110 |
astropy/astropy-healpix | astropy_healpix/healpy.py | pix2vec | def pix2vec(nside, ipix, nest=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`."""
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
return ang2vec(*_lonlat_to_healpy(lon, lat)) | python | def pix2vec(nside, ipix, nest=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`."""
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
return ang2vec(*_lonlat_to_healpy(lon, lat)) | Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L113-L116 |
astropy/astropy-healpix | astropy_healpix/healpy.py | vec2pix | def vec2pix(nside, x, y, z, nest=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.vec2pix`."""
theta, phi = vec2ang(np.transpose([x, y, z]))
# hp.vec2ang() returns raveled arrays, which are 1D.
if np.isscalar(x):
theta = theta.item()
phi = phi.item()
else:
shape = np.shape(x)
theta = theta.reshape(shape)
phi = phi.reshape(shape)
lon, lat = _healpy_to_lonlat(theta, phi)
return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring') | python | def vec2pix(nside, x, y, z, nest=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.vec2pix`."""
theta, phi = vec2ang(np.transpose([x, y, z]))
# hp.vec2ang() returns raveled arrays, which are 1D.
if np.isscalar(x):
theta = theta.item()
phi = phi.item()
else:
shape = np.shape(x)
theta = theta.reshape(shape)
phi = phi.reshape(shape)
lon, lat = _healpy_to_lonlat(theta, phi)
return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring') | Drop-in replacement for healpy `~healpy.pixelfunc.vec2pix`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L119-L131 |
astropy/astropy-healpix | astropy_healpix/healpy.py | nest2ring | def nest2ring(nside, ipix):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`."""
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
return nested_to_ring(ipix, nside) | python | def nest2ring(nside, ipix):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`."""
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
return nested_to_ring(ipix, nside) | Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L134-L137 |
astropy/astropy-healpix | astropy_healpix/healpy.py | ring2nest | def ring2nest(nside, ipix):
"""Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`."""
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
return ring_to_nested(ipix, nside) | python | def ring2nest(nside, ipix):
"""Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`."""
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
return ring_to_nested(ipix, nside) | Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L140-L143 |
astropy/astropy-healpix | astropy_healpix/healpy.py | boundaries | def boundaries(nside, pix, step=1, nest=False):
"""Drop-in replacement for healpy `~healpy.boundaries`."""
pix = np.asarray(pix)
if pix.ndim > 1:
# For consistency with healpy we only support scalars or 1D arrays
raise ValueError("Array has to be one dimensional")
lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring')
rep_sph = UnitSphericalRepresentation(lon, lat)
rep_car = rep_sph.to_cartesian().xyz.value.swapaxes(0, 1)
if rep_car.shape[0] == 1:
return rep_car[0]
else:
return rep_car | python | def boundaries(nside, pix, step=1, nest=False):
"""Drop-in replacement for healpy `~healpy.boundaries`."""
pix = np.asarray(pix)
if pix.ndim > 1:
# For consistency with healpy we only support scalars or 1D arrays
raise ValueError("Array has to be one dimensional")
lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring')
rep_sph = UnitSphericalRepresentation(lon, lat)
rep_car = rep_sph.to_cartesian().xyz.value.swapaxes(0, 1)
if rep_car.shape[0] == 1:
return rep_car[0]
else:
return rep_car | Drop-in replacement for healpy `~healpy.boundaries`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L146-L158 |
astropy/astropy-healpix | astropy_healpix/healpy.py | vec2ang | def vec2ang(vectors, lonlat=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.vec2ang`."""
x, y, z = vectors.transpose()
rep_car = CartesianRepresentation(x, y, z)
rep_sph = rep_car.represent_as(UnitSphericalRepresentation)
return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel(), lonlat=lonlat) | python | def vec2ang(vectors, lonlat=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.vec2ang`."""
x, y, z = vectors.transpose()
rep_car = CartesianRepresentation(x, y, z)
rep_sph = rep_car.represent_as(UnitSphericalRepresentation)
return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel(), lonlat=lonlat) | Drop-in replacement for healpy `~healpy.pixelfunc.vec2ang`. | https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L161-L166 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.