id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
243,700
sryza/spark-timeseries
python/sparkts/timeseriesrdd.py
TimeSeriesRDD.to_pandas_dataframe
def to_pandas_dataframe(self): """ Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame. Each record in the RDD becomes and column, and the DataFrame is indexed with a DatetimeIndex generated from this RDD's index. """ pd_index = self.index().to_pandas_index() return pd.DataFrame.from_items(self.collect()).set_index(pd_index)
python
def to_pandas_dataframe(self): pd_index = self.index().to_pandas_index() return pd.DataFrame.from_items(self.collect()).set_index(pd_index)
[ "def", "to_pandas_dataframe", "(", "self", ")", ":", "pd_index", "=", "self", ".", "index", "(", ")", ".", "to_pandas_index", "(", ")", "return", "pd", ".", "DataFrame", ".", "from_items", "(", "self", ".", "collect", "(", ")", ")", ".", "set_index", "...
Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame. Each record in the RDD becomes and column, and the DataFrame is indexed with a DatetimeIndex generated from this RDD's index.
[ "Pulls", "the", "contents", "of", "the", "RDD", "to", "the", "driver", "and", "places", "them", "in", "a", "Pandas", "DataFrame", ".", "Each", "record", "in", "the", "RDD", "becomes", "and", "column", "and", "the", "DataFrame", "is", "indexed", "with", "...
280aa887dc08ab114411245268f230fdabb76eec
https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L148-L156
243,701
google/textfsm
textfsm/texttable.py
Row._SetHeader
def _SetHeader(self, values): """Set the row's header from a list.""" if self._values and len(values) != len(self._values): raise ValueError('Header values not equal to existing data width.') if not self._values: for _ in range(len(values)): self._values.append(None) self._keys = list(values) self._BuildIndex()
python
def _SetHeader(self, values): if self._values and len(values) != len(self._values): raise ValueError('Header values not equal to existing data width.') if not self._values: for _ in range(len(values)): self._values.append(None) self._keys = list(values) self._BuildIndex()
[ "def", "_SetHeader", "(", "self", ",", "values", ")", ":", "if", "self", ".", "_values", "and", "len", "(", "values", ")", "!=", "len", "(", "self", ".", "_values", ")", ":", "raise", "ValueError", "(", "'Header values not equal to existing data width.'", ")...
Set the row's header from a list.
[ "Set", "the", "row", "s", "header", "from", "a", "list", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L190-L198
243,702
google/textfsm
textfsm/texttable.py
Row._SetValues
def _SetValues(self, values): """Set values from supplied dictionary or list. Args: values: A Row, dict indexed by column name, or list. Raises: TypeError: Argument is not a list or dict, or list is not equal row length or dictionary keys don't match. """ def _ToStr(value): """Convert individul list entries to string.""" if isinstance(value, (list, tuple)): result = [] for val in value: result.append(str(val)) return result else: return str(value) # Row with identical header can be copied directly. if isinstance(values, Row): if self._keys != values.header: raise TypeError('Attempt to append row with mismatched header.') self._values = copy.deepcopy(values.values) elif isinstance(values, dict): for key in self._keys: if key not in values: raise TypeError('Dictionary key mismatch with row.') for key in self._keys: self[key] = _ToStr(values[key]) elif isinstance(values, list) or isinstance(values, tuple): if len(values) != len(self._values): raise TypeError('Supplied list length != row length') for (index, value) in enumerate(values): self._values[index] = _ToStr(value) else: raise TypeError('Supplied argument must be Row, dict or list, not %s', type(values))
python
def _SetValues(self, values): def _ToStr(value): """Convert individul list entries to string.""" if isinstance(value, (list, tuple)): result = [] for val in value: result.append(str(val)) return result else: return str(value) # Row with identical header can be copied directly. if isinstance(values, Row): if self._keys != values.header: raise TypeError('Attempt to append row with mismatched header.') self._values = copy.deepcopy(values.values) elif isinstance(values, dict): for key in self._keys: if key not in values: raise TypeError('Dictionary key mismatch with row.') for key in self._keys: self[key] = _ToStr(values[key]) elif isinstance(values, list) or isinstance(values, tuple): if len(values) != len(self._values): raise TypeError('Supplied list length != row length') for (index, value) in enumerate(values): self._values[index] = _ToStr(value) else: raise TypeError('Supplied argument must be Row, dict or list, not %s', type(values))
[ "def", "_SetValues", "(", "self", ",", "values", ")", ":", "def", "_ToStr", "(", "value", ")", ":", "\"\"\"Convert individul list entries to string.\"\"\"", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "result", "=", "[", ...
Set values from supplied dictionary or list. Args: values: A Row, dict indexed by column name, or list. Raises: TypeError: Argument is not a list or dict, or list is not equal row length or dictionary keys don't match.
[ "Set", "values", "from", "supplied", "dictionary", "or", "list", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L222-L264
243,703
google/textfsm
textfsm/texttable.py
TextTable.Filter
def Filter(self, function=None): """Construct Textable from the rows of which the function returns true. Args: function: A function applied to each row which returns a bool. If function is None, all rows with empty column values are removed. Returns: A new TextTable() Raises: TableError: When an invalid row entry is Append()'d """ flat = lambda x: x if isinstance(x, str) else ''.join([flat(y) for y in x]) if function is None: function = lambda row: bool(flat(row.values)) new_table = self.__class__() # pylint: disable=protected-access new_table._table = [self.header] for row in self: if function(row) is True: new_table.Append(row) return new_table
python
def Filter(self, function=None): flat = lambda x: x if isinstance(x, str) else ''.join([flat(y) for y in x]) if function is None: function = lambda row: bool(flat(row.values)) new_table = self.__class__() # pylint: disable=protected-access new_table._table = [self.header] for row in self: if function(row) is True: new_table.Append(row) return new_table
[ "def", "Filter", "(", "self", ",", "function", "=", "None", ")", ":", "flat", "=", "lambda", "x", ":", "x", "if", "isinstance", "(", "x", ",", "str", ")", "else", "''", ".", "join", "(", "[", "flat", "(", "y", ")", "for", "y", "in", "x", "]",...
Construct Textable from the rows of which the function returns true. Args: function: A function applied to each row which returns a bool. If function is None, all rows with empty column values are removed. Returns: A new TextTable() Raises: TableError: When an invalid row entry is Append()'d
[ "Construct", "Textable", "from", "the", "rows", "of", "which", "the", "function", "returns", "true", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L378-L402
243,704
google/textfsm
textfsm/texttable.py
TextTable._GetTable
def _GetTable(self): """Returns table, with column headers and separators. Returns: The whole table including headers as a string. Each row is joined by a newline and each entry by self.separator. """ result = [] # Avoid the global lookup cost on each iteration. lstr = str for row in self._table: result.append( '%s\n' % self.separator.join(lstr(v) for v in row)) return ''.join(result)
python
def _GetTable(self): result = [] # Avoid the global lookup cost on each iteration. lstr = str for row in self._table: result.append( '%s\n' % self.separator.join(lstr(v) for v in row)) return ''.join(result)
[ "def", "_GetTable", "(", "self", ")", ":", "result", "=", "[", "]", "# Avoid the global lookup cost on each iteration.", "lstr", "=", "str", "for", "row", "in", "self", ".", "_table", ":", "result", ".", "append", "(", "'%s\\n'", "%", "self", ".", "separator...
Returns table, with column headers and separators. Returns: The whole table including headers as a string. Each row is joined by a newline and each entry by self.separator.
[ "Returns", "table", "with", "column", "headers", "and", "separators", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L595-L610
243,705
google/textfsm
textfsm/texttable.py
TextTable._SetTable
def _SetTable(self, table): """Sets table, with column headers and separators.""" if not isinstance(table, TextTable): raise TypeError('Not an instance of TextTable.') self.Reset() self._table = copy.deepcopy(table._table) # pylint: disable=W0212 # Point parent table of each row back ourselves. for row in self: row.table = self
python
def _SetTable(self, table): if not isinstance(table, TextTable): raise TypeError('Not an instance of TextTable.') self.Reset() self._table = copy.deepcopy(table._table) # pylint: disable=W0212 # Point parent table of each row back ourselves. for row in self: row.table = self
[ "def", "_SetTable", "(", "self", ",", "table", ")", ":", "if", "not", "isinstance", "(", "table", ",", "TextTable", ")", ":", "raise", "TypeError", "(", "'Not an instance of TextTable.'", ")", "self", ".", "Reset", "(", ")", "self", ".", "_table", "=", "...
Sets table, with column headers and separators.
[ "Sets", "table", "with", "column", "headers", "and", "separators", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L612-L620
243,706
google/textfsm
textfsm/texttable.py
TextTable._TextJustify
def _TextJustify(self, text, col_size): """Formats text within column with white space padding. A single space is prefixed, and a number of spaces are added as a suffix such that the length of the resultant string equals the col_size. If the length of the text exceeds the column width available then it is split into words and returned as a list of string, each string contains one or more words padded to the column size. Args: text: String of text to format. col_size: integer size of column to pad out the text to. Returns: List of strings col_size in length. Raises: TableError: If col_size is too small to fit the words in the text. """ result = [] if '\n' in text: for paragraph in text.split('\n'): result.extend(self._TextJustify(paragraph, col_size)) return result wrapper = textwrap.TextWrapper(width=col_size-2, break_long_words=False, expand_tabs=False) try: text_list = wrapper.wrap(text) except ValueError: raise TableError('Field too small (minimum width: 3)') if not text_list: return [' '*col_size] for current_line in text_list: stripped_len = len(terminal.StripAnsiText(current_line)) ansi_color_adds = len(current_line) - stripped_len # +2 for white space on either side. if stripped_len + 2 > col_size: raise TableError('String contains words that do not fit in column.') result.append(' %-*s' % (col_size - 1 + ansi_color_adds, current_line)) return result
python
def _TextJustify(self, text, col_size): result = [] if '\n' in text: for paragraph in text.split('\n'): result.extend(self._TextJustify(paragraph, col_size)) return result wrapper = textwrap.TextWrapper(width=col_size-2, break_long_words=False, expand_tabs=False) try: text_list = wrapper.wrap(text) except ValueError: raise TableError('Field too small (minimum width: 3)') if not text_list: return [' '*col_size] for current_line in text_list: stripped_len = len(terminal.StripAnsiText(current_line)) ansi_color_adds = len(current_line) - stripped_len # +2 for white space on either side. if stripped_len + 2 > col_size: raise TableError('String contains words that do not fit in column.') result.append(' %-*s' % (col_size - 1 + ansi_color_adds, current_line)) return result
[ "def", "_TextJustify", "(", "self", ",", "text", ",", "col_size", ")", ":", "result", "=", "[", "]", "if", "'\\n'", "in", "text", ":", "for", "paragraph", "in", "text", ".", "split", "(", "'\\n'", ")", ":", "result", ".", "extend", "(", "self", "."...
Formats text within column with white space padding. A single space is prefixed, and a number of spaces are added as a suffix such that the length of the resultant string equals the col_size. If the length of the text exceeds the column width available then it is split into words and returned as a list of string, each string contains one or more words padded to the column size. Args: text: String of text to format. col_size: integer size of column to pad out the text to. Returns: List of strings col_size in length. Raises: TableError: If col_size is too small to fit the words in the text.
[ "Formats", "text", "within", "column", "with", "white", "space", "padding", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L639-L684
243,707
google/textfsm
textfsm/texttable.py
TextTable.index
def index(self, name=None): # pylint: disable=C6409 """Returns index number of supplied column name. Args: name: string of column name. Raises: TableError: If name not found. Returns: Index of the specified header entry. """ try: return self.header.index(name) except ValueError: raise TableError('Unknown index name %s.' % name)
python
def index(self, name=None): # pylint: disable=C6409 try: return self.header.index(name) except ValueError: raise TableError('Unknown index name %s.' % name)
[ "def", "index", "(", "self", ",", "name", "=", "None", ")", ":", "# pylint: disable=C6409", "try", ":", "return", "self", ".", "header", ".", "index", "(", "name", ")", "except", "ValueError", ":", "raise", "TableError", "(", "'Unknown index name %s.'", "%",...
Returns index number of supplied column name. Args: name: string of column name. Raises: TableError: If name not found. Returns: Index of the specified header entry.
[ "Returns", "index", "number", "of", "supplied", "column", "name", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L1074-L1089
243,708
google/textfsm
textfsm/clitable.py
CliTable._ParseCmdItem
def _ParseCmdItem(self, cmd_input, template_file=None): """Creates Texttable with output of command. Args: cmd_input: String, Device response. template_file: File object, template to parse with. Returns: TextTable containing command output. Raises: CliTableError: A template was not found for the given command. """ # Build FSM machine from the template. fsm = textfsm.TextFSM(template_file) if not self._keys: self._keys = set(fsm.GetValuesByAttrib('Key')) # Pass raw data through FSM. table = texttable.TextTable() table.header = fsm.header # Fill TextTable from record entries. for record in fsm.ParseText(cmd_input): table.Append(record) return table
python
def _ParseCmdItem(self, cmd_input, template_file=None): # Build FSM machine from the template. fsm = textfsm.TextFSM(template_file) if not self._keys: self._keys = set(fsm.GetValuesByAttrib('Key')) # Pass raw data through FSM. table = texttable.TextTable() table.header = fsm.header # Fill TextTable from record entries. for record in fsm.ParseText(cmd_input): table.Append(record) return table
[ "def", "_ParseCmdItem", "(", "self", ",", "cmd_input", ",", "template_file", "=", "None", ")", ":", "# Build FSM machine from the template.", "fsm", "=", "textfsm", ".", "TextFSM", "(", "template_file", ")", "if", "not", "self", ".", "_keys", ":", "self", ".",...
Creates Texttable with output of command. Args: cmd_input: String, Device response. template_file: File object, template to parse with. Returns: TextTable containing command output. Raises: CliTableError: A template was not found for the given command.
[ "Creates", "Texttable", "with", "output", "of", "command", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/clitable.py#L288-L313
243,709
google/textfsm
textfsm/clitable.py
CliTable._Completion
def _Completion(self, match): # pylint: disable=C6114 r"""Replaces double square brackets with variable length completion. Completion cannot be mixed with regexp matching or '\' characters i.e. '[[(\n)]] would become (\(n)?)?.' Args: match: A regex Match() object. Returns: String of the format '(a(b(c(d)?)?)?)?'. """ # Strip the outer '[[' & ']]' and replace with ()? regexp pattern. word = str(match.group())[2:-2] return '(' + ('(').join(word) + ')?' * len(word)
python
def _Completion(self, match): # pylint: disable=C6114 r"""Replaces double square brackets with variable length completion. Completion cannot be mixed with regexp matching or '\' characters i.e. '[[(\n)]] would become (\(n)?)?.' Args: match: A regex Match() object. Returns: String of the format '(a(b(c(d)?)?)?)?'. """ # Strip the outer '[[' & ']]' and replace with ()? regexp pattern. word = str(match.group())[2:-2] return '(' + ('(').join(word) + ')?' * len(word)
[ "def", "_Completion", "(", "self", ",", "match", ")", ":", "# pylint: disable=C6114", "# Strip the outer '[[' & ']]' and replace with ()? regexp pattern.", "word", "=", "str", "(", "match", ".", "group", "(", ")", ")", "[", "2", ":", "-", "2", "]", "return", "'(...
r"""Replaces double square brackets with variable length completion. Completion cannot be mixed with regexp matching or '\' characters i.e. '[[(\n)]] would become (\(n)?)?.' Args: match: A regex Match() object. Returns: String of the format '(a(b(c(d)?)?)?)?'.
[ "r", "Replaces", "double", "square", "brackets", "with", "variable", "length", "completion", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/clitable.py#L329-L344
243,710
google/textfsm
textfsm/parser.py
main
def main(argv=None): """Validate text parsed with FSM or validate an FSM via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'h', ['help']) except getopt.error as msg: raise Usage(msg) for opt, _ in opts: if opt in ('-h', '--help'): print(__doc__) print(help_msg) return 0 if not args or len(args) > 4: raise Usage('Invalid arguments.') # If we have an argument, parse content of file and display as a template. # Template displayed will match input template, minus any comment lines. with open(args[0], 'r') as template: fsm = TextFSM(template) print('FSM Template:\n%s\n' % fsm) if len(args) > 1: # Second argument is file with example cli input. # Prints parsed tabular result. with open(args[1], 'r') as f: cli_input = f.read() table = fsm.ParseText(cli_input) print('FSM Table:') result = str(fsm.header) + '\n' for line in table: result += str(line) + '\n' print(result, end='') if len(args) > 2: # Compare tabular result with data in third file argument. # Exit value indicates if processed data matched expected result. with open(args[2], 'r') as f: ref_table = f.read() if ref_table != result: print('Data mis-match!') return 1 else: print('Data match!')
python
def main(argv=None): if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'h', ['help']) except getopt.error as msg: raise Usage(msg) for opt, _ in opts: if opt in ('-h', '--help'): print(__doc__) print(help_msg) return 0 if not args or len(args) > 4: raise Usage('Invalid arguments.') # If we have an argument, parse content of file and display as a template. # Template displayed will match input template, minus any comment lines. with open(args[0], 'r') as template: fsm = TextFSM(template) print('FSM Template:\n%s\n' % fsm) if len(args) > 1: # Second argument is file with example cli input. # Prints parsed tabular result. with open(args[1], 'r') as f: cli_input = f.read() table = fsm.ParseText(cli_input) print('FSM Table:') result = str(fsm.header) + '\n' for line in table: result += str(line) + '\n' print(result, end='') if len(args) > 2: # Compare tabular result with data in third file argument. # Exit value indicates if processed data matched expected result. with open(args[2], 'r') as f: ref_table = f.read() if ref_table != result: print('Data mis-match!') return 1 else: print('Data match!')
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "argv", "[", "1", ":", "]", ",", "'h'", ",", "[", "'help'...
Validate text parsed with FSM or validate an FSM via command line.
[ "Validate", "text", "parsed", "with", "FSM", "or", "validate", "an", "FSM", "via", "command", "line", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L1044-L1093
243,711
google/textfsm
textfsm/parser.py
TextFSMOptions.ValidOptions
def ValidOptions(cls): """Returns a list of valid option names.""" valid_options = [] for obj_name in dir(cls): obj = getattr(cls, obj_name) if inspect.isclass(obj) and issubclass(obj, cls.OptionBase): valid_options.append(obj_name) return valid_options
python
def ValidOptions(cls): valid_options = [] for obj_name in dir(cls): obj = getattr(cls, obj_name) if inspect.isclass(obj) and issubclass(obj, cls.OptionBase): valid_options.append(obj_name) return valid_options
[ "def", "ValidOptions", "(", "cls", ")", ":", "valid_options", "=", "[", "]", "for", "obj_name", "in", "dir", "(", "cls", ")", ":", "obj", "=", "getattr", "(", "cls", ",", "obj_name", ")", "if", "inspect", ".", "isclass", "(", "obj", ")", "and", "is...
Returns a list of valid option names.
[ "Returns", "a", "list", "of", "valid", "option", "names", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L114-L121
243,712
google/textfsm
textfsm/parser.py
TextFSMValue.Header
def Header(self): """Fetch the header name of this Value.""" # Call OnGetValue on options. _ = [option.OnGetValue() for option in self.options] return self.name
python
def Header(self): # Call OnGetValue on options. _ = [option.OnGetValue() for option in self.options] return self.name
[ "def", "Header", "(", "self", ")", ":", "# Call OnGetValue on options.", "_", "=", "[", "option", ".", "OnGetValue", "(", ")", "for", "option", "in", "self", ".", "options", "]", "return", "self", ".", "name" ]
Fetch the header name of this Value.
[ "Fetch", "the", "header", "name", "of", "this", "Value", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L262-L266
243,713
google/textfsm
textfsm/parser.py
TextFSMValue._AddOption
def _AddOption(self, name): """Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist. """ # Check for duplicate option declaration if name in [option.name for option in self.options]: raise TextFSMTemplateError('Duplicate option "%s"' % name) # Create the option object try: option = self._options_cls.GetOption(name)(self) except AttributeError: raise TextFSMTemplateError('Unknown option "%s"' % name) self.options.append(option)
python
def _AddOption(self, name): # Check for duplicate option declaration if name in [option.name for option in self.options]: raise TextFSMTemplateError('Duplicate option "%s"' % name) # Create the option object try: option = self._options_cls.GetOption(name)(self) except AttributeError: raise TextFSMTemplateError('Unknown option "%s"' % name) self.options.append(option)
[ "def", "_AddOption", "(", "self", ",", "name", ")", ":", "# Check for duplicate option declaration", "if", "name", "in", "[", "option", ".", "name", "for", "option", "in", "self", ".", "options", "]", ":", "raise", "TextFSMTemplateError", "(", "'Duplicate option...
Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist.
[ "Add", "an", "option", "to", "this", "Value", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L321-L342
243,714
google/textfsm
textfsm/parser.py
TextFSM.Reset
def Reset(self): """Preserves FSM but resets starting state and current record.""" # Current state is Start state. self._cur_state = self.states['Start'] self._cur_state_name = 'Start' # Clear table of results and current record. self._result = [] self._ClearAllRecord()
python
def Reset(self): # Current state is Start state. self._cur_state = self.states['Start'] self._cur_state_name = 'Start' # Clear table of results and current record. self._result = [] self._ClearAllRecord()
[ "def", "Reset", "(", "self", ")", ":", "# Current state is Start state.", "self", ".", "_cur_state", "=", "self", ".", "states", "[", "'Start'", "]", "self", ".", "_cur_state_name", "=", "'Start'", "# Clear table of results and current record.", "self", ".", "_resul...
Preserves FSM but resets starting state and current record.
[ "Preserves", "FSM", "but", "resets", "starting", "state", "and", "current", "record", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L596-L605
243,715
google/textfsm
textfsm/parser.py
TextFSM._GetHeader
def _GetHeader(self): """Returns header.""" header = [] for value in self.values: try: header.append(value.Header()) except SkipValue: continue return header
python
def _GetHeader(self): header = [] for value in self.values: try: header.append(value.Header()) except SkipValue: continue return header
[ "def", "_GetHeader", "(", "self", ")", ":", "header", "=", "[", "]", "for", "value", "in", "self", ".", "values", ":", "try", ":", "header", ".", "append", "(", "value", ".", "Header", "(", ")", ")", "except", "SkipValue", ":", "continue", "return", ...
Returns header.
[ "Returns", "header", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L612-L620
243,716
google/textfsm
textfsm/parser.py
TextFSM._GetValue
def _GetValue(self, name): """Returns the TextFSMValue object natching the requested name.""" for value in self.values: if value.name == name: return value
python
def _GetValue(self, name): for value in self.values: if value.name == name: return value
[ "def", "_GetValue", "(", "self", ",", "name", ")", ":", "for", "value", "in", "self", ".", "values", ":", "if", "value", ".", "name", "==", "name", ":", "return", "value" ]
Returns the TextFSMValue object natching the requested name.
[ "Returns", "the", "TextFSMValue", "object", "natching", "the", "requested", "name", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L622-L626
243,717
google/textfsm
textfsm/parser.py
TextFSM._AppendRecord
def _AppendRecord(self): """Adds current record to result if well formed.""" # If no Values then don't output. if not self.values: return cur_record = [] for value in self.values: try: value.OnSaveRecord() except SkipRecord: self._ClearRecord() return except SkipValue: continue # Build current record into a list. cur_record.append(value.value) # If no Values in template or whole record is empty then don't output. if len(cur_record) == (cur_record.count(None) + cur_record.count([])): return # Replace any 'None' entries with null string ''. while None in cur_record: cur_record[cur_record.index(None)] = '' self._result.append(cur_record) self._ClearRecord()
python
def _AppendRecord(self): # If no Values then don't output. if not self.values: return cur_record = [] for value in self.values: try: value.OnSaveRecord() except SkipRecord: self._ClearRecord() return except SkipValue: continue # Build current record into a list. cur_record.append(value.value) # If no Values in template or whole record is empty then don't output. if len(cur_record) == (cur_record.count(None) + cur_record.count([])): return # Replace any 'None' entries with null string ''. while None in cur_record: cur_record[cur_record.index(None)] = '' self._result.append(cur_record) self._ClearRecord()
[ "def", "_AppendRecord", "(", "self", ")", ":", "# If no Values then don't output.", "if", "not", "self", ".", "values", ":", "return", "cur_record", "=", "[", "]", "for", "value", "in", "self", ".", "values", ":", "try", ":", "value", ".", "OnSaveRecord", ...
Adds current record to result if well formed.
[ "Adds", "current", "record", "to", "result", "if", "well", "formed", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L628-L657
243,718
google/textfsm
textfsm/parser.py
TextFSM._Parse
def _Parse(self, template): """Parses template file for FSM structure. Args: template: Valid template file. Raises: TextFSMTemplateError: If template file syntax is invalid. """ if not template: raise TextFSMTemplateError('Null template.') # Parse header with Variables. self._ParseFSMVariables(template) # Parse States. while self._ParseFSMState(template): pass # Validate destination states. self._ValidateFSM()
python
def _Parse(self, template): if not template: raise TextFSMTemplateError('Null template.') # Parse header with Variables. self._ParseFSMVariables(template) # Parse States. while self._ParseFSMState(template): pass # Validate destination states. self._ValidateFSM()
[ "def", "_Parse", "(", "self", ",", "template", ")", ":", "if", "not", "template", ":", "raise", "TextFSMTemplateError", "(", "'Null template.'", ")", "# Parse header with Variables.", "self", ".", "_ParseFSMVariables", "(", "template", ")", "# Parse States.", "while...
Parses template file for FSM structure. Args: template: Valid template file. Raises: TextFSMTemplateError: If template file syntax is invalid.
[ "Parses", "template", "file", "for", "FSM", "structure", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L659-L680
243,719
google/textfsm
textfsm/parser.py
TextFSM._ParseFSMVariables
def _ParseFSMVariables(self, template): """Extracts Variables from start of template file. Values are expected as a contiguous block at the head of the file. These will be line separated from the State definitions that follow. Args: template: Valid template file, with Value definitions at the top. Raises: TextFSMTemplateError: If syntax or semantic errors are found. """ self.values = [] for line in template: self._line_num += 1 line = line.rstrip() # Blank line signifies end of Value definitions. if not line: return # Skip commented lines. if self.comment_regex.match(line): continue if line.startswith('Value '): try: value = TextFSMValue( fsm=self, max_name_len=self.MAX_NAME_LEN, options_class=self._options_cls) value.Parse(line) except TextFSMTemplateError as error: raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num)) if value.name in self.header: raise TextFSMTemplateError( "Duplicate declarations for Value '%s'. Line: %s." % (value.name, self._line_num)) try: self._ValidateOptions(value) except TextFSMTemplateError as error: raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num)) self.values.append(value) self.value_map[value.name] = value.template # The line has text but without the 'Value ' prefix. elif not self.values: raise TextFSMTemplateError('No Value definitions found.') else: raise TextFSMTemplateError( 'Expected blank line after last Value entry. Line: %s.' % (self._line_num))
python
def _ParseFSMVariables(self, template): self.values = [] for line in template: self._line_num += 1 line = line.rstrip() # Blank line signifies end of Value definitions. if not line: return # Skip commented lines. if self.comment_regex.match(line): continue if line.startswith('Value '): try: value = TextFSMValue( fsm=self, max_name_len=self.MAX_NAME_LEN, options_class=self._options_cls) value.Parse(line) except TextFSMTemplateError as error: raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num)) if value.name in self.header: raise TextFSMTemplateError( "Duplicate declarations for Value '%s'. Line: %s." % (value.name, self._line_num)) try: self._ValidateOptions(value) except TextFSMTemplateError as error: raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num)) self.values.append(value) self.value_map[value.name] = value.template # The line has text but without the 'Value ' prefix. elif not self.values: raise TextFSMTemplateError('No Value definitions found.') else: raise TextFSMTemplateError( 'Expected blank line after last Value entry. Line: %s.' % (self._line_num))
[ "def", "_ParseFSMVariables", "(", "self", ",", "template", ")", ":", "self", ".", "values", "=", "[", "]", "for", "line", "in", "template", ":", "self", ".", "_line_num", "+=", "1", "line", "=", "line", ".", "rstrip", "(", ")", "# Blank line signifies en...
Extracts Variables from start of template file. Values are expected as a contiguous block at the head of the file. These will be line separated from the State definitions that follow. Args: template: Valid template file, with Value definitions at the top. Raises: TextFSMTemplateError: If syntax or semantic errors are found.
[ "Extracts", "Variables", "from", "start", "of", "template", "file", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L682-L736
243,720
google/textfsm
textfsm/parser.py
TextFSM._ParseFSMState
def _ParseFSMState(self, template): """Extracts State and associated Rules from body of template file. After the Value definitions the remainder of the template is state definitions. The routine is expected to be called iteratively until no more states remain - indicated by returning None. The routine checks that the state names are a well formed string, do not clash with reserved names and are unique. Args: template: Valid template file after Value definitions have already been read. Returns: Name of the state parsed from file. None otherwise. Raises: TextFSMTemplateError: If any state definitions are invalid. """ if not template: return state_name = '' # Strip off extra white space lines (including comments). for line in template: self._line_num += 1 line = line.rstrip() # First line is state definition if line and not self.comment_regex.match(line): # Ensure statename has valid syntax and is not a reserved word. if (not self.state_name_re.match(line) or len(line) > self.MAX_NAME_LEN or line in TextFSMRule.LINE_OP or line in TextFSMRule.RECORD_OP): raise TextFSMTemplateError("Invalid state name: '%s'. Line: %s" % (line, self._line_num)) state_name = line if state_name in self.states: raise TextFSMTemplateError("Duplicate state name: '%s'. Line: %s" % (line, self._line_num)) self.states[state_name] = [] self.state_list.append(state_name) break # Parse each rule in the state. for line in template: self._line_num += 1 line = line.rstrip() # Finish rules processing on blank line. if not line: break if self.comment_regex.match(line): continue # A rule within a state, starts with whitespace if not (line.startswith(' ^') or line.startswith('\t^')): raise TextFSMTemplateError( "Missing white space or carat ('^') before rule. Line: %s" % self._line_num) self.states[state_name].append( TextFSMRule(line, self._line_num, self.value_map)) return state_name
python
def _ParseFSMState(self, template): if not template: return state_name = '' # Strip off extra white space lines (including comments). for line in template: self._line_num += 1 line = line.rstrip() # First line is state definition if line and not self.comment_regex.match(line): # Ensure statename has valid syntax and is not a reserved word. if (not self.state_name_re.match(line) or len(line) > self.MAX_NAME_LEN or line in TextFSMRule.LINE_OP or line in TextFSMRule.RECORD_OP): raise TextFSMTemplateError("Invalid state name: '%s'. Line: %s" % (line, self._line_num)) state_name = line if state_name in self.states: raise TextFSMTemplateError("Duplicate state name: '%s'. Line: %s" % (line, self._line_num)) self.states[state_name] = [] self.state_list.append(state_name) break # Parse each rule in the state. for line in template: self._line_num += 1 line = line.rstrip() # Finish rules processing on blank line. if not line: break if self.comment_regex.match(line): continue # A rule within a state, starts with whitespace if not (line.startswith(' ^') or line.startswith('\t^')): raise TextFSMTemplateError( "Missing white space or carat ('^') before rule. Line: %s" % self._line_num) self.states[state_name].append( TextFSMRule(line, self._line_num, self.value_map)) return state_name
[ "def", "_ParseFSMState", "(", "self", ",", "template", ")", ":", "if", "not", "template", ":", "return", "state_name", "=", "''", "# Strip off extra white space lines (including comments).", "for", "line", "in", "template", ":", "self", ".", "_line_num", "+=", "1"...
Extracts State and associated Rules from body of template file. After the Value definitions the remainder of the template is state definitions. The routine is expected to be called iteratively until no more states remain - indicated by returning None. The routine checks that the state names are a well formed string, do not clash with reserved names and are unique. Args: template: Valid template file after Value definitions have already been read. Returns: Name of the state parsed from file. None otherwise. Raises: TextFSMTemplateError: If any state definitions are invalid.
[ "Extracts", "State", "and", "associated", "Rules", "from", "body", "of", "template", "file", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L743-L812
243,721
google/textfsm
textfsm/parser.py
TextFSM._ValidateFSM
def _ValidateFSM(self): """Checks state names and destinations for validity. Each destination state must exist, be a valid name and not be a reserved name. There must be a 'Start' state and if 'EOF' or 'End' states are specified, they must be empty. Returns: True if FSM is valid. Raises: TextFSMTemplateError: If any state definitions are invalid. """ # Must have 'Start' state. if 'Start' not in self.states: raise TextFSMTemplateError("Missing state 'Start'.") # 'End/EOF' state (if specified) must be empty. if self.states.get('End'): raise TextFSMTemplateError("Non-Empty 'End' state.") if self.states.get('EOF'): raise TextFSMTemplateError("Non-Empty 'EOF' state.") # Remove 'End' state. if 'End' in self.states: del self.states['End'] self.state_list.remove('End') # Ensure jump states are all valid. for state in self.states: for rule in self.states[state]: if rule.line_op == 'Error': continue if not rule.new_state or rule.new_state in ('End', 'EOF'): continue if rule.new_state not in self.states: raise TextFSMTemplateError( "State '%s' not found, referenced in state '%s'" % (rule.new_state, state)) return True
python
def _ValidateFSM(self): # Must have 'Start' state. if 'Start' not in self.states: raise TextFSMTemplateError("Missing state 'Start'.") # 'End/EOF' state (if specified) must be empty. if self.states.get('End'): raise TextFSMTemplateError("Non-Empty 'End' state.") if self.states.get('EOF'): raise TextFSMTemplateError("Non-Empty 'EOF' state.") # Remove 'End' state. if 'End' in self.states: del self.states['End'] self.state_list.remove('End') # Ensure jump states are all valid. for state in self.states: for rule in self.states[state]: if rule.line_op == 'Error': continue if not rule.new_state or rule.new_state in ('End', 'EOF'): continue if rule.new_state not in self.states: raise TextFSMTemplateError( "State '%s' not found, referenced in state '%s'" % (rule.new_state, state)) return True
[ "def", "_ValidateFSM", "(", "self", ")", ":", "# Must have 'Start' state.", "if", "'Start'", "not", "in", "self", ".", "states", ":", "raise", "TextFSMTemplateError", "(", "\"Missing state 'Start'.\"", ")", "# 'End/EOF' state (if specified) must be empty.", "if", "self", ...
Checks state names and destinations for validity. Each destination state must exist, be a valid name and not be a reserved name. There must be a 'Start' state and if 'EOF' or 'End' states are specified, they must be empty. Returns: True if FSM is valid. Raises: TextFSMTemplateError: If any state definitions are invalid.
[ "Checks", "state", "names", "and", "destinations", "for", "validity", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L814-L859
243,722
google/textfsm
textfsm/parser.py
TextFSM.ParseText
def ParseText(self, text, eof=True): """Passes CLI output through FSM and returns list of tuples. First tuple is the header, every subsequent tuple is a row. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsing only part of the file. Suppresses triggering EOF state. Raises: TextFSMError: An error occurred within the FSM. Returns: List of Lists. """ lines = [] if text: lines = text.splitlines() for line in lines: self._CheckLine(line) if self._cur_state_name in ('End', 'EOF'): break if self._cur_state_name != 'End' and 'EOF' not in self.states and eof: # Implicit EOF performs Next.Record operation. # Suppressed if Null EOF state is instantiated. self._AppendRecord() return self._result
python
def ParseText(self, text, eof=True): lines = [] if text: lines = text.splitlines() for line in lines: self._CheckLine(line) if self._cur_state_name in ('End', 'EOF'): break if self._cur_state_name != 'End' and 'EOF' not in self.states and eof: # Implicit EOF performs Next.Record operation. # Suppressed if Null EOF state is instantiated. self._AppendRecord() return self._result
[ "def", "ParseText", "(", "self", ",", "text", ",", "eof", "=", "True", ")", ":", "lines", "=", "[", "]", "if", "text", ":", "lines", "=", "text", ".", "splitlines", "(", ")", "for", "line", "in", "lines", ":", "self", ".", "_CheckLine", "(", "lin...
Passes CLI output through FSM and returns list of tuples. First tuple is the header, every subsequent tuple is a row. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsing only part of the file. Suppresses triggering EOF state. Raises: TextFSMError: An error occurred within the FSM. Returns: List of Lists.
[ "Passes", "CLI", "output", "through", "FSM", "and", "returns", "list", "of", "tuples", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L861-L892
243,723
google/textfsm
textfsm/parser.py
TextFSM.ParseTextToDicts
def ParseTextToDicts(self, *args, **kwargs): """Calls ParseText and turns the result into list of dicts. List items are dicts of rows, dict key is column header and value is column value. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsing only part of the file. Suppresses triggering EOF state. Raises: TextFSMError: An error occurred within the FSM. Returns: List of dicts. """ result_lists = self.ParseText(*args, **kwargs) result_dicts = [] for row in result_lists: result_dicts.append(dict(zip(self.header, row))) return result_dicts
python
def ParseTextToDicts(self, *args, **kwargs): result_lists = self.ParseText(*args, **kwargs) result_dicts = [] for row in result_lists: result_dicts.append(dict(zip(self.header, row))) return result_dicts
[ "def", "ParseTextToDicts", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result_lists", "=", "self", ".", "ParseText", "(", "*", "args", ",", "*", "*", "kwargs", ")", "result_dicts", "=", "[", "]", "for", "row", "in", "result_lis...
Calls ParseText and turns the result into list of dicts. List items are dicts of rows, dict key is column header and value is column value. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsing only part of the file. Suppresses triggering EOF state. Raises: TextFSMError: An error occurred within the FSM. Returns: List of dicts.
[ "Calls", "ParseText", "and", "turns", "the", "result", "into", "list", "of", "dicts", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L894-L918
243,724
google/textfsm
textfsm/parser.py
TextFSM._AssignVar
def _AssignVar(self, matched, value): """Assigns variable into current record from a matched rule. If a record entry is a list then append, otherwise values are replaced. Args: matched: (regexp.match) Named group for each matched value. value: (str) The matched value. """ _value = self._GetValue(value) if _value is not None: _value.AssignVar(matched.group(value))
python
def _AssignVar(self, matched, value): _value = self._GetValue(value) if _value is not None: _value.AssignVar(matched.group(value))
[ "def", "_AssignVar", "(", "self", ",", "matched", ",", "value", ")", ":", "_value", "=", "self", ".", "_GetValue", "(", "value", ")", "if", "_value", "is", "not", "None", ":", "_value", ".", "AssignVar", "(", "matched", ".", "group", "(", "value", ")...
Assigns variable into current record from a matched rule. If a record entry is a list then append, otherwise values are replaced. Args: matched: (regexp.match) Named group for each matched value. value: (str) The matched value.
[ "Assigns", "variable", "into", "current", "record", "from", "a", "matched", "rule", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L955-L966
243,725
google/textfsm
textfsm/parser.py
TextFSM._Operations
def _Operations(self, rule, line): """Operators on the data record. Operators come in two parts and are a '.' separated pair: Operators that effect the input line or the current state (line_op). 'Next' Get next input line and restart parsing (default). 'Continue' Keep current input line and continue resume parsing. 'Error' Unrecoverable input discard result and raise Error. Operators that affect the record being built for output (record_op). 'NoRecord' Does nothing (default) 'Record' Adds the current record to the result. 'Clear' Clears non-Filldown data from the record. 'Clearall' Clears all data from the record. Args: rule: FSMRule object. line: A string, the current input line. Returns: True if state machine should restart state with new line. Raises: TextFSMError: If Error state is encountered. """ # First process the Record operators. if rule.record_op == 'Record': self._AppendRecord() elif rule.record_op == 'Clear': # Clear record. self._ClearRecord() elif rule.record_op == 'Clearall': # Clear all record entries. self._ClearAllRecord() # Lastly process line operators. if rule.line_op == 'Error': if rule.new_state: raise TextFSMError('Error: %s. Rule Line: %s. Input Line: %s.' % (rule.new_state, rule.line_num, line)) raise TextFSMError('State Error raised. Rule Line: %s. Input Line: %s' % (rule.line_num, line)) elif rule.line_op == 'Continue': # Continue with current line without returning to the start of the state. return False # Back to start of current state with a new line. return True
python
def _Operations(self, rule, line): # First process the Record operators. if rule.record_op == 'Record': self._AppendRecord() elif rule.record_op == 'Clear': # Clear record. self._ClearRecord() elif rule.record_op == 'Clearall': # Clear all record entries. self._ClearAllRecord() # Lastly process line operators. if rule.line_op == 'Error': if rule.new_state: raise TextFSMError('Error: %s. Rule Line: %s. Input Line: %s.' % (rule.new_state, rule.line_num, line)) raise TextFSMError('State Error raised. Rule Line: %s. Input Line: %s' % (rule.line_num, line)) elif rule.line_op == 'Continue': # Continue with current line without returning to the start of the state. return False # Back to start of current state with a new line. return True
[ "def", "_Operations", "(", "self", ",", "rule", ",", "line", ")", ":", "# First process the Record operators.", "if", "rule", ".", "record_op", "==", "'Record'", ":", "self", ".", "_AppendRecord", "(", ")", "elif", "rule", ".", "record_op", "==", "'Clear'", ...
Operators on the data record. Operators come in two parts and are a '.' separated pair: Operators that effect the input line or the current state (line_op). 'Next' Get next input line and restart parsing (default). 'Continue' Keep current input line and continue resume parsing. 'Error' Unrecoverable input discard result and raise Error. Operators that affect the record being built for output (record_op). 'NoRecord' Does nothing (default) 'Record' Adds the current record to the result. 'Clear' Clears non-Filldown data from the record. 'Clearall' Clears all data from the record. Args: rule: FSMRule object. line: A string, the current input line. Returns: True if state machine should restart state with new line. Raises: TextFSMError: If Error state is encountered.
[ "Operators", "on", "the", "data", "record", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L968-L1020
243,726
google/textfsm
textfsm/parser.py
TextFSM.GetValuesByAttrib
def GetValuesByAttrib(self, attribute): """Returns the list of values that have a particular attribute.""" if attribute not in self._options_cls.ValidOptions(): raise ValueError("'%s': Not a valid attribute." % attribute) result = [] for value in self.values: if attribute in value.OptionNames(): result.append(value.name) return result
python
def GetValuesByAttrib(self, attribute): if attribute not in self._options_cls.ValidOptions(): raise ValueError("'%s': Not a valid attribute." % attribute) result = [] for value in self.values: if attribute in value.OptionNames(): result.append(value.name) return result
[ "def", "GetValuesByAttrib", "(", "self", ",", "attribute", ")", ":", "if", "attribute", "not", "in", "self", ".", "_options_cls", ".", "ValidOptions", "(", ")", ":", "raise", "ValueError", "(", "\"'%s': Not a valid attribute.\"", "%", "attribute", ")", "result",...
Returns the list of values that have a particular attribute.
[ "Returns", "the", "list", "of", "values", "that", "have", "a", "particular", "attribute", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L1030-L1041
243,727
google/textfsm
textfsm/terminal.py
_AnsiCmd
def _AnsiCmd(command_list): """Takes a list of SGR values and formats them as an ANSI escape sequence. Args: command_list: List of strings, each string represents an SGR value. e.g. 'fg_blue', 'bg_yellow' Returns: The ANSI escape sequence. Raises: ValueError: if a member of command_list does not map to a valid SGR value. """ if not isinstance(command_list, list): raise ValueError('Invalid list: %s' % command_list) # Checks that entries are valid SGR names. # No checking is done for sequences that are correct but 'nonsensical'. for sgr in command_list: if sgr.lower() not in SGR: raise ValueError('Invalid or unsupported SGR name: %s' % sgr) # Convert to numerical strings. command_str = [str(SGR[x.lower()]) for x in command_list] # Wrap values in Ansi escape sequence (CSI prefix & SGR suffix). return '\033[%sm' % (';'.join(command_str))
python
def _AnsiCmd(command_list): if not isinstance(command_list, list): raise ValueError('Invalid list: %s' % command_list) # Checks that entries are valid SGR names. # No checking is done for sequences that are correct but 'nonsensical'. for sgr in command_list: if sgr.lower() not in SGR: raise ValueError('Invalid or unsupported SGR name: %s' % sgr) # Convert to numerical strings. command_str = [str(SGR[x.lower()]) for x in command_list] # Wrap values in Ansi escape sequence (CSI prefix & SGR suffix). return '\033[%sm' % (';'.join(command_str))
[ "def", "_AnsiCmd", "(", "command_list", ")", ":", "if", "not", "isinstance", "(", "command_list", ",", "list", ")", ":", "raise", "ValueError", "(", "'Invalid list: %s'", "%", "command_list", ")", "# Checks that entries are valid SGR names.", "# No checking is done for ...
Takes a list of SGR values and formats them as an ANSI escape sequence. Args: command_list: List of strings, each string represents an SGR value. e.g. 'fg_blue', 'bg_yellow' Returns: The ANSI escape sequence. Raises: ValueError: if a member of command_list does not map to a valid SGR value.
[ "Takes", "a", "list", "of", "SGR", "values", "and", "formats", "them", "as", "an", "ANSI", "escape", "sequence", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L115-L138
243,728
google/textfsm
textfsm/terminal.py
TerminalSize
def TerminalSize(): """Returns terminal length and width as a tuple.""" try: with open(os.ctermid(), 'r') as tty_instance: length_width = struct.unpack( 'hh', fcntl.ioctl(tty_instance.fileno(), termios.TIOCGWINSZ, '1234')) except (IOError, OSError): try: length_width = (int(os.environ['LINES']), int(os.environ['COLUMNS'])) except (ValueError, KeyError): length_width = (24, 80) return length_width
python
def TerminalSize(): try: with open(os.ctermid(), 'r') as tty_instance: length_width = struct.unpack( 'hh', fcntl.ioctl(tty_instance.fileno(), termios.TIOCGWINSZ, '1234')) except (IOError, OSError): try: length_width = (int(os.environ['LINES']), int(os.environ['COLUMNS'])) except (ValueError, KeyError): length_width = (24, 80) return length_width
[ "def", "TerminalSize", "(", ")", ":", "try", ":", "with", "open", "(", "os", ".", "ctermid", "(", ")", ",", "'r'", ")", "as", "tty_instance", ":", "length_width", "=", "struct", ".", "unpack", "(", "'hh'", ",", "fcntl", ".", "ioctl", "(", "tty_instan...
Returns terminal length and width as a tuple.
[ "Returns", "terminal", "length", "and", "width", "as", "a", "tuple", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L170-L182
243,729
google/textfsm
textfsm/terminal.py
main
def main(argv=None): """Routine to page text or determine window size via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'dhs', ['nodelay', 'help', 'size']) except getopt.error as msg: raise Usage(msg) # Print usage and return, regardless of presence of other args. for opt, _ in opts: if opt in ('-h', '--help'): print(__doc__) print(help_msg) return 0 isdelay = False for opt, _ in opts: # Prints the size of the terminal and returns. # Mutually exclusive to the paging of text and overrides that behaviour. if opt in ('-s', '--size'): print('Length: %d, Width: %d' % TerminalSize()) return 0 elif opt in ('-d', '--delay'): isdelay = True else: raise Usage('Invalid arguments.') # Page text supplied in either specified file or stdin. if len(args) == 1: with open(args[0]) as f: fd = f.read() else: fd = sys.stdin.read() Pager(fd, delay=isdelay).Page()
python
def main(argv=None): if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'dhs', ['nodelay', 'help', 'size']) except getopt.error as msg: raise Usage(msg) # Print usage and return, regardless of presence of other args. for opt, _ in opts: if opt in ('-h', '--help'): print(__doc__) print(help_msg) return 0 isdelay = False for opt, _ in opts: # Prints the size of the terminal and returns. # Mutually exclusive to the paging of text and overrides that behaviour. if opt in ('-s', '--size'): print('Length: %d, Width: %d' % TerminalSize()) return 0 elif opt in ('-d', '--delay'): isdelay = True else: raise Usage('Invalid arguments.') # Page text supplied in either specified file or stdin. if len(args) == 1: with open(args[0]) as f: fd = f.read() else: fd = sys.stdin.read() Pager(fd, delay=isdelay).Page()
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "argv", "[", "1", ":", "]", ",", "'dhs'", ",", "[", "'nod...
Routine to page text or determine window size via command line.
[ "Routine", "to", "page", "text", "or", "determine", "window", "size", "via", "command", "line", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L447-L484
243,730
google/textfsm
textfsm/terminal.py
Pager.Reset
def Reset(self): """Reset the pager to the top of the text.""" self._displayed = 0 self._currentpagelines = 0 self._lastscroll = 1 self._lines_to_show = self._cli_lines
python
def Reset(self): self._displayed = 0 self._currentpagelines = 0 self._lastscroll = 1 self._lines_to_show = self._cli_lines
[ "def", "Reset", "(", "self", ")", ":", "self", ".", "_displayed", "=", "0", "self", ".", "_currentpagelines", "=", "0", "self", ".", "_lastscroll", "=", "1", "self", ".", "_lines_to_show", "=", "self", ".", "_cli_lines" ]
Reset the pager to the top of the text.
[ "Reset", "the", "pager", "to", "the", "top", "of", "the", "text", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L302-L307
243,731
google/textfsm
textfsm/terminal.py
Pager.SetLines
def SetLines(self, lines): """Set number of screen lines. Args: lines: An int, number of lines. If None, use terminal dimensions. Raises: ValueError, TypeError: Not a valid integer representation. """ (self._cli_lines, self._cli_cols) = TerminalSize() if lines: self._cli_lines = int(lines)
python
def SetLines(self, lines): (self._cli_lines, self._cli_cols) = TerminalSize() if lines: self._cli_lines = int(lines)
[ "def", "SetLines", "(", "self", ",", "lines", ")", ":", "(", "self", ".", "_cli_lines", ",", "self", ".", "_cli_cols", ")", "=", "TerminalSize", "(", ")", "if", "lines", ":", "self", ".", "_cli_lines", "=", "int", "(", "lines", ")" ]
Set number of screen lines. Args: lines: An int, number of lines. If None, use terminal dimensions. Raises: ValueError, TypeError: Not a valid integer representation.
[ "Set", "number", "of", "screen", "lines", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L309-L322
243,732
google/textfsm
textfsm/terminal.py
Pager.Page
def Page(self, text=None, show_percent=None): """Page text. Continues to page through any text supplied in the constructor. Also, any text supplied to this method will be appended to the total text to be displayed. The method returns when all available text has been displayed to the user, or the user quits the pager. Args: text: A string, extra text to be paged. show_percent: A boolean, if True, indicate how much is displayed so far. If None, this behaviour is 'text is None'. Returns: A boolean. If True, more data can be displayed to the user. False implies that the user has quit the pager. """ if text is not None: self._text += text if show_percent is None: show_percent = text is None self._show_percent = show_percent text = LineWrap(self._text).splitlines() while True: # Get a list of new lines to display. self._newlines = text[self._displayed:self._displayed+self._lines_to_show] for line in self._newlines: sys.stdout.write(line + '\n') if self._delay and self._lastscroll > 0: time.sleep(0.005) self._displayed += len(self._newlines) self._currentpagelines += len(self._newlines) if self._currentpagelines >= self._lines_to_show: self._currentpagelines = 0 wish = self._AskUser() if wish == 'q': # Quit pager. return False elif wish == 'g': # Display till the end. self._Scroll(len(text) - self._displayed + 1) elif wish == '\r': # Enter, down a line. self._Scroll(1) elif wish == '\033[B': # Down arrow, down a line. self._Scroll(1) elif wish == '\033[A': # Up arrow, up a line. self._Scroll(-1) elif wish == 'b': # Up a page. self._Scroll(0 - self._cli_lines) else: # Next page. self._Scroll() if self._displayed >= len(text): break return True
python
def Page(self, text=None, show_percent=None): if text is not None: self._text += text if show_percent is None: show_percent = text is None self._show_percent = show_percent text = LineWrap(self._text).splitlines() while True: # Get a list of new lines to display. self._newlines = text[self._displayed:self._displayed+self._lines_to_show] for line in self._newlines: sys.stdout.write(line + '\n') if self._delay and self._lastscroll > 0: time.sleep(0.005) self._displayed += len(self._newlines) self._currentpagelines += len(self._newlines) if self._currentpagelines >= self._lines_to_show: self._currentpagelines = 0 wish = self._AskUser() if wish == 'q': # Quit pager. return False elif wish == 'g': # Display till the end. self._Scroll(len(text) - self._displayed + 1) elif wish == '\r': # Enter, down a line. self._Scroll(1) elif wish == '\033[B': # Down arrow, down a line. self._Scroll(1) elif wish == '\033[A': # Up arrow, up a line. self._Scroll(-1) elif wish == 'b': # Up a page. self._Scroll(0 - self._cli_lines) else: # Next page. self._Scroll() if self._displayed >= len(text): break return True
[ "def", "Page", "(", "self", ",", "text", "=", "None", ",", "show_percent", "=", "None", ")", ":", "if", "text", "is", "not", "None", ":", "self", ".", "_text", "+=", "text", "if", "show_percent", "is", "None", ":", "show_percent", "=", "text", "is", ...
Page text. Continues to page through any text supplied in the constructor. Also, any text supplied to this method will be appended to the total text to be displayed. The method returns when all available text has been displayed to the user, or the user quits the pager. Args: text: A string, extra text to be paged. show_percent: A boolean, if True, indicate how much is displayed so far. If None, this behaviour is 'text is None'. Returns: A boolean. If True, more data can be displayed to the user. False implies that the user has quit the pager.
[ "Page", "text", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L329-L383
243,733
google/textfsm
textfsm/terminal.py
Pager._Scroll
def _Scroll(self, lines=None): """Set attributes to scroll the buffer correctly. Args: lines: An int, number of lines to scroll. If None, scrolls by the terminal length. """ if lines is None: lines = self._cli_lines if lines < 0: self._displayed -= self._cli_lines self._displayed += lines if self._displayed < 0: self._displayed = 0 self._lines_to_show = self._cli_lines else: self._lines_to_show = lines self._lastscroll = lines
python
def _Scroll(self, lines=None): if lines is None: lines = self._cli_lines if lines < 0: self._displayed -= self._cli_lines self._displayed += lines if self._displayed < 0: self._displayed = 0 self._lines_to_show = self._cli_lines else: self._lines_to_show = lines self._lastscroll = lines
[ "def", "_Scroll", "(", "self", ",", "lines", "=", "None", ")", ":", "if", "lines", "is", "None", ":", "lines", "=", "self", ".", "_cli_lines", "if", "lines", "<", "0", ":", "self", ".", "_displayed", "-=", "self", ".", "_cli_lines", "self", ".", "_...
Set attributes to scroll the buffer correctly. Args: lines: An int, number of lines to scroll. If None, scrolls by the terminal length.
[ "Set", "attributes", "to", "scroll", "the", "buffer", "correctly", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L385-L404
243,734
google/textfsm
textfsm/terminal.py
Pager._AskUser
def _AskUser(self): """Prompt the user for the next action. Returns: A string, the character entered by the user. """ if self._show_percent: progress = int(self._displayed*100 / (len(self._text.splitlines()))) progress_text = ' (%d%%)' % progress else: progress_text = '' question = AnsiText( 'Enter: next line, Space: next page, ' 'b: prev page, q: quit.%s' % progress_text, ['green']) sys.stdout.write(question) sys.stdout.flush() ch = self._GetCh() sys.stdout.write('\r%s\r' % (' '*len(question))) sys.stdout.flush() return ch
python
def _AskUser(self): if self._show_percent: progress = int(self._displayed*100 / (len(self._text.splitlines()))) progress_text = ' (%d%%)' % progress else: progress_text = '' question = AnsiText( 'Enter: next line, Space: next page, ' 'b: prev page, q: quit.%s' % progress_text, ['green']) sys.stdout.write(question) sys.stdout.flush() ch = self._GetCh() sys.stdout.write('\r%s\r' % (' '*len(question))) sys.stdout.flush() return ch
[ "def", "_AskUser", "(", "self", ")", ":", "if", "self", ".", "_show_percent", ":", "progress", "=", "int", "(", "self", ".", "_displayed", "*", "100", "/", "(", "len", "(", "self", ".", "_text", ".", "splitlines", "(", ")", ")", ")", ")", "progress...
Prompt the user for the next action. Returns: A string, the character entered by the user.
[ "Prompt", "the", "user", "for", "the", "next", "action", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L406-L426
243,735
google/textfsm
textfsm/terminal.py
Pager._GetCh
def _GetCh(self): """Read a single character from the user. Returns: A string, the character read. """ fd = self._tty.fileno() old = termios.tcgetattr(fd) try: tty.setraw(fd) ch = self._tty.read(1) # Also support arrow key shortcuts (escape + 2 chars) if ord(ch) == 27: ch += self._tty.read(2) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) return ch
python
def _GetCh(self): fd = self._tty.fileno() old = termios.tcgetattr(fd) try: tty.setraw(fd) ch = self._tty.read(1) # Also support arrow key shortcuts (escape + 2 chars) if ord(ch) == 27: ch += self._tty.read(2) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) return ch
[ "def", "_GetCh", "(", "self", ")", ":", "fd", "=", "self", ".", "_tty", ".", "fileno", "(", ")", "old", "=", "termios", ".", "tcgetattr", "(", "fd", ")", "try", ":", "tty", ".", "setraw", "(", "fd", ")", "ch", "=", "self", ".", "_tty", ".", "...
Read a single character from the user. Returns: A string, the character read.
[ "Read", "a", "single", "character", "from", "the", "user", "." ]
63a2aaece33e07947aa80963dca99b893964633b
https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/terminal.py#L428-L444
243,736
skyfielders/python-skyfield
skyfield/relativity.py
add_deflection
def add_deflection(position, observer, ephemeris, t, include_earth_deflection, count=3): """Update `position` for how solar system masses will deflect its light. Given the ICRS `position` [x,y,z] of an object (au) that is being viewed from the `observer` also expressed as [x,y,z], and given an ephemeris that can be used to determine solar system body positions, and given the time `t` and Boolean `apply_earth` indicating whether to worry about the effect of Earth's mass, and a `count` of how many major solar system bodies to worry about, this function updates `position` in-place to show how the masses in the solar system will deflect its image. """ # Compute light-time to observed object. tlt = length_of(position) / C_AUDAY # Cycle through gravitating bodies. jd_tdb = t.tdb ts = t.ts for name in deflectors[:count]: try: deflector = ephemeris[name] except KeyError: deflector = ephemeris[name + ' barycenter'] # Get position of gravitating body wrt ss barycenter at time 't_tdb'. bposition = deflector.at(ts.tdb(jd=jd_tdb)).position.au # TODO # Get position of gravitating body wrt observer at time 'jd_tdb'. gpv = bposition - observer # Compute light-time from point on incoming light ray that is closest # to gravitating body. dlt = light_time_difference(position, gpv) # Get position of gravitating body wrt ss barycenter at time when # incoming photons were closest to it. tclose = jd_tdb # if dlt > 0.0: # tclose = jd - dlt tclose = where(dlt > 0.0, jd_tdb - dlt, tclose) tclose = where(tlt < dlt, jd_tdb - tlt, tclose) # if tlt < dlt: # tclose = jd - tlt bposition = deflector.at(ts.tdb(jd=tclose)).position.au # TODO rmass = rmasses[name] _add_deflection(position, observer, bposition, rmass) # If observer is not at geocenter, add in deflection due to Earth. if include_earth_deflection.any(): deflector = ephemeris['earth'] bposition = deflector.at(ts.tdb(jd=tclose)).position.au # TODO rmass = rmasses['earth'] # TODO: Make the following code less messy, maybe by having # _add_deflection() return a new vector instead of modifying the # old one in-place. deflected_position = position.copy() _add_deflection(deflected_position, observer, bposition, rmass) if include_earth_deflection.shape: position[:,include_earth_deflection] = ( deflected_position[:,include_earth_deflection]) else: position[:] = deflected_position[:]
python
def add_deflection(position, observer, ephemeris, t, include_earth_deflection, count=3): # Compute light-time to observed object. tlt = length_of(position) / C_AUDAY # Cycle through gravitating bodies. jd_tdb = t.tdb ts = t.ts for name in deflectors[:count]: try: deflector = ephemeris[name] except KeyError: deflector = ephemeris[name + ' barycenter'] # Get position of gravitating body wrt ss barycenter at time 't_tdb'. bposition = deflector.at(ts.tdb(jd=jd_tdb)).position.au # TODO # Get position of gravitating body wrt observer at time 'jd_tdb'. gpv = bposition - observer # Compute light-time from point on incoming light ray that is closest # to gravitating body. dlt = light_time_difference(position, gpv) # Get position of gravitating body wrt ss barycenter at time when # incoming photons were closest to it. tclose = jd_tdb # if dlt > 0.0: # tclose = jd - dlt tclose = where(dlt > 0.0, jd_tdb - dlt, tclose) tclose = where(tlt < dlt, jd_tdb - tlt, tclose) # if tlt < dlt: # tclose = jd - tlt bposition = deflector.at(ts.tdb(jd=tclose)).position.au # TODO rmass = rmasses[name] _add_deflection(position, observer, bposition, rmass) # If observer is not at geocenter, add in deflection due to Earth. if include_earth_deflection.any(): deflector = ephemeris['earth'] bposition = deflector.at(ts.tdb(jd=tclose)).position.au # TODO rmass = rmasses['earth'] # TODO: Make the following code less messy, maybe by having # _add_deflection() return a new vector instead of modifying the # old one in-place. deflected_position = position.copy() _add_deflection(deflected_position, observer, bposition, rmass) if include_earth_deflection.shape: position[:,include_earth_deflection] = ( deflected_position[:,include_earth_deflection]) else: position[:] = deflected_position[:]
[ "def", "add_deflection", "(", "position", ",", "observer", ",", "ephemeris", ",", "t", ",", "include_earth_deflection", ",", "count", "=", "3", ")", ":", "# Compute light-time to observed object.", "tlt", "=", "length_of", "(", "position", ")", "/", "C_AUDAY", "...
Update `position` for how solar system masses will deflect its light. Given the ICRS `position` [x,y,z] of an object (au) that is being viewed from the `observer` also expressed as [x,y,z], and given an ephemeris that can be used to determine solar system body positions, and given the time `t` and Boolean `apply_earth` indicating whether to worry about the effect of Earth's mass, and a `count` of how many major solar system bodies to worry about, this function updates `position` in-place to show how the masses in the solar system will deflect its image.
[ "Update", "position", "for", "how", "solar", "system", "masses", "will", "deflect", "its", "light", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/relativity.py#L23-L97
243,737
skyfielders/python-skyfield
skyfield/relativity.py
_add_deflection
def _add_deflection(position, observer, deflector, rmass): """Correct a position vector for how one particular mass deflects light. Given the ICRS `position` [x,y,z] of an object (AU) together with the positions of an `observer` and a `deflector` of reciprocal mass `rmass`, this function updates `position` in-place to show how much the presence of the deflector will deflect the image of the object. """ # Construct vector 'pq' from gravitating body to observed object and # construct vector 'pe' from gravitating body to observer. pq = observer + position - deflector pe = observer - deflector # Compute vector magnitudes and unit vectors. pmag = length_of(position) qmag = length_of(pq) emag = length_of(pe) phat = position / where(pmag, pmag, 1.0) # where() avoids divide-by-zero qhat = pq / where(qmag, qmag, 1.0) ehat = pe / where(emag, emag, 1.0) # Compute dot products of vectors. pdotq = dots(phat, qhat) qdote = dots(qhat, ehat) edotp = dots(ehat, phat) # If gravitating body is observed object, or is on a straight line # toward or away from observed object to within 1 arcsec, deflection # is set to zero set 'pos2' equal to 'pos1'. make_no_correction = abs(edotp) > 0.99999999999 # Compute scalar factors. fac1 = 2.0 * GS / (C * C * emag * AU_M * rmass) fac2 = 1.0 + qdote # Correct position vector. position += where(make_no_correction, 0.0, fac1 * (pdotq * ehat - edotp * qhat) / fac2 * pmag)
python
def _add_deflection(position, observer, deflector, rmass): # Construct vector 'pq' from gravitating body to observed object and # construct vector 'pe' from gravitating body to observer. pq = observer + position - deflector pe = observer - deflector # Compute vector magnitudes and unit vectors. pmag = length_of(position) qmag = length_of(pq) emag = length_of(pe) phat = position / where(pmag, pmag, 1.0) # where() avoids divide-by-zero qhat = pq / where(qmag, qmag, 1.0) ehat = pe / where(emag, emag, 1.0) # Compute dot products of vectors. pdotq = dots(phat, qhat) qdote = dots(qhat, ehat) edotp = dots(ehat, phat) # If gravitating body is observed object, or is on a straight line # toward or away from observed object to within 1 arcsec, deflection # is set to zero set 'pos2' equal to 'pos1'. make_no_correction = abs(edotp) > 0.99999999999 # Compute scalar factors. fac1 = 2.0 * GS / (C * C * emag * AU_M * rmass) fac2 = 1.0 + qdote # Correct position vector. position += where(make_no_correction, 0.0, fac1 * (pdotq * ehat - edotp * qhat) / fac2 * pmag)
[ "def", "_add_deflection", "(", "position", ",", "observer", ",", "deflector", ",", "rmass", ")", ":", "# Construct vector 'pq' from gravitating body to observed object and", "# construct vector 'pe' from gravitating body to observer.", "pq", "=", "observer", "+", "position", "-...
Correct a position vector for how one particular mass deflects light. Given the ICRS `position` [x,y,z] of an object (AU) together with the positions of an `observer` and a `deflector` of reciprocal mass `rmass`, this function updates `position` in-place to show how much the presence of the deflector will deflect the image of the object.
[ "Correct", "a", "position", "vector", "for", "how", "one", "particular", "mass", "deflects", "light", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/relativity.py#L121-L166
243,738
skyfielders/python-skyfield
skyfield/relativity.py
add_aberration
def add_aberration(position, velocity, light_time): """Correct a relative position vector for aberration of light. Given the relative `position` [x,y,z] of an object (AU) from a particular observer, the `velocity` [dx,dy,dz] at which the observer is traveling (AU/day), and the light propagation delay `light_time` to the object (days), this function updates `position` in-place to give the object's apparent position due to the aberration of light. """ p1mag = light_time * C_AUDAY vemag = length_of(velocity) beta = vemag / C_AUDAY dot = dots(position, velocity) cosd = dot / (p1mag * vemag) gammai = sqrt(1.0 - beta * beta) p = beta * cosd q = (1.0 + p / (1.0 + gammai)) * light_time r = 1.0 + p position *= gammai position += q * velocity position /= r
python
def add_aberration(position, velocity, light_time): p1mag = light_time * C_AUDAY vemag = length_of(velocity) beta = vemag / C_AUDAY dot = dots(position, velocity) cosd = dot / (p1mag * vemag) gammai = sqrt(1.0 - beta * beta) p = beta * cosd q = (1.0 + p / (1.0 + gammai)) * light_time r = 1.0 + p position *= gammai position += q * velocity position /= r
[ "def", "add_aberration", "(", "position", ",", "velocity", ",", "light_time", ")", ":", "p1mag", "=", "light_time", "*", "C_AUDAY", "vemag", "=", "length_of", "(", "velocity", ")", "beta", "=", "vemag", "/", "C_AUDAY", "dot", "=", "dots", "(", "position", ...
Correct a relative position vector for aberration of light. Given the relative `position` [x,y,z] of an object (AU) from a particular observer, the `velocity` [dx,dy,dz] at which the observer is traveling (AU/day), and the light propagation delay `light_time` to the object (days), this function updates `position` in-place to give the object's apparent position due to the aberration of light.
[ "Correct", "a", "relative", "position", "vector", "for", "aberration", "of", "light", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/relativity.py#L170-L193
243,739
skyfielders/python-skyfield
skyfield/jpllib.py
_center
def _center(code, segment_dict): """Starting with `code`, follow segments from target to center.""" while code in segment_dict: segment = segment_dict[code] yield segment code = segment.center
python
def _center(code, segment_dict): while code in segment_dict: segment = segment_dict[code] yield segment code = segment.center
[ "def", "_center", "(", "code", ",", "segment_dict", ")", ":", "while", "code", "in", "segment_dict", ":", "segment", "=", "segment_dict", "[", "code", "]", "yield", "segment", "code", "=", "segment", ".", "center" ]
Starting with `code`, follow segments from target to center.
[ "Starting", "with", "code", "follow", "segments", "from", "target", "to", "center", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/jpllib.py#L217-L222
243,740
skyfielders/python-skyfield
skyfield/jpllib.py
SpiceKernel.names
def names(self): """Return all target names that are valid with this kernel. >>> pprint(planets.names()) {0: ['SOLAR_SYSTEM_BARYCENTER', 'SSB', 'SOLAR SYSTEM BARYCENTER'], 1: ['MERCURY_BARYCENTER', 'MERCURY BARYCENTER'], 2: ['VENUS_BARYCENTER', 'VENUS BARYCENTER'], 3: ['EARTH_BARYCENTER', 'EMB', ... The result is a dictionary with target code keys and name lists as values. The last name in each list is the one that Skyfield uses when printing information about a body. """ d = defaultdict(list) for code, name in target_name_pairs: if code in self.codes: d[code].append(name) return dict(d)
python
def names(self): d = defaultdict(list) for code, name in target_name_pairs: if code in self.codes: d[code].append(name) return dict(d)
[ "def", "names", "(", "self", ")", ":", "d", "=", "defaultdict", "(", "list", ")", "for", "code", ",", "name", "in", "target_name_pairs", ":", "if", "code", "in", "self", ".", "codes", ":", "d", "[", "code", "]", ".", "append", "(", "name", ")", "...
Return all target names that are valid with this kernel. >>> pprint(planets.names()) {0: ['SOLAR_SYSTEM_BARYCENTER', 'SSB', 'SOLAR SYSTEM BARYCENTER'], 1: ['MERCURY_BARYCENTER', 'MERCURY BARYCENTER'], 2: ['VENUS_BARYCENTER', 'VENUS BARYCENTER'], 3: ['EARTH_BARYCENTER', 'EMB', ... The result is a dictionary with target code keys and name lists as values. The last name in each list is the one that Skyfield uses when printing information about a body.
[ "Return", "all", "target", "names", "that", "are", "valid", "with", "this", "kernel", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/jpllib.py#L106-L126
243,741
skyfielders/python-skyfield
skyfield/jpllib.py
SpiceKernel.decode
def decode(self, name): """Translate a target name into its integer code. >>> planets.decode('Venus') 299 Raises ``ValueError`` if you supply an unknown name, or ``KeyError`` if the target is missing from this kernel. You can supply an integer code if you already have one and just want to check whether it is present in this kernel. """ if isinstance(name, int): code = name else: name = name.upper() code = _targets.get(name) if code is None: raise ValueError('unknown SPICE target {0!r}'.format(name)) if code not in self.codes: targets = ', '.join(_format_code_and_name(c) for c in self.codes) raise KeyError('kernel {0!r} is missing {1!r} -' ' the targets it supports are: {2}' .format(self.filename, name, targets)) return code
python
def decode(self, name): if isinstance(name, int): code = name else: name = name.upper() code = _targets.get(name) if code is None: raise ValueError('unknown SPICE target {0!r}'.format(name)) if code not in self.codes: targets = ', '.join(_format_code_and_name(c) for c in self.codes) raise KeyError('kernel {0!r} is missing {1!r} -' ' the targets it supports are: {2}' .format(self.filename, name, targets)) return code
[ "def", "decode", "(", "self", ",", "name", ")", ":", "if", "isinstance", "(", "name", ",", "int", ")", ":", "code", "=", "name", "else", ":", "name", "=", "name", ".", "upper", "(", ")", "code", "=", "_targets", ".", "get", "(", "name", ")", "i...
Translate a target name into its integer code. >>> planets.decode('Venus') 299 Raises ``ValueError`` if you supply an unknown name, or ``KeyError`` if the target is missing from this kernel. You can supply an integer code if you already have one and just want to check whether it is present in this kernel.
[ "Translate", "a", "target", "name", "into", "its", "integer", "code", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/jpllib.py#L128-L152
243,742
skyfielders/python-skyfield
skyfield/iokit.py
_search
def _search(mapping, filename): """Search a Loader data structure for a filename.""" result = mapping.get(filename) if result is not None: return result name, ext = os.path.splitext(filename) result = mapping.get(ext) if result is not None: for pattern, result2 in result: if fnmatch(filename, pattern): return result2 return None
python
def _search(mapping, filename): result = mapping.get(filename) if result is not None: return result name, ext = os.path.splitext(filename) result = mapping.get(ext) if result is not None: for pattern, result2 in result: if fnmatch(filename, pattern): return result2 return None
[ "def", "_search", "(", "mapping", ",", "filename", ")", ":", "result", "=", "mapping", ".", "get", "(", "filename", ")", "if", "result", "is", "not", "None", ":", "return", "result", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", ...
Search a Loader data structure for a filename.
[ "Search", "a", "Loader", "data", "structure", "for", "a", "filename", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L288-L299
243,743
skyfielders/python-skyfield
skyfield/iokit.py
load_file
def load_file(path): """Open a file on your local drive, using its extension to guess its type. This routine only works on ``.bsp`` ephemeris files right now, but will gain support for additional file types in the future. :: from skyfield.api import load_file planets = load_file('~/Downloads/de421.bsp') """ path = os.path.expanduser(path) base, ext = os.path.splitext(path) if ext == '.bsp': return SpiceKernel(path) raise ValueError('unrecognized file extension: {}'.format(path))
python
def load_file(path): path = os.path.expanduser(path) base, ext = os.path.splitext(path) if ext == '.bsp': return SpiceKernel(path) raise ValueError('unrecognized file extension: {}'.format(path))
[ "def", "load_file", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "if", "ext", "==", "'.bsp'", ":", "return", "SpiceKernel"...
Open a file on your local drive, using its extension to guess its type. This routine only works on ``.bsp`` ephemeris files right now, but will gain support for additional file types in the future. :: from skyfield.api import load_file planets = load_file('~/Downloads/de421.bsp')
[ "Open", "a", "file", "on", "your", "local", "drive", "using", "its", "extension", "to", "guess", "its", "type", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L302-L316
243,744
skyfielders/python-skyfield
skyfield/iokit.py
parse_deltat_data
def parse_deltat_data(fileobj): """Parse the United States Naval Observatory ``deltat.data`` file. Each line file gives the date and the value of Delta T:: 2016 2 1 68.1577 This function returns a 2xN array of raw Julian dates and matching Delta T values. """ array = np.loadtxt(fileobj) year, month, day = array[-1,:3].astype(int) expiration_date = date(year + 1, month, day) year, month, day, delta_t = array.T data = np.array((julian_date(year, month, day), delta_t)) return expiration_date, data
python
def parse_deltat_data(fileobj): array = np.loadtxt(fileobj) year, month, day = array[-1,:3].astype(int) expiration_date = date(year + 1, month, day) year, month, day, delta_t = array.T data = np.array((julian_date(year, month, day), delta_t)) return expiration_date, data
[ "def", "parse_deltat_data", "(", "fileobj", ")", ":", "array", "=", "np", ".", "loadtxt", "(", "fileobj", ")", "year", ",", "month", ",", "day", "=", "array", "[", "-", "1", ",", ":", "3", "]", ".", "astype", "(", "int", ")", "expiration_date", "="...
Parse the United States Naval Observatory ``deltat.data`` file. Each line file gives the date and the value of Delta T:: 2016 2 1 68.1577 This function returns a 2xN array of raw Julian dates and matching Delta T values.
[ "Parse", "the", "United", "States", "Naval", "Observatory", "deltat", ".", "data", "file", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L319-L335
243,745
skyfielders/python-skyfield
skyfield/iokit.py
parse_deltat_preds
def parse_deltat_preds(fileobj): """Parse the United States Naval Observatory ``deltat.preds`` file. The old format supplies a floating point year, the value of Delta T, and one or two other fields:: 2015.75 67.97 0.210 0.02 The new format adds a modified Julian day as the first field: 58484.000 2019.00 69.34 -0.152 0.117 This function returns a 2xN array of raw Julian dates and matching Delta T values. """ lines = iter(fileobj) header = next(lines) if header.startswith(b'YEAR'): # Format in use until 2019 February next(lines) # discard blank line year_float, delta_t = np.loadtxt(lines, usecols=[0, 1]).T else: # Format in use since 2019 February year_float, delta_t = np.loadtxt(lines, usecols=[1, 2]).T year = year_float.astype(int) month = 1 + (year_float * 12.0).astype(int) % 12 expiration_date = date(year[0] + 2, month[0], 1) data = np.array((julian_date(year, month, 1), delta_t)) return expiration_date, data
python
def parse_deltat_preds(fileobj): lines = iter(fileobj) header = next(lines) if header.startswith(b'YEAR'): # Format in use until 2019 February next(lines) # discard blank line year_float, delta_t = np.loadtxt(lines, usecols=[0, 1]).T else: # Format in use since 2019 February year_float, delta_t = np.loadtxt(lines, usecols=[1, 2]).T year = year_float.astype(int) month = 1 + (year_float * 12.0).astype(int) % 12 expiration_date = date(year[0] + 2, month[0], 1) data = np.array((julian_date(year, month, 1), delta_t)) return expiration_date, data
[ "def", "parse_deltat_preds", "(", "fileobj", ")", ":", "lines", "=", "iter", "(", "fileobj", ")", "header", "=", "next", "(", "lines", ")", "if", "header", ".", "startswith", "(", "b'YEAR'", ")", ":", "# Format in use until 2019 February", "next", "(", "line...
Parse the United States Naval Observatory ``deltat.preds`` file. The old format supplies a floating point year, the value of Delta T, and one or two other fields:: 2015.75 67.97 0.210 0.02 The new format adds a modified Julian day as the first field: 58484.000 2019.00 69.34 -0.152 0.117 This function returns a 2xN array of raw Julian dates and matching Delta T values.
[ "Parse", "the", "United", "States", "Naval", "Observatory", "deltat", ".", "preds", "file", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L338-L369
243,746
skyfielders/python-skyfield
skyfield/iokit.py
parse_leap_seconds
def parse_leap_seconds(fileobj): """Parse the IERS file ``Leap_Second.dat``. The leap dates array can be searched with:: index = np.searchsorted(leap_dates, jd, 'right') The resulting index allows (TAI - UTC) to be fetched with:: offset = leap_offsets[index] """ lines = iter(fileobj) for line in lines: if line.startswith(b'# File expires on'): break else: raise ValueError('Leap_Second.dat is missing its expiration date') line = line.decode('ascii') with _lock: # won't help if anyone user threads are doing parsing, alas original_locale = locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, 'C') try: dt = datetime.strptime(line, '# File expires on %d %B %Y\n') finally: locale.setlocale(locale.LC_ALL, original_locale) # The file went out of date at the beginning of July 2016, and kept # downloading every time a user ran a Skyfield program. So we now # build in a grace period: grace_period = timedelta(days=30) expiration_date = dt.date() + grace_period mjd, day, month, year, offsets = np.loadtxt(lines).T leap_dates = np.ndarray(len(mjd) + 2) leap_dates[0] = '-inf' leap_dates[1:-1] = mjd + 2400000.5 leap_dates[-1] = 'inf' leap_offsets = np.ndarray(len(mjd) + 2) leap_offsets[0] = leap_offsets[1] = offsets[0] leap_offsets[2:] = offsets return expiration_date, (leap_dates, leap_offsets)
python
def parse_leap_seconds(fileobj): lines = iter(fileobj) for line in lines: if line.startswith(b'# File expires on'): break else: raise ValueError('Leap_Second.dat is missing its expiration date') line = line.decode('ascii') with _lock: # won't help if anyone user threads are doing parsing, alas original_locale = locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, 'C') try: dt = datetime.strptime(line, '# File expires on %d %B %Y\n') finally: locale.setlocale(locale.LC_ALL, original_locale) # The file went out of date at the beginning of July 2016, and kept # downloading every time a user ran a Skyfield program. So we now # build in a grace period: grace_period = timedelta(days=30) expiration_date = dt.date() + grace_period mjd, day, month, year, offsets = np.loadtxt(lines).T leap_dates = np.ndarray(len(mjd) + 2) leap_dates[0] = '-inf' leap_dates[1:-1] = mjd + 2400000.5 leap_dates[-1] = 'inf' leap_offsets = np.ndarray(len(mjd) + 2) leap_offsets[0] = leap_offsets[1] = offsets[0] leap_offsets[2:] = offsets return expiration_date, (leap_dates, leap_offsets)
[ "def", "parse_leap_seconds", "(", "fileobj", ")", ":", "lines", "=", "iter", "(", "fileobj", ")", "for", "line", "in", "lines", ":", "if", "line", ".", "startswith", "(", "b'# File expires on'", ")", ":", "break", "else", ":", "raise", "ValueError", "(", ...
Parse the IERS file ``Leap_Second.dat``. The leap dates array can be searched with:: index = np.searchsorted(leap_dates, jd, 'right') The resulting index allows (TAI - UTC) to be fetched with:: offset = leap_offsets[index]
[ "Parse", "the", "IERS", "file", "Leap_Second", ".", "dat", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L371-L412
243,747
skyfielders/python-skyfield
skyfield/iokit.py
parse_tle
def parse_tle(fileobj): """Parse a file of TLE satellite element sets. Builds an Earth satellite from each pair of adjacent lines in the file that start with "1 " and "2 " and have 69 or more characters each. If the preceding line is exactly 24 characters long, then it is parsed as the satellite's name. For each satellite found, yields a tuple `(names, sat)` giving the name(s) on the preceding line (or `None` if no name was found) and the satellite object itself. An exception is raised if the attempt to parse a pair of candidate lines as TLE elements fails. """ b0 = b1 = b'' for b2 in fileobj: if (b1.startswith(b'1 ') and len(b1) >= 69 and b2.startswith(b'2 ') and len(b2) >= 69): b0 = b0.rstrip(b'\n\r') if len(b0) == 24: # Celestrak name = b0.decode('ascii').rstrip() names = [name] elif b0.startswith(b'0 '): # Spacetrack 3-line format name = b0[2:].decode('ascii').rstrip() names = [name] else: name = None names = () line1 = b1.decode('ascii') line2 = b2.decode('ascii') sat = EarthSatellite(line1, line2, name) if name and ' (' in name: # Given a name like `ISS (ZARYA)` or `HTV-6 (KOUNOTORI # 6)`, also support lookup by the name inside or outside # the parentheses. short_name, secondary_name = name.split(' (') secondary_name = secondary_name.rstrip(')') names.append(short_name) names.append(secondary_name) yield names, sat b0 = b1 b1 = b2
python
def parse_tle(fileobj): b0 = b1 = b'' for b2 in fileobj: if (b1.startswith(b'1 ') and len(b1) >= 69 and b2.startswith(b'2 ') and len(b2) >= 69): b0 = b0.rstrip(b'\n\r') if len(b0) == 24: # Celestrak name = b0.decode('ascii').rstrip() names = [name] elif b0.startswith(b'0 '): # Spacetrack 3-line format name = b0[2:].decode('ascii').rstrip() names = [name] else: name = None names = () line1 = b1.decode('ascii') line2 = b2.decode('ascii') sat = EarthSatellite(line1, line2, name) if name and ' (' in name: # Given a name like `ISS (ZARYA)` or `HTV-6 (KOUNOTORI # 6)`, also support lookup by the name inside or outside # the parentheses. short_name, secondary_name = name.split(' (') secondary_name = secondary_name.rstrip(')') names.append(short_name) names.append(secondary_name) yield names, sat b0 = b1 b1 = b2
[ "def", "parse_tle", "(", "fileobj", ")", ":", "b0", "=", "b1", "=", "b''", "for", "b2", "in", "fileobj", ":", "if", "(", "b1", ".", "startswith", "(", "b'1 '", ")", "and", "len", "(", "b1", ")", ">=", "69", "and", "b2", ".", "startswith", "(", ...
Parse a file of TLE satellite element sets. Builds an Earth satellite from each pair of adjacent lines in the file that start with "1 " and "2 " and have 69 or more characters each. If the preceding line is exactly 24 characters long, then it is parsed as the satellite's name. For each satellite found, yields a tuple `(names, sat)` giving the name(s) on the preceding line (or `None` if no name was found) and the satellite object itself. An exception is raised if the attempt to parse a pair of candidate lines as TLE elements fails.
[ "Parse", "a", "file", "of", "TLE", "satellite", "element", "sets", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L415-L461
243,748
skyfielders/python-skyfield
skyfield/iokit.py
download
def download(url, path, verbose=None, blocksize=128*1024): """Download a file from a URL, possibly displaying a progress bar. Saves the output to the file named by `path`. If the URL cannot be downloaded or the file cannot be written, an IOError is raised. Normally, if the standard error output is a terminal, then a progress bar is displayed to keep the user entertained. Specify `verbose=True` or `verbose=False` to control this behavior. """ tempname = path + '.download' try: connection = urlopen(url) except Exception as e: raise IOError('cannot get {0} because {1}'.format(url, e)) if verbose is None: verbose = sys.stderr.isatty() bar = None if verbose: if _running_IDLE: print('Downloading {0} ...'.format(os.path.basename(path)), file=sys.stderr) else: bar = ProgressBar(path) content_length = int(connection.headers.get('content-length', -1)) # Python open() provides no way to achieve O_CREAT without also # truncating the file, which would ruin the work of another process # that is trying to download the same file at the same time. So: flags = getattr(os, 'O_BINARY', 0) | os.O_CREAT | os.O_RDWR fd = os.open(tempname, flags, 0o666) with os.fdopen(fd, 'wb') as w: try: if lockf is not None: fd = w.fileno() lockf(fd, LOCK_EX) # only one download at a time if os.path.exists(path): # did someone else finish first? if os.path.exists(tempname): os.unlink(tempname) return w.seek(0) length = 0 while True: data = connection.read(blocksize) if not data: break w.write(data) length += len(data) if bar is not None: bar.report(length, content_length) w.flush() if lockf is not None: # On Unix, rename while still protected by the lock. try: os.rename(tempname, path) except Exception as e: raise IOError('error renaming {0} to {1} - {2}'.format( tempname, path, e)) except Exception as e: raise IOError('error getting {0} - {1}'.format(url, e)) finally: if lockf is not None: lockf(fd, LOCK_UN) if lockf is None: # On Windows, rename here because the file needs to be closed first. try: _replace(tempname, path) except Exception as e: raise IOError('error renaming {0} to {1} - {2}'.format( tempname, path, e))
python
def download(url, path, verbose=None, blocksize=128*1024): tempname = path + '.download' try: connection = urlopen(url) except Exception as e: raise IOError('cannot get {0} because {1}'.format(url, e)) if verbose is None: verbose = sys.stderr.isatty() bar = None if verbose: if _running_IDLE: print('Downloading {0} ...'.format(os.path.basename(path)), file=sys.stderr) else: bar = ProgressBar(path) content_length = int(connection.headers.get('content-length', -1)) # Python open() provides no way to achieve O_CREAT without also # truncating the file, which would ruin the work of another process # that is trying to download the same file at the same time. So: flags = getattr(os, 'O_BINARY', 0) | os.O_CREAT | os.O_RDWR fd = os.open(tempname, flags, 0o666) with os.fdopen(fd, 'wb') as w: try: if lockf is not None: fd = w.fileno() lockf(fd, LOCK_EX) # only one download at a time if os.path.exists(path): # did someone else finish first? if os.path.exists(tempname): os.unlink(tempname) return w.seek(0) length = 0 while True: data = connection.read(blocksize) if not data: break w.write(data) length += len(data) if bar is not None: bar.report(length, content_length) w.flush() if lockf is not None: # On Unix, rename while still protected by the lock. try: os.rename(tempname, path) except Exception as e: raise IOError('error renaming {0} to {1} - {2}'.format( tempname, path, e)) except Exception as e: raise IOError('error getting {0} - {1}'.format(url, e)) finally: if lockf is not None: lockf(fd, LOCK_UN) if lockf is None: # On Windows, rename here because the file needs to be closed first. try: _replace(tempname, path) except Exception as e: raise IOError('error renaming {0} to {1} - {2}'.format( tempname, path, e))
[ "def", "download", "(", "url", ",", "path", ",", "verbose", "=", "None", ",", "blocksize", "=", "128", "*", "1024", ")", ":", "tempname", "=", "path", "+", "'.download'", "try", ":", "connection", "=", "urlopen", "(", "url", ")", "except", "Exception",...
Download a file from a URL, possibly displaying a progress bar. Saves the output to the file named by `path`. If the URL cannot be downloaded or the file cannot be written, an IOError is raised. Normally, if the standard error output is a terminal, then a progress bar is displayed to keep the user entertained. Specify `verbose=True` or `verbose=False` to control this behavior.
[ "Download", "a", "file", "from", "a", "URL", "possibly", "displaying", "a", "progress", "bar", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L464-L536
243,749
skyfielders/python-skyfield
skyfield/iokit.py
Loader.tle
def tle(self, url, reload=False, filename=None): """Load and parse a satellite TLE file. Given a URL or a local path, this loads a file of three-line records in the common Celestrak file format, or two-line records like those from space-track.org. For a three-line element set, each first line gives the name of a satellite and the following two lines are the TLE orbital elements. A two-line element set comprises only these last two lines. See the :meth:`~skyfield.iokit.Loader.open()` documentation for the meaning of the ``reload`` and ``filename`` parameters. Returns a dictionary whose keys are satellite names and numbers, and whose values are :class:`~skyfield.sgp4lib.EarthSatellite` objects. If you want to build a list in which each satellite appears only once, simply run ``sats = set(d.values())`` on the returned dictionary. """ d = {} with self.open(url, reload=reload, filename=filename) as f: for names, sat in parse_tle(f): d[sat.model.satnum] = sat for name in names: d[name] = sat return d
python
def tle(self, url, reload=False, filename=None): d = {} with self.open(url, reload=reload, filename=filename) as f: for names, sat in parse_tle(f): d[sat.model.satnum] = sat for name in names: d[name] = sat return d
[ "def", "tle", "(", "self", ",", "url", ",", "reload", "=", "False", ",", "filename", "=", "None", ")", ":", "d", "=", "{", "}", "with", "self", ".", "open", "(", "url", ",", "reload", "=", "reload", ",", "filename", "=", "filename", ")", "as", ...
Load and parse a satellite TLE file. Given a URL or a local path, this loads a file of three-line records in the common Celestrak file format, or two-line records like those from space-track.org. For a three-line element set, each first line gives the name of a satellite and the following two lines are the TLE orbital elements. A two-line element set comprises only these last two lines. See the :meth:`~skyfield.iokit.Loader.open()` documentation for the meaning of the ``reload`` and ``filename`` parameters. Returns a dictionary whose keys are satellite names and numbers, and whose values are :class:`~skyfield.sgp4lib.EarthSatellite` objects. If you want to build a list in which each satellite appears only once, simply run ``sats = set(d.values())`` on the returned dictionary.
[ "Load", "and", "parse", "a", "satellite", "TLE", "file", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L199-L224
243,750
skyfielders/python-skyfield
skyfield/iokit.py
Loader.open
def open(self, url, mode='rb', reload=False, filename=None): """Open a file, downloading it first if it does not yet exist. Unlike when you call a loader directly like ``my_loader()``, this ``my_loader.open()`` method does not attempt to parse or interpret the file; it simply returns an open file object. The ``url`` can be either an external URL, or else the path to a file on the current filesystem. A relative path will be assumed to be relative to the base directory of this loader object. If a URL was provided and the ``reload`` parameter is true, then any existing file will be removed before the download starts. The ``filename`` parameter lets you specify an alternative local filename instead of having the filename extracted from the final component of the URL. """ if '://' not in url: path_that_might_be_relative = url path = os.path.join(self.directory, path_that_might_be_relative) return open(path, mode) if filename is None: filename = urlparse(url).path.split('/')[-1] path = self.path_to(filename) if reload and os.path.exists(path): os.remove(path) if not os.path.exists(path): download(url, path, self.verbose) return open(path, mode)
python
def open(self, url, mode='rb', reload=False, filename=None): if '://' not in url: path_that_might_be_relative = url path = os.path.join(self.directory, path_that_might_be_relative) return open(path, mode) if filename is None: filename = urlparse(url).path.split('/')[-1] path = self.path_to(filename) if reload and os.path.exists(path): os.remove(path) if not os.path.exists(path): download(url, path, self.verbose) return open(path, mode)
[ "def", "open", "(", "self", ",", "url", ",", "mode", "=", "'rb'", ",", "reload", "=", "False", ",", "filename", "=", "None", ")", ":", "if", "'://'", "not", "in", "url", ":", "path_that_might_be_relative", "=", "url", "path", "=", "os", ".", "path", ...
Open a file, downloading it first if it does not yet exist. Unlike when you call a loader directly like ``my_loader()``, this ``my_loader.open()`` method does not attempt to parse or interpret the file; it simply returns an open file object. The ``url`` can be either an external URL, or else the path to a file on the current filesystem. A relative path will be assumed to be relative to the base directory of this loader object. If a URL was provided and the ``reload`` parameter is true, then any existing file will be removed before the download starts. The ``filename`` parameter lets you specify an alternative local filename instead of having the filename extracted from the final component of the URL.
[ "Open", "a", "file", "downloading", "it", "first", "if", "it", "does", "not", "yet", "exist", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L226-L256
243,751
skyfielders/python-skyfield
skyfield/iokit.py
Loader.timescale
def timescale(self, delta_t=None): """Open or download three time scale files, returning a `Timescale`. This method is how most Skyfield users build a `Timescale` object, which is necessary for building specific `Time` objects that name specific moments. This will open or download the three files that Skyfield needs to measure time. UT1 is tabulated by the United States Naval Observatory files ``deltat.data`` and ``deltat.preds``, while UTC is defined by ``Leap_Second.dat`` from the International Earth Rotation Service. """ if delta_t is not None: delta_t_recent = np.array(((-1e99, 1e99), (delta_t, delta_t))) else: data = self('deltat.data') preds = self('deltat.preds') data_end_time = data[0, -1] i = np.searchsorted(preds[0], data_end_time, side='right') delta_t_recent = np.concatenate([data, preds[:,i:]], axis=1) leap_dates, leap_offsets = self('Leap_Second.dat') return Timescale(delta_t_recent, leap_dates, leap_offsets)
python
def timescale(self, delta_t=None): if delta_t is not None: delta_t_recent = np.array(((-1e99, 1e99), (delta_t, delta_t))) else: data = self('deltat.data') preds = self('deltat.preds') data_end_time = data[0, -1] i = np.searchsorted(preds[0], data_end_time, side='right') delta_t_recent = np.concatenate([data, preds[:,i:]], axis=1) leap_dates, leap_offsets = self('Leap_Second.dat') return Timescale(delta_t_recent, leap_dates, leap_offsets)
[ "def", "timescale", "(", "self", ",", "delta_t", "=", "None", ")", ":", "if", "delta_t", "is", "not", "None", ":", "delta_t_recent", "=", "np", ".", "array", "(", "(", "(", "-", "1e99", ",", "1e99", ")", ",", "(", "delta_t", ",", "delta_t", ")", ...
Open or download three time scale files, returning a `Timescale`. This method is how most Skyfield users build a `Timescale` object, which is necessary for building specific `Time` objects that name specific moments. This will open or download the three files that Skyfield needs to measure time. UT1 is tabulated by the United States Naval Observatory files ``deltat.data`` and ``deltat.preds``, while UTC is defined by ``Leap_Second.dat`` from the International Earth Rotation Service.
[ "Open", "or", "download", "three", "time", "scale", "files", "returning", "a", "Timescale", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/iokit.py#L258-L281
243,752
skyfielders/python-skyfield
skyfield/contrib/iosurvey.py
get_summary
def get_summary(url, spk=True): ''' simple function to retrieve the header of a BSP file and return SPK object''' # connect to file at URL bspurl = urllib2.urlopen(url) # retrieve the "tip" of a file at URL bsptip = bspurl.read(10**5) # first 100kB # save data in fake file object (in-memory) bspstr = StringIO(bsptip) # load into DAF object daf = DAF(bspstr) # return either SPK or DAF object if spk: # make a SPK object spk = SPK(daf) # return representation return spk else: # return representation return daf
python
def get_summary(url, spk=True): ''' simple function to retrieve the header of a BSP file and return SPK object''' # connect to file at URL bspurl = urllib2.urlopen(url) # retrieve the "tip" of a file at URL bsptip = bspurl.read(10**5) # first 100kB # save data in fake file object (in-memory) bspstr = StringIO(bsptip) # load into DAF object daf = DAF(bspstr) # return either SPK or DAF object if spk: # make a SPK object spk = SPK(daf) # return representation return spk else: # return representation return daf
[ "def", "get_summary", "(", "url", ",", "spk", "=", "True", ")", ":", "# connect to file at URL", "bspurl", "=", "urllib2", ".", "urlopen", "(", "url", ")", "# retrieve the \"tip\" of a file at URL", "bsptip", "=", "bspurl", ".", "read", "(", "10", "**", "5", ...
simple function to retrieve the header of a BSP file and return SPK object
[ "simple", "function", "to", "retrieve", "the", "header", "of", "a", "BSP", "file", "and", "return", "SPK", "object" ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/contrib/iosurvey.py#L11-L29
243,753
skyfielders/python-skyfield
skyfield/vectorlib.py
_correct_for_light_travel_time
def _correct_for_light_travel_time(observer, target): """Return a light-time corrected astrometric position and velocity. Given an `observer` that is a `Barycentric` position somewhere in the solar system, compute where in the sky they will see the body `target`, by computing the light-time between them and figuring out where `target` was back when the light was leaving it that is now reaching the eyes or instruments of the `observer`. """ t = observer.t ts = t.ts cposition = observer.position.au cvelocity = observer.velocity.au_per_d tposition, tvelocity, gcrs_position, message = target._at(t) distance = length_of(tposition - cposition) light_time0 = 0.0 t_tdb = t.tdb for i in range(10): light_time = distance / C_AUDAY delta = light_time - light_time0 if -1e-12 < min(delta) and max(delta) < 1e-12: break t2 = ts.tdb(jd=t_tdb - light_time) tposition, tvelocity, gcrs_position, message = target._at(t2) distance = length_of(tposition - cposition) light_time0 = light_time else: raise ValueError('light-travel time failed to converge') return tposition - cposition, tvelocity - cvelocity, t, light_time
python
def _correct_for_light_travel_time(observer, target): t = observer.t ts = t.ts cposition = observer.position.au cvelocity = observer.velocity.au_per_d tposition, tvelocity, gcrs_position, message = target._at(t) distance = length_of(tposition - cposition) light_time0 = 0.0 t_tdb = t.tdb for i in range(10): light_time = distance / C_AUDAY delta = light_time - light_time0 if -1e-12 < min(delta) and max(delta) < 1e-12: break t2 = ts.tdb(jd=t_tdb - light_time) tposition, tvelocity, gcrs_position, message = target._at(t2) distance = length_of(tposition - cposition) light_time0 = light_time else: raise ValueError('light-travel time failed to converge') return tposition - cposition, tvelocity - cvelocity, t, light_time
[ "def", "_correct_for_light_travel_time", "(", "observer", ",", "target", ")", ":", "t", "=", "observer", ".", "t", "ts", "=", "t", ".", "ts", "cposition", "=", "observer", ".", "position", ".", "au", "cvelocity", "=", "observer", ".", "velocity", ".", "a...
Return a light-time corrected astrometric position and velocity. Given an `observer` that is a `Barycentric` position somewhere in the solar system, compute where in the sky they will see the body `target`, by computing the light-time between them and figuring out where `target` was back when the light was leaving it that is now reaching the eyes or instruments of the `observer`.
[ "Return", "a", "light", "-", "time", "corrected", "astrometric", "position", "and", "velocity", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/vectorlib.py#L201-L230
243,754
skyfielders/python-skyfield
skyfield/vectorlib.py
VectorFunction.at
def at(self, t): """At time ``t``, compute the target's position relative to the center. If ``t`` is an array of times, then the returned position object will specify as many positions as there were times. The kind of position returned depends on the value of the ``center`` attribute: * Solar System Barycenter: :class:`~skyfield.positionlib.Barycentric` * Center of the Earth: :class:`~skyfield.positionlib.Geocentric` * Difference: :class:`~skyfield.positionlib.Geometric` * Anything else: :class:`~skyfield.positionlib.ICRF` """ if not isinstance(t, Time): raise ValueError('please provide the at() method with a Time' ' instance as its argument, instead of the' ' value {0!r}'.format(t)) observer_data = ObserverData() observer_data.ephemeris = self.ephemeris p, v, observer_data.gcrs_position, message = self._at(t) center = self.center if center == 0: observer_data.bcrs_position = p observer_data.bcrs_velocity = v self._snag_observer_data(observer_data, t) position = build_position(p, v, t, center, self.target, observer_data) position.message = message return position
python
def at(self, t): if not isinstance(t, Time): raise ValueError('please provide the at() method with a Time' ' instance as its argument, instead of the' ' value {0!r}'.format(t)) observer_data = ObserverData() observer_data.ephemeris = self.ephemeris p, v, observer_data.gcrs_position, message = self._at(t) center = self.center if center == 0: observer_data.bcrs_position = p observer_data.bcrs_velocity = v self._snag_observer_data(observer_data, t) position = build_position(p, v, t, center, self.target, observer_data) position.message = message return position
[ "def", "at", "(", "self", ",", "t", ")", ":", "if", "not", "isinstance", "(", "t", ",", "Time", ")", ":", "raise", "ValueError", "(", "'please provide the at() method with a Time'", "' instance as its argument, instead of the'", "' value {0!r}'", ".", "format", "(",...
At time ``t``, compute the target's position relative to the center. If ``t`` is an array of times, then the returned position object will specify as many positions as there were times. The kind of position returned depends on the value of the ``center`` attribute: * Solar System Barycenter: :class:`~skyfield.positionlib.Barycentric` * Center of the Earth: :class:`~skyfield.positionlib.Geocentric` * Difference: :class:`~skyfield.positionlib.Geometric` * Anything else: :class:`~skyfield.positionlib.ICRF`
[ "At", "time", "t", "compute", "the", "target", "s", "position", "relative", "to", "the", "center", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/vectorlib.py#L54-L82
243,755
skyfielders/python-skyfield
skyfield/timelib.py
_to_array
def _to_array(value): """When `value` is a plain Python sequence, return it as a NumPy array.""" if hasattr(value, 'shape'): return value elif hasattr(value, '__len__'): return array(value) else: return float_(value)
python
def _to_array(value): if hasattr(value, 'shape'): return value elif hasattr(value, '__len__'): return array(value) else: return float_(value)
[ "def", "_to_array", "(", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'shape'", ")", ":", "return", "value", "elif", "hasattr", "(", "value", ",", "'__len__'", ")", ":", "return", "array", "(", "value", ")", "else", ":", "return", "float_", ...
When `value` is a plain Python sequence, return it as a NumPy array.
[ "When", "value", "is", "a", "plain", "Python", "sequence", "return", "it", "as", "a", "NumPy", "array", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L40-L47
243,756
skyfielders/python-skyfield
skyfield/timelib.py
julian_day
def julian_day(year, month=1, day=1): """Given a proleptic Gregorian calendar date, return a Julian day int.""" janfeb = month < 3 return (day + 1461 * (year + 4800 - janfeb) // 4 + 367 * (month - 2 + janfeb * 12) // 12 - 3 * ((year + 4900 - janfeb) // 100) // 4 - 32075)
python
def julian_day(year, month=1, day=1): janfeb = month < 3 return (day + 1461 * (year + 4800 - janfeb) // 4 + 367 * (month - 2 + janfeb * 12) // 12 - 3 * ((year + 4900 - janfeb) // 100) // 4 - 32075)
[ "def", "julian_day", "(", "year", ",", "month", "=", "1", ",", "day", "=", "1", ")", ":", "janfeb", "=", "month", "<", "3", "return", "(", "day", "+", "1461", "*", "(", "year", "+", "4800", "-", "janfeb", ")", "//", "4", "+", "367", "*", "(",...
Given a proleptic Gregorian calendar date, return a Julian day int.
[ "Given", "a", "proleptic", "Gregorian", "calendar", "date", "return", "a", "Julian", "day", "int", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L700-L707
243,757
skyfielders/python-skyfield
skyfield/timelib.py
julian_date
def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0): """Given a proleptic Gregorian calendar date, return a Julian date float.""" return julian_day(year, month, day) - 0.5 + ( second + minute * 60.0 + hour * 3600.0) / DAY_S
python
def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0): return julian_day(year, month, day) - 0.5 + ( second + minute * 60.0 + hour * 3600.0) / DAY_S
[ "def", "julian_date", "(", "year", ",", "month", "=", "1", ",", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0.0", ")", ":", "return", "julian_day", "(", "year", ",", "month", ",", "day", ")", "-", "0.5"...
Given a proleptic Gregorian calendar date, return a Julian date float.
[ "Given", "a", "proleptic", "Gregorian", "calendar", "date", "return", "a", "Julian", "date", "float", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L709-L712
243,758
skyfielders/python-skyfield
skyfield/timelib.py
tdb_minus_tt
def tdb_minus_tt(jd_tdb): """Computes how far TDB is in advance of TT, given TDB. Given that the two time scales never diverge by more than 2ms, TT can also be given as the argument to perform the conversion in the other direction. """ t = (jd_tdb - T0) / 36525.0 # USNO Circular 179, eq. 2.6. return (0.001657 * sin ( 628.3076 * t + 6.2401) + 0.000022 * sin ( 575.3385 * t + 4.2970) + 0.000014 * sin (1256.6152 * t + 6.1969) + 0.000005 * sin ( 606.9777 * t + 4.0212) + 0.000005 * sin ( 52.9691 * t + 0.4444) + 0.000002 * sin ( 21.3299 * t + 5.5431) + 0.000010 * t * sin ( 628.3076 * t + 4.2490))
python
def tdb_minus_tt(jd_tdb): t = (jd_tdb - T0) / 36525.0 # USNO Circular 179, eq. 2.6. return (0.001657 * sin ( 628.3076 * t + 6.2401) + 0.000022 * sin ( 575.3385 * t + 4.2970) + 0.000014 * sin (1256.6152 * t + 6.1969) + 0.000005 * sin ( 606.9777 * t + 4.0212) + 0.000005 * sin ( 52.9691 * t + 0.4444) + 0.000002 * sin ( 21.3299 * t + 5.5431) + 0.000010 * t * sin ( 628.3076 * t + 4.2490))
[ "def", "tdb_minus_tt", "(", "jd_tdb", ")", ":", "t", "=", "(", "jd_tdb", "-", "T0", ")", "/", "36525.0", "# USNO Circular 179, eq. 2.6.", "return", "(", "0.001657", "*", "sin", "(", "628.3076", "*", "t", "+", "6.2401", ")", "+", "0.000022", "*", "sin", ...
Computes how far TDB is in advance of TT, given TDB. Given that the two time scales never diverge by more than 2ms, TT can also be given as the argument to perform the conversion in the other direction.
[ "Computes", "how", "far", "TDB", "is", "in", "advance", "of", "TT", "given", "TDB", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L752-L769
243,759
skyfielders/python-skyfield
skyfield/timelib.py
interpolate_delta_t
def interpolate_delta_t(delta_t_table, tt): """Return interpolated Delta T values for the times in `tt`. The 2xN table should provide TT values as element 0 and corresponding Delta T values for element 1. For times outside the range of the table, a long-term formula is used instead. """ tt_array, delta_t_array = delta_t_table delta_t = _to_array(interp(tt, tt_array, delta_t_array, nan, nan)) missing = isnan(delta_t) if missing.any(): # Test if we are dealing with an array and proceed appropriately if missing.shape: tt = tt[missing] delta_t[missing] = delta_t_formula_morrison_and_stephenson_2004(tt) else: delta_t = delta_t_formula_morrison_and_stephenson_2004(tt) return delta_t
python
def interpolate_delta_t(delta_t_table, tt): tt_array, delta_t_array = delta_t_table delta_t = _to_array(interp(tt, tt_array, delta_t_array, nan, nan)) missing = isnan(delta_t) if missing.any(): # Test if we are dealing with an array and proceed appropriately if missing.shape: tt = tt[missing] delta_t[missing] = delta_t_formula_morrison_and_stephenson_2004(tt) else: delta_t = delta_t_formula_morrison_and_stephenson_2004(tt) return delta_t
[ "def", "interpolate_delta_t", "(", "delta_t_table", ",", "tt", ")", ":", "tt_array", ",", "delta_t_array", "=", "delta_t_table", "delta_t", "=", "_to_array", "(", "interp", "(", "tt", ",", "tt_array", ",", "delta_t_array", ",", "nan", ",", "nan", ")", ")", ...
Return interpolated Delta T values for the times in `tt`. The 2xN table should provide TT values as element 0 and corresponding Delta T values for element 1. For times outside the range of the table, a long-term formula is used instead.
[ "Return", "interpolated", "Delta", "T", "values", "for", "the", "times", "in", "tt", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L771-L790
243,760
skyfielders/python-skyfield
skyfield/timelib.py
build_delta_t_table
def build_delta_t_table(delta_t_recent): """Build a table for interpolating Delta T. Given a 2xN array of recent Delta T values, whose element 0 is a sorted array of TT Julian dates and element 1 is Delta T values, this routine returns a more complete table by prepending two built-in data sources that ship with Skyfield as pre-built arrays: * The historical values from Morrison and Stephenson (2004) which the http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html NASA web page presents in an HTML table. * The United States Naval Observatory ``historic_deltat.data`` values for Delta T over the years 1657 through 1984. """ ancient = load_bundled_npy('morrison_stephenson_deltat.npy') historic = load_bundled_npy('historic_deltat.npy') # Prefer USNO over Morrison and Stephenson where they overlap. historic_start_time = historic[0,0] i = searchsorted(ancient[0], historic_start_time) bundled = concatenate([ancient[:,:i], historic], axis=1) # Let recent data replace everything else. recent_start_time = delta_t_recent[0,0] i = searchsorted(bundled[0], recent_start_time) row = ((0,),(0,)) table = concatenate([row, bundled[:,:i], delta_t_recent, row], axis=1) # Create initial and final point to provide continuity with formula. century = 36524.0 start = table[0,1] - century table[:,0] = start, delta_t_formula_morrison_and_stephenson_2004(start) end = table[0,-2] + century table[:,-1] = end, delta_t_formula_morrison_and_stephenson_2004(end) return table
python
def build_delta_t_table(delta_t_recent): ancient = load_bundled_npy('morrison_stephenson_deltat.npy') historic = load_bundled_npy('historic_deltat.npy') # Prefer USNO over Morrison and Stephenson where they overlap. historic_start_time = historic[0,0] i = searchsorted(ancient[0], historic_start_time) bundled = concatenate([ancient[:,:i], historic], axis=1) # Let recent data replace everything else. recent_start_time = delta_t_recent[0,0] i = searchsorted(bundled[0], recent_start_time) row = ((0,),(0,)) table = concatenate([row, bundled[:,:i], delta_t_recent, row], axis=1) # Create initial and final point to provide continuity with formula. century = 36524.0 start = table[0,1] - century table[:,0] = start, delta_t_formula_morrison_and_stephenson_2004(start) end = table[0,-2] + century table[:,-1] = end, delta_t_formula_morrison_and_stephenson_2004(end) return table
[ "def", "build_delta_t_table", "(", "delta_t_recent", ")", ":", "ancient", "=", "load_bundled_npy", "(", "'morrison_stephenson_deltat.npy'", ")", "historic", "=", "load_bundled_npy", "(", "'historic_deltat.npy'", ")", "# Prefer USNO over Morrison and Stephenson where they overlap....
Build a table for interpolating Delta T. Given a 2xN array of recent Delta T values, whose element 0 is a sorted array of TT Julian dates and element 1 is Delta T values, this routine returns a more complete table by prepending two built-in data sources that ship with Skyfield as pre-built arrays: * The historical values from Morrison and Stephenson (2004) which the http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html NASA web page presents in an HTML table. * The United States Naval Observatory ``historic_deltat.data`` values for Delta T over the years 1657 through 1984.
[ "Build", "a", "table", "for", "interpolating", "Delta", "T", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L803-L839
243,761
skyfielders/python-skyfield
skyfield/timelib.py
Timescale.utc
def utc(self, year, month=1, day=1, hour=0, minute=0, second=0.0): """Build a `Time` from a UTC calendar date. You can either specify the date as separate components, or provide a time zone aware Python datetime. The following two calls are equivalent (the ``utc`` time zone object can be imported from the ``skyfield.api`` module, or from ``pytz`` if you have it):: ts.utc(2014, 1, 18, 1, 35, 37.5) ts.utc(datetime(2014, 1, 18, 1, 35, 37, 500000, tzinfo=utc)) Note that only by passing the components separately can you specify a leap second, because a Python datetime will not allow the value 60 in its seconds field. """ if isinstance(year, datetime): dt = year tai = _utc_datetime_to_tai(self.leap_dates, self.leap_offsets, dt) elif isinstance(year, date): d = year tai = _utc_date_to_tai(self.leap_dates, self.leap_offsets, d) elif hasattr(year, '__len__') and isinstance(year[0], datetime): # TODO: clean this up and better document the possibilities. list_of_datetimes = year tai = array([ _utc_datetime_to_tai(self.leap_dates, self.leap_offsets, dt) for dt in list_of_datetimes]) else: tai = _utc_to_tai(self.leap_dates, self.leap_offsets, _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second)) t = Time(self, tai + tt_minus_tai) t.tai = tai return t
python
def utc(self, year, month=1, day=1, hour=0, minute=0, second=0.0): if isinstance(year, datetime): dt = year tai = _utc_datetime_to_tai(self.leap_dates, self.leap_offsets, dt) elif isinstance(year, date): d = year tai = _utc_date_to_tai(self.leap_dates, self.leap_offsets, d) elif hasattr(year, '__len__') and isinstance(year[0], datetime): # TODO: clean this up and better document the possibilities. list_of_datetimes = year tai = array([ _utc_datetime_to_tai(self.leap_dates, self.leap_offsets, dt) for dt in list_of_datetimes]) else: tai = _utc_to_tai(self.leap_dates, self.leap_offsets, _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second)) t = Time(self, tai + tt_minus_tai) t.tai = tai return t
[ "def", "utc", "(", "self", ",", "year", ",", "month", "=", "1", ",", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0.0", ")", ":", "if", "isinstance", "(", "year", ",", "datetime", ")", ":", "dt", "=", ...
Build a `Time` from a UTC calendar date. You can either specify the date as separate components, or provide a time zone aware Python datetime. The following two calls are equivalent (the ``utc`` time zone object can be imported from the ``skyfield.api`` module, or from ``pytz`` if you have it):: ts.utc(2014, 1, 18, 1, 35, 37.5) ts.utc(datetime(2014, 1, 18, 1, 35, 37, 500000, tzinfo=utc)) Note that only by passing the components separately can you specify a leap second, because a Python datetime will not allow the value 60 in its seconds field.
[ "Build", "a", "Time", "from", "a", "UTC", "calendar", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L91-L127
243,762
skyfielders/python-skyfield
skyfield/timelib.py
Timescale.tai
def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a TAI calendar date. Supply the International Atomic Time (TAI) as a proleptic Gregorian calendar date: >>> t = ts.tai(2014, 1, 18, 1, 35, 37.5) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5) """ if jd is not None: tai = jd else: tai = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second), ) return self.tai_jd(tai)
python
def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): if jd is not None: tai = jd else: tai = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second), ) return self.tai_jd(tai)
[ "def", "tai", "(", "self", ",", "year", "=", "None", ",", "month", "=", "1", ",", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0.0", ",", "jd", "=", "None", ")", ":", "if", "jd", "is", "not", "None",...
Build a `Time` from a TAI calendar date. Supply the International Atomic Time (TAI) as a proleptic Gregorian calendar date: >>> t = ts.tai(2014, 1, 18, 1, 35, 37.5) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5)
[ "Build", "a", "Time", "from", "a", "TAI", "calendar", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L129-L150
243,763
skyfielders/python-skyfield
skyfield/timelib.py
Timescale.tai_jd
def tai_jd(self, jd): """Build a `Time` from a TAI Julian date. Supply the International Atomic Time (TAI) as a Julian date: >>> t = ts.tai_jd(2456675.56640625) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5) """ tai = _to_array(jd) t = Time(self, tai + tt_minus_tai) t.tai = tai return t
python
def tai_jd(self, jd): tai = _to_array(jd) t = Time(self, tai + tt_minus_tai) t.tai = tai return t
[ "def", "tai_jd", "(", "self", ",", "jd", ")", ":", "tai", "=", "_to_array", "(", "jd", ")", "t", "=", "Time", "(", "self", ",", "tai", "+", "tt_minus_tai", ")", "t", ".", "tai", "=", "tai", "return", "t" ]
Build a `Time` from a TAI Julian date. Supply the International Atomic Time (TAI) as a Julian date: >>> t = ts.tai_jd(2456675.56640625) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5)
[ "Build", "a", "Time", "from", "a", "TAI", "Julian", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L152-L167
243,764
skyfielders/python-skyfield
skyfield/timelib.py
Timescale.tt
def tt(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a TT calendar date. Supply the Terrestrial Time (TT) as a proleptic Gregorian calendar date: >>> t = ts.tt(2014, 1, 18, 1, 35, 37.5) >>> t.tt 2456675.56640625 >>> t.tt_calendar() (2014, 1, 18, 1, 35, 37.5) """ if jd is not None: tt = jd else: tt = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second), ) tt = _to_array(tt) return Time(self, tt)
python
def tt(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): if jd is not None: tt = jd else: tt = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second), ) tt = _to_array(tt) return Time(self, tt)
[ "def", "tt", "(", "self", ",", "year", "=", "None", ",", "month", "=", "1", ",", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0.0", ",", "jd", "=", "None", ")", ":", "if", "jd", "is", "not", "None", ...
Build a `Time` from a TT calendar date. Supply the Terrestrial Time (TT) as a proleptic Gregorian calendar date: >>> t = ts.tt(2014, 1, 18, 1, 35, 37.5) >>> t.tt 2456675.56640625 >>> t.tt_calendar() (2014, 1, 18, 1, 35, 37.5)
[ "Build", "a", "Time", "from", "a", "TT", "calendar", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L169-L191
243,765
skyfielders/python-skyfield
skyfield/timelib.py
Timescale.tdb
def tdb(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a TDB calendar date. Supply the Barycentric Dynamical Time (TDB) as a proleptic Gregorian calendar date: >>> t = ts.tdb(2014, 1, 18, 1, 35, 37.5) >>> t.tdb 2456675.56640625 """ if jd is not None: tdb = jd else: tdb = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second), ) tdb = _to_array(tdb) tt = tdb - tdb_minus_tt(tdb) / DAY_S t = Time(self, tt) t.tdb = tdb return t
python
def tdb(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): if jd is not None: tdb = jd else: tdb = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second), ) tdb = _to_array(tdb) tt = tdb - tdb_minus_tt(tdb) / DAY_S t = Time(self, tt) t.tdb = tdb return t
[ "def", "tdb", "(", "self", ",", "year", "=", "None", ",", "month", "=", "1", ",", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0.0", ",", "jd", "=", "None", ")", ":", "if", "jd", "is", "not", "None",...
Build a `Time` from a TDB calendar date. Supply the Barycentric Dynamical Time (TDB) as a proleptic Gregorian calendar date: >>> t = ts.tdb(2014, 1, 18, 1, 35, 37.5) >>> t.tdb 2456675.56640625
[ "Build", "a", "Time", "from", "a", "TDB", "calendar", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L208-L231
243,766
skyfielders/python-skyfield
skyfield/timelib.py
Timescale.tdb_jd
def tdb_jd(self, jd): """Build a `Time` from a TDB Julian date. Supply the Barycentric Dynamical Time (TDB) as a Julian date: >>> t = ts.tdb_jd(2456675.56640625) >>> t.tdb 2456675.56640625 """ tdb = _to_array(jd) tt = tdb - tdb_minus_tt(tdb) / DAY_S t = Time(self, tt) t.tdb = tdb return t
python
def tdb_jd(self, jd): tdb = _to_array(jd) tt = tdb - tdb_minus_tt(tdb) / DAY_S t = Time(self, tt) t.tdb = tdb return t
[ "def", "tdb_jd", "(", "self", ",", "jd", ")", ":", "tdb", "=", "_to_array", "(", "jd", ")", "tt", "=", "tdb", "-", "tdb_minus_tt", "(", "tdb", ")", "/", "DAY_S", "t", "=", "Time", "(", "self", ",", "tt", ")", "t", ".", "tdb", "=", "tdb", "ret...
Build a `Time` from a TDB Julian date. Supply the Barycentric Dynamical Time (TDB) as a Julian date: >>> t = ts.tdb_jd(2456675.56640625) >>> t.tdb 2456675.56640625
[ "Build", "a", "Time", "from", "a", "TDB", "Julian", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L233-L247
243,767
skyfielders/python-skyfield
skyfield/timelib.py
Timescale.ut1
def ut1(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a UT1 calendar date. Supply the Universal Time (UT1) as a proleptic Gregorian calendar date: >>> t = ts.ut1(2014, 1, 18, 1, 35, 37.5) >>> t.ut1 2456675.56640625 """ if jd is not None: ut1 = jd else: ut1 = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second), ) return self.ut1_jd(ut1)
python
def ut1(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): if jd is not None: ut1 = jd else: ut1 = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_array(second), ) return self.ut1_jd(ut1)
[ "def", "ut1", "(", "self", ",", "year", "=", "None", ",", "month", "=", "1", ",", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0.0", ",", "jd", "=", "None", ")", ":", "if", "jd", "is", "not", "None",...
Build a `Time` from a UT1 calendar date. Supply the Universal Time (UT1) as a proleptic Gregorian calendar date: >>> t = ts.ut1(2014, 1, 18, 1, 35, 37.5) >>> t.ut1 2456675.56640625
[ "Build", "a", "Time", "from", "a", "UT1", "calendar", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L249-L268
243,768
skyfielders/python-skyfield
skyfield/timelib.py
Timescale.ut1_jd
def ut1_jd(self, jd): """Build a `Time` from UT1 a Julian date. Supply the Universal Time (UT1) as a Julian date: >>> t = ts.ut1_jd(2456675.56640625) >>> t.ut1 2456675.56640625 """ ut1 = _to_array(jd) # Estimate TT = UT1, to get a rough Delta T estimate. tt_approx = ut1 delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx) # Use the rough Delta T to make a much better estimate of TT, # then generate an even better Delta T. tt_approx = ut1 + delta_t_approx / DAY_S delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx) # We can now estimate TT with an error of < 1e-9 seconds within # 10 centuries of either side of the present; for details, see: # https://github.com/skyfielders/astronomy-notebooks # and look for the notebook "error-in-timescale-ut1.ipynb". tt = ut1 + delta_t_approx / DAY_S t = Time(self, tt) t.ut1 = ut1 return t
python
def ut1_jd(self, jd): ut1 = _to_array(jd) # Estimate TT = UT1, to get a rough Delta T estimate. tt_approx = ut1 delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx) # Use the rough Delta T to make a much better estimate of TT, # then generate an even better Delta T. tt_approx = ut1 + delta_t_approx / DAY_S delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx) # We can now estimate TT with an error of < 1e-9 seconds within # 10 centuries of either side of the present; for details, see: # https://github.com/skyfielders/astronomy-notebooks # and look for the notebook "error-in-timescale-ut1.ipynb". tt = ut1 + delta_t_approx / DAY_S t = Time(self, tt) t.ut1 = ut1 return t
[ "def", "ut1_jd", "(", "self", ",", "jd", ")", ":", "ut1", "=", "_to_array", "(", "jd", ")", "# Estimate TT = UT1, to get a rough Delta T estimate.", "tt_approx", "=", "ut1", "delta_t_approx", "=", "interpolate_delta_t", "(", "self", ".", "delta_t_table", ",", "tt_...
Build a `Time` from UT1 a Julian date. Supply the Universal Time (UT1) as a Julian date: >>> t = ts.ut1_jd(2456675.56640625) >>> t.ut1 2456675.56640625
[ "Build", "a", "Time", "from", "UT1", "a", "Julian", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L270-L298
243,769
skyfielders/python-skyfield
skyfield/timelib.py
Time.astimezone_and_leap_second
def astimezone_and_leap_second(self, tz): """Convert to a Python ``datetime`` and leap second in a timezone. Convert this time to a Python ``datetime`` and a leap second:: dt, leap_second = t.astimezone_and_leap_second(tz) The argument ``tz`` should be a timezone from the third-party ``pytz`` package, which must be installed separately. The date and time returned will be for that time zone. The leap second value is provided because a Python ``datetime`` can only number seconds ``0`` through ``59``, but leap seconds have a designation of at least ``60``. The leap second return value will normally be ``0``, but will instead be ``1`` if the date and time are a UTC leap second. Add the leap second value to the ``second`` field of the ``datetime`` to learn the real name of the second. If this time is an array, then an array of ``datetime`` objects and an array of leap second integers is returned, instead of a single value each. """ dt, leap_second = self.utc_datetime_and_leap_second() normalize = getattr(tz, 'normalize', None) if self.shape and normalize is not None: dt = array([normalize(d.astimezone(tz)) for d in dt]) elif self.shape: dt = array([d.astimezone(tz) for d in dt]) elif normalize is not None: dt = normalize(dt.astimezone(tz)) else: dt = dt.astimezone(tz) return dt, leap_second
python
def astimezone_and_leap_second(self, tz): dt, leap_second = self.utc_datetime_and_leap_second() normalize = getattr(tz, 'normalize', None) if self.shape and normalize is not None: dt = array([normalize(d.astimezone(tz)) for d in dt]) elif self.shape: dt = array([d.astimezone(tz) for d in dt]) elif normalize is not None: dt = normalize(dt.astimezone(tz)) else: dt = dt.astimezone(tz) return dt, leap_second
[ "def", "astimezone_and_leap_second", "(", "self", ",", "tz", ")", ":", "dt", ",", "leap_second", "=", "self", ".", "utc_datetime_and_leap_second", "(", ")", "normalize", "=", "getattr", "(", "tz", ",", "'normalize'", ",", "None", ")", "if", "self", ".", "s...
Convert to a Python ``datetime`` and leap second in a timezone. Convert this time to a Python ``datetime`` and a leap second:: dt, leap_second = t.astimezone_and_leap_second(tz) The argument ``tz`` should be a timezone from the third-party ``pytz`` package, which must be installed separately. The date and time returned will be for that time zone. The leap second value is provided because a Python ``datetime`` can only number seconds ``0`` through ``59``, but leap seconds have a designation of at least ``60``. The leap second return value will normally be ``0``, but will instead be ``1`` if the date and time are a UTC leap second. Add the leap second value to the ``second`` field of the ``datetime`` to learn the real name of the second. If this time is an array, then an array of ``datetime`` objects and an array of leap second integers is returned, instead of a single value each.
[ "Convert", "to", "a", "Python", "datetime", "and", "leap", "second", "in", "a", "timezone", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L365-L399
243,770
skyfielders/python-skyfield
skyfield/timelib.py
Time.utc_datetime_and_leap_second
def utc_datetime_and_leap_second(self): """Convert to a Python ``datetime`` in UTC, plus a leap second value. Convert this time to a `datetime`_ object and a leap second:: dt, leap_second = t.utc_datetime_and_leap_second() If the third-party `pytz`_ package is available, then its ``utc`` timezone will be used as the timezone of the return value. Otherwise, Skyfield uses its own ``utc`` timezone. The leap second value is provided because a Python ``datetime`` can only number seconds ``0`` through ``59``, but leap seconds have a designation of at least ``60``. The leap second return value will normally be ``0``, but will instead be ``1`` if the date and time are a UTC leap second. Add the leap second value to the ``second`` field of the ``datetime`` to learn the real name of the second. If this time is an array, then an array of ``datetime`` objects and an array of leap second integers is returned, instead of a single value each. """ year, month, day, hour, minute, second = self._utc_tuple( _half_millisecond) second, fraction = divmod(second, 1.0) second = second.astype(int) leap_second = second // 60 second -= leap_second milli = (fraction * 1000).astype(int) * 1000 if self.shape: utcs = [utc] * self.shape[0] argsets = zip(year, month, day, hour, minute, second, milli, utcs) dt = array([datetime(*args) for args in argsets]) else: dt = datetime(year, month, day, hour, minute, second, milli, utc) return dt, leap_second
python
def utc_datetime_and_leap_second(self): year, month, day, hour, minute, second = self._utc_tuple( _half_millisecond) second, fraction = divmod(second, 1.0) second = second.astype(int) leap_second = second // 60 second -= leap_second milli = (fraction * 1000).astype(int) * 1000 if self.shape: utcs = [utc] * self.shape[0] argsets = zip(year, month, day, hour, minute, second, milli, utcs) dt = array([datetime(*args) for args in argsets]) else: dt = datetime(year, month, day, hour, minute, second, milli, utc) return dt, leap_second
[ "def", "utc_datetime_and_leap_second", "(", "self", ")", ":", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", "=", "self", ".", "_utc_tuple", "(", "_half_millisecond", ")", "second", ",", "fraction", "=", "divmod", "(", "second...
Convert to a Python ``datetime`` in UTC, plus a leap second value. Convert this time to a `datetime`_ object and a leap second:: dt, leap_second = t.utc_datetime_and_leap_second() If the third-party `pytz`_ package is available, then its ``utc`` timezone will be used as the timezone of the return value. Otherwise, Skyfield uses its own ``utc`` timezone. The leap second value is provided because a Python ``datetime`` can only number seconds ``0`` through ``59``, but leap seconds have a designation of at least ``60``. The leap second return value will normally be ``0``, but will instead be ``1`` if the date and time are a UTC leap second. Add the leap second value to the ``second`` field of the ``datetime`` to learn the real name of the second. If this time is an array, then an array of ``datetime`` objects and an array of leap second integers is returned, instead of a single value each.
[ "Convert", "to", "a", "Python", "datetime", "in", "UTC", "plus", "a", "leap", "second", "value", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L425-L462
243,771
skyfielders/python-skyfield
skyfield/timelib.py
Time.utc_strftime
def utc_strftime(self, format): """Format the UTC time using a Python date formatting string. This internally calls the Python ``strftime()`` routine from the Standard Library ``time()`` module, for which you can find a quick reference at ``http://strftime.org/``. If this object is an array of times, then a sequence of strings is returned instead of a single string. """ tup = self._utc_tuple(_half_second) year, month, day, hour, minute, second = tup second = second.astype(int) zero = zeros_like(year) tup = (year, month, day, hour, minute, second, zero, zero, zero) if self.shape: return [strftime(format, item) for item in zip(*tup)] else: return strftime(format, tup)
python
def utc_strftime(self, format): tup = self._utc_tuple(_half_second) year, month, day, hour, minute, second = tup second = second.astype(int) zero = zeros_like(year) tup = (year, month, day, hour, minute, second, zero, zero, zero) if self.shape: return [strftime(format, item) for item in zip(*tup)] else: return strftime(format, tup)
[ "def", "utc_strftime", "(", "self", ",", "format", ")", ":", "tup", "=", "self", ".", "_utc_tuple", "(", "_half_second", ")", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", "=", "tup", "second", "=", "second", ".", "asty...
Format the UTC time using a Python date formatting string. This internally calls the Python ``strftime()`` routine from the Standard Library ``time()`` module, for which you can find a quick reference at ``http://strftime.org/``. If this object is an array of times, then a sequence of strings is returned instead of a single string.
[ "Format", "the", "UTC", "time", "using", "a", "Python", "date", "formatting", "string", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L520-L538
243,772
skyfielders/python-skyfield
skyfield/timelib.py
Time._utc_year
def _utc_year(self): """Return a fractional UTC year, for convenience when plotting. An experiment, probably superseded by the ``J`` attribute below. """ d = self._utc_float() - 1721059.5 #d += offset C = 365 * 100 + 24 d -= 365 d += d // C - d // (4 * C) d += 365 # Y = d / C * 100 # print(Y) K = 365 * 3 + 366 d -= (d + K*7//8) // K # d -= d // 1461.0 return d / 365.0
python
def _utc_year(self): d = self._utc_float() - 1721059.5 #d += offset C = 365 * 100 + 24 d -= 365 d += d // C - d // (4 * C) d += 365 # Y = d / C * 100 # print(Y) K = 365 * 3 + 366 d -= (d + K*7//8) // K # d -= d // 1461.0 return d / 365.0
[ "def", "_utc_year", "(", "self", ")", ":", "d", "=", "self", ".", "_utc_float", "(", ")", "-", "1721059.5", "#d += offset", "C", "=", "365", "*", "100", "+", "24", "d", "-=", "365", "d", "+=", "d", "//", "C", "-", "d", "//", "(", "4", "*", "C...
Return a fractional UTC year, for convenience when plotting. An experiment, probably superseded by the ``J`` attribute below.
[ "Return", "a", "fractional", "UTC", "year", "for", "convenience", "when", "plotting", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L540-L557
243,773
skyfielders/python-skyfield
skyfield/timelib.py
Time._utc_float
def _utc_float(self): """Return UTC as a floating point Julian date.""" tai = self.tai leap_dates = self.ts.leap_dates leap_offsets = self.ts.leap_offsets leap_reverse_dates = leap_dates + leap_offsets / DAY_S i = searchsorted(leap_reverse_dates, tai, 'right') return tai - leap_offsets[i] / DAY_S
python
def _utc_float(self): tai = self.tai leap_dates = self.ts.leap_dates leap_offsets = self.ts.leap_offsets leap_reverse_dates = leap_dates + leap_offsets / DAY_S i = searchsorted(leap_reverse_dates, tai, 'right') return tai - leap_offsets[i] / DAY_S
[ "def", "_utc_float", "(", "self", ")", ":", "tai", "=", "self", ".", "tai", "leap_dates", "=", "self", ".", "ts", ".", "leap_dates", "leap_offsets", "=", "self", ".", "ts", ".", "leap_offsets", "leap_reverse_dates", "=", "leap_dates", "+", "leap_offsets", ...
Return UTC as a floating point Julian date.
[ "Return", "UTC", "as", "a", "floating", "point", "Julian", "date", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L586-L593
243,774
skyfielders/python-skyfield
skyfield/earthlib.py
terra
def terra(latitude, longitude, elevation, gast): """Compute the position and velocity of a terrestrial observer. `latitude` - Latitude in radians. `longitude` - Longitude in radians. `elevation` - Elevation above sea level in au. `gast` - Hours of Greenwich Apparent Sidereal Time (can be an array). The return value is a tuple of two 3-vectors `(pos, vel)` in the dynamical reference system (the true equator and equinox of date) whose components are measured in au with respect to the center of the Earth. """ zero = zeros_like(gast) sinphi = sin(latitude) cosphi = cos(latitude) c = 1.0 / sqrt(cosphi * cosphi + sinphi * sinphi * one_minus_flattening_squared) s = one_minus_flattening_squared * c ach = earth_radius_au * c + elevation ash = earth_radius_au * s + elevation # Compute local sidereal time factors at the observer's longitude. stlocl = 15.0 * DEG2RAD * gast + longitude sinst = sin(stlocl) cosst = cos(stlocl) # Compute position vector components in kilometers. ac = ach * cosphi acsst = ac * sinst accst = ac * cosst pos = array((accst, acsst, zero + ash * sinphi)) # Compute velocity vector components in kilometers/sec. vel = ANGVEL * DAY_S * array((-acsst, accst, zero)) return pos, vel
python
def terra(latitude, longitude, elevation, gast): zero = zeros_like(gast) sinphi = sin(latitude) cosphi = cos(latitude) c = 1.0 / sqrt(cosphi * cosphi + sinphi * sinphi * one_minus_flattening_squared) s = one_minus_flattening_squared * c ach = earth_radius_au * c + elevation ash = earth_radius_au * s + elevation # Compute local sidereal time factors at the observer's longitude. stlocl = 15.0 * DEG2RAD * gast + longitude sinst = sin(stlocl) cosst = cos(stlocl) # Compute position vector components in kilometers. ac = ach * cosphi acsst = ac * sinst accst = ac * cosst pos = array((accst, acsst, zero + ash * sinphi)) # Compute velocity vector components in kilometers/sec. vel = ANGVEL * DAY_S * array((-acsst, accst, zero)) return pos, vel
[ "def", "terra", "(", "latitude", ",", "longitude", ",", "elevation", ",", "gast", ")", ":", "zero", "=", "zeros_like", "(", "gast", ")", "sinphi", "=", "sin", "(", "latitude", ")", "cosphi", "=", "cos", "(", "latitude", ")", "c", "=", "1.0", "/", "...
Compute the position and velocity of a terrestrial observer. `latitude` - Latitude in radians. `longitude` - Longitude in radians. `elevation` - Elevation above sea level in au. `gast` - Hours of Greenwich Apparent Sidereal Time (can be an array). The return value is a tuple of two 3-vectors `(pos, vel)` in the dynamical reference system (the true equator and equinox of date) whose components are measured in au with respect to the center of the Earth.
[ "Compute", "the", "position", "and", "velocity", "of", "a", "terrestrial", "observer", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L15-L55
243,775
skyfielders/python-skyfield
skyfield/earthlib.py
compute_limb_angle
def compute_limb_angle(position_au, observer_au): """Determine the angle of an object above or below the Earth's limb. Given an object's GCRS `position_au` [x,y,z] vector and the position of an `observer_au` as a vector in the same coordinate system, return a tuple that provides `(limb_ang, nadir_ang)`: limb_angle Angle of observed object above (+) or below (-) limb in degrees. nadir_angle Nadir angle of observed object as a fraction of apparent radius of limb: <1.0 means below the limb, =1.0 means on the limb, and >1.0 means above the limb. """ # Compute the distance to the object and the distance to the observer. disobj = sqrt(dots(position_au, position_au)) disobs = sqrt(dots(observer_au, observer_au)) # Compute apparent angular radius of Earth's limb. aprad = arcsin(minimum(earth_radius_au / disobs, 1.0)) # Compute zenith distance of Earth's limb. zdlim = pi - aprad # Compute zenith distance of observed object. coszd = dots(position_au, observer_au) / (disobj * disobs) coszd = clip(coszd, -1.0, 1.0) zdobj = arccos(coszd) # Angle of object wrt limb is difference in zenith distances. limb_angle = (zdlim - zdobj) * RAD2DEG # Nadir angle of object as a fraction of angular radius of limb. nadir_angle = (pi - zdobj) / aprad return limb_angle, nadir_angle
python
def compute_limb_angle(position_au, observer_au): # Compute the distance to the object and the distance to the observer. disobj = sqrt(dots(position_au, position_au)) disobs = sqrt(dots(observer_au, observer_au)) # Compute apparent angular radius of Earth's limb. aprad = arcsin(minimum(earth_radius_au / disobs, 1.0)) # Compute zenith distance of Earth's limb. zdlim = pi - aprad # Compute zenith distance of observed object. coszd = dots(position_au, observer_au) / (disobj * disobs) coszd = clip(coszd, -1.0, 1.0) zdobj = arccos(coszd) # Angle of object wrt limb is difference in zenith distances. limb_angle = (zdlim - zdobj) * RAD2DEG # Nadir angle of object as a fraction of angular radius of limb. nadir_angle = (pi - zdobj) / aprad return limb_angle, nadir_angle
[ "def", "compute_limb_angle", "(", "position_au", ",", "observer_au", ")", ":", "# Compute the distance to the object and the distance to the observer.", "disobj", "=", "sqrt", "(", "dots", "(", "position_au", ",", "position_au", ")", ")", "disobs", "=", "sqrt", "(", "...
Determine the angle of an object above or below the Earth's limb. Given an object's GCRS `position_au` [x,y,z] vector and the position of an `observer_au` as a vector in the same coordinate system, return a tuple that provides `(limb_ang, nadir_ang)`: limb_angle Angle of observed object above (+) or below (-) limb in degrees. nadir_angle Nadir angle of observed object as a fraction of apparent radius of limb: <1.0 means below the limb, =1.0 means on the limb, and >1.0 means above the limb.
[ "Determine", "the", "angle", "of", "an", "object", "above", "or", "below", "the", "Earth", "s", "limb", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L85-L127
243,776
skyfielders/python-skyfield
skyfield/earthlib.py
sidereal_time
def sidereal_time(t): """Compute Greenwich sidereal time at the given ``Time``.""" # Compute the Earth Rotation Angle. Time argument is UT1. theta = earth_rotation_angle(t.ut1) # The equinox method. See Circular 179, Section 2.6.2. # Precession-in-RA terms in mean sidereal time taken from third # reference, eq. (42), with coefficients in arcseconds. t = (t.tdb - T0) / 36525.0 st = ( 0.014506 + (((( - 0.0000000368 * t - 0.000029956 ) * t - 0.00000044 ) * t + 1.3915817 ) * t + 4612.156534 ) * t) # Form the Greenwich sidereal time. return (st / 54000.0 + theta * 24.0) % 24.0
python
def sidereal_time(t): # Compute the Earth Rotation Angle. Time argument is UT1. theta = earth_rotation_angle(t.ut1) # The equinox method. See Circular 179, Section 2.6.2. # Precession-in-RA terms in mean sidereal time taken from third # reference, eq. (42), with coefficients in arcseconds. t = (t.tdb - T0) / 36525.0 st = ( 0.014506 + (((( - 0.0000000368 * t - 0.000029956 ) * t - 0.00000044 ) * t + 1.3915817 ) * t + 4612.156534 ) * t) # Form the Greenwich sidereal time. return (st / 54000.0 + theta * 24.0) % 24.0
[ "def", "sidereal_time", "(", "t", ")", ":", "# Compute the Earth Rotation Angle. Time argument is UT1.", "theta", "=", "earth_rotation_angle", "(", "t", ".", "ut1", ")", "# The equinox method. See Circular 179, Section 2.6.2.", "# Precession-in-RA terms in mean sidereal time taken ...
Compute Greenwich sidereal time at the given ``Time``.
[ "Compute", "Greenwich", "sidereal", "time", "at", "the", "given", "Time", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L130-L151
243,777
skyfielders/python-skyfield
skyfield/earthlib.py
refraction
def refraction(alt_degrees, temperature_C, pressure_mbar): """Given an observed altitude, return how much the image is refracted. Zero refraction is returned both for objects very near the zenith, as well as for objects more than one degree below the horizon. """ r = 0.016667 / tan((alt_degrees + 7.31 / (alt_degrees + 4.4)) * DEG2RAD) d = r * (0.28 * pressure_mbar / (temperature_C + 273.0)) return where((-1.0 <= alt_degrees) & (alt_degrees <= 89.9), d, 0.0)
python
def refraction(alt_degrees, temperature_C, pressure_mbar): r = 0.016667 / tan((alt_degrees + 7.31 / (alt_degrees + 4.4)) * DEG2RAD) d = r * (0.28 * pressure_mbar / (temperature_C + 273.0)) return where((-1.0 <= alt_degrees) & (alt_degrees <= 89.9), d, 0.0)
[ "def", "refraction", "(", "alt_degrees", ",", "temperature_C", ",", "pressure_mbar", ")", ":", "r", "=", "0.016667", "/", "tan", "(", "(", "alt_degrees", "+", "7.31", "/", "(", "alt_degrees", "+", "4.4", ")", ")", "*", "DEG2RAD", ")", "d", "=", "r", ...
Given an observed altitude, return how much the image is refracted. Zero refraction is returned both for objects very near the zenith, as well as for objects more than one degree below the horizon.
[ "Given", "an", "observed", "altitude", "return", "how", "much", "the", "image", "is", "refracted", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L166-L175
243,778
skyfielders/python-skyfield
skyfield/earthlib.py
refract
def refract(alt_degrees, temperature_C, pressure_mbar): """Given an unrefracted `alt` determine where it will appear in the sky.""" alt = alt_degrees while True: alt1 = alt alt = alt_degrees + refraction(alt, temperature_C, pressure_mbar) converged = abs(alt - alt1) <= 3.0e-5 if converged.all(): break return alt
python
def refract(alt_degrees, temperature_C, pressure_mbar): alt = alt_degrees while True: alt1 = alt alt = alt_degrees + refraction(alt, temperature_C, pressure_mbar) converged = abs(alt - alt1) <= 3.0e-5 if converged.all(): break return alt
[ "def", "refract", "(", "alt_degrees", ",", "temperature_C", ",", "pressure_mbar", ")", ":", "alt", "=", "alt_degrees", "while", "True", ":", "alt1", "=", "alt", "alt", "=", "alt_degrees", "+", "refraction", "(", "alt", ",", "temperature_C", ",", "pressure_mb...
Given an unrefracted `alt` determine where it will appear in the sky.
[ "Given", "an", "unrefracted", "alt", "determine", "where", "it", "will", "appear", "in", "the", "sky", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L178-L187
243,779
skyfielders/python-skyfield
skyfield/precessionlib.py
compute_precession
def compute_precession(jd_tdb): """Return the rotation matrices for precessing to an array of epochs. `jd_tdb` - array of TDB Julian dates The array returned has the shape `(3, 3, n)` where `n` is the number of dates that have been provided as input. """ eps0 = 84381.406 # 't' is time in TDB centuries. t = (jd_tdb - T0) / 36525.0 # Numerical coefficients of psi_a, omega_a, and chi_a, along with # epsilon_0, the obliquity at J2000.0, are 4-angle formulation from # Capitaine et al. (2003), eqs. (4), (37), & (39). psia = ((((- 0.0000000951 * t + 0.000132851 ) * t - 0.00114045 ) * t - 1.0790069 ) * t + 5038.481507 ) * t omegaa = ((((+ 0.0000003337 * t - 0.000000467 ) * t - 0.00772503 ) * t + 0.0512623 ) * t - 0.025754 ) * t + eps0 chia = ((((- 0.0000000560 * t + 0.000170663 ) * t - 0.00121197 ) * t - 2.3814292 ) * t + 10.556403 ) * t eps0 = eps0 * ASEC2RAD psia = psia * ASEC2RAD omegaa = omegaa * ASEC2RAD chia = chia * ASEC2RAD sa = sin(eps0) ca = cos(eps0) sb = sin(-psia) cb = cos(-psia) sc = sin(-omegaa) cc = cos(-omegaa) sd = sin(chia) cd = cos(chia) # Compute elements of precession rotation matrix equivalent to # R3(chi_a) R1(-omega_a) R3(-psi_a) R1(epsilon_0). rot3 = array(((cd * cb - sb * sd * cc, cd * sb * ca + sd * cc * cb * ca - sa * sd * sc, cd * sb * sa + sd * cc * cb * sa + ca * sd * sc), (-sd * cb - sb * cd * cc, -sd * sb * ca + cd * cc * cb * ca - sa * cd * sc, -sd * sb * sa + cd * cc * cb * sa + ca * cd * sc), (sb * sc, -sc * cb * ca - sa * cc, -sc * cb * sa + cc * ca))) return rot3
python
def compute_precession(jd_tdb): eps0 = 84381.406 # 't' is time in TDB centuries. t = (jd_tdb - T0) / 36525.0 # Numerical coefficients of psi_a, omega_a, and chi_a, along with # epsilon_0, the obliquity at J2000.0, are 4-angle formulation from # Capitaine et al. (2003), eqs. (4), (37), & (39). psia = ((((- 0.0000000951 * t + 0.000132851 ) * t - 0.00114045 ) * t - 1.0790069 ) * t + 5038.481507 ) * t omegaa = ((((+ 0.0000003337 * t - 0.000000467 ) * t - 0.00772503 ) * t + 0.0512623 ) * t - 0.025754 ) * t + eps0 chia = ((((- 0.0000000560 * t + 0.000170663 ) * t - 0.00121197 ) * t - 2.3814292 ) * t + 10.556403 ) * t eps0 = eps0 * ASEC2RAD psia = psia * ASEC2RAD omegaa = omegaa * ASEC2RAD chia = chia * ASEC2RAD sa = sin(eps0) ca = cos(eps0) sb = sin(-psia) cb = cos(-psia) sc = sin(-omegaa) cc = cos(-omegaa) sd = sin(chia) cd = cos(chia) # Compute elements of precession rotation matrix equivalent to # R3(chi_a) R1(-omega_a) R3(-psi_a) R1(epsilon_0). rot3 = array(((cd * cb - sb * sd * cc, cd * sb * ca + sd * cc * cb * ca - sa * sd * sc, cd * sb * sa + sd * cc * cb * sa + ca * sd * sc), (-sd * cb - sb * cd * cc, -sd * sb * ca + cd * cc * cb * ca - sa * cd * sc, -sd * sb * sa + cd * cc * cb * sa + ca * cd * sc), (sb * sc, -sc * cb * ca - sa * cc, -sc * cb * sa + cc * ca))) return rot3
[ "def", "compute_precession", "(", "jd_tdb", ")", ":", "eps0", "=", "84381.406", "# 't' is time in TDB centuries.", "t", "=", "(", "jd_tdb", "-", "T0", ")", "/", "36525.0", "# Numerical coefficients of psi_a, omega_a, and chi_a, along with", "# epsilon_0, the obliquity at J200...
Return the rotation matrices for precessing to an array of epochs. `jd_tdb` - array of TDB Julian dates The array returned has the shape `(3, 3, n)` where `n` is the number of dates that have been provided as input.
[ "Return", "the", "rotation", "matrices", "for", "precessing", "to", "an", "array", "of", "epochs", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/precessionlib.py#L5-L69
243,780
skyfielders/python-skyfield
skyfield/nutationlib.py
compute_nutation
def compute_nutation(t): """Generate the nutation rotations for Time `t`. If the Julian date is scalar, a simple ``(3, 3)`` matrix is returned; if the date is an array of length ``n``, then an array of matrices is returned with dimensions ``(3, 3, n)``. """ oblm, oblt, eqeq, psi, eps = t._earth_tilt cobm = cos(oblm * DEG2RAD) sobm = sin(oblm * DEG2RAD) cobt = cos(oblt * DEG2RAD) sobt = sin(oblt * DEG2RAD) cpsi = cos(psi * ASEC2RAD) spsi = sin(psi * ASEC2RAD) return array(((cpsi, -spsi * cobm, -spsi * sobm), (spsi * cobt, cpsi * cobm * cobt + sobm * sobt, cpsi * sobm * cobt - cobm * sobt), (spsi * sobt, cpsi * cobm * sobt - sobm * cobt, cpsi * sobm * sobt + cobm * cobt)))
python
def compute_nutation(t): oblm, oblt, eqeq, psi, eps = t._earth_tilt cobm = cos(oblm * DEG2RAD) sobm = sin(oblm * DEG2RAD) cobt = cos(oblt * DEG2RAD) sobt = sin(oblt * DEG2RAD) cpsi = cos(psi * ASEC2RAD) spsi = sin(psi * ASEC2RAD) return array(((cpsi, -spsi * cobm, -spsi * sobm), (spsi * cobt, cpsi * cobm * cobt + sobm * sobt, cpsi * sobm * cobt - cobm * sobt), (spsi * sobt, cpsi * cobm * sobt - sobm * cobt, cpsi * sobm * sobt + cobm * cobt)))
[ "def", "compute_nutation", "(", "t", ")", ":", "oblm", ",", "oblt", ",", "eqeq", ",", "psi", ",", "eps", "=", "t", ".", "_earth_tilt", "cobm", "=", "cos", "(", "oblm", "*", "DEG2RAD", ")", "sobm", "=", "sin", "(", "oblm", "*", "DEG2RAD", ")", "co...
Generate the nutation rotations for Time `t`. If the Julian date is scalar, a simple ``(3, 3)`` matrix is returned; if the date is an array of length ``n``, then an array of matrices is returned with dimensions ``(3, 3, n)``.
[ "Generate", "the", "nutation", "rotations", "for", "Time", "t", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L19-L44
243,781
skyfielders/python-skyfield
skyfield/nutationlib.py
earth_tilt
def earth_tilt(t): """Return a tuple of information about the earth's axis and position. `t` - A Time object. The returned tuple contains five items: ``mean_ob`` - Mean obliquity of the ecliptic in degrees. ``true_ob`` - True obliquity of the ecliptic in degrees. ``eq_eq`` - Equation of the equinoxes in seconds of time. ``d_psi`` - Nutation in longitude in arcseconds. ``d_eps`` - Nutation in obliquity in arcseconds. """ dp, de = t._nutation_angles c_terms = equation_of_the_equinoxes_complimentary_terms(t.tt) / ASEC2RAD d_psi = dp * 1e-7 + t.psi_correction d_eps = de * 1e-7 + t.eps_correction mean_ob = mean_obliquity(t.tdb) true_ob = mean_ob + d_eps mean_ob /= 3600.0 true_ob /= 3600.0 eq_eq = d_psi * cos(mean_ob * DEG2RAD) + c_terms eq_eq /= 15.0 return mean_ob, true_ob, eq_eq, d_psi, d_eps
python
def earth_tilt(t): dp, de = t._nutation_angles c_terms = equation_of_the_equinoxes_complimentary_terms(t.tt) / ASEC2RAD d_psi = dp * 1e-7 + t.psi_correction d_eps = de * 1e-7 + t.eps_correction mean_ob = mean_obliquity(t.tdb) true_ob = mean_ob + d_eps mean_ob /= 3600.0 true_ob /= 3600.0 eq_eq = d_psi * cos(mean_ob * DEG2RAD) + c_terms eq_eq /= 15.0 return mean_ob, true_ob, eq_eq, d_psi, d_eps
[ "def", "earth_tilt", "(", "t", ")", ":", "dp", ",", "de", "=", "t", ".", "_nutation_angles", "c_terms", "=", "equation_of_the_equinoxes_complimentary_terms", "(", "t", ".", "tt", ")", "/", "ASEC2RAD", "d_psi", "=", "dp", "*", "1e-7", "+", "t", ".", "psi_...
Return a tuple of information about the earth's axis and position. `t` - A Time object. The returned tuple contains five items: ``mean_ob`` - Mean obliquity of the ecliptic in degrees. ``true_ob`` - True obliquity of the ecliptic in degrees. ``eq_eq`` - Equation of the equinoxes in seconds of time. ``d_psi`` - Nutation in longitude in arcseconds. ``d_eps`` - Nutation in obliquity in arcseconds.
[ "Return", "a", "tuple", "of", "information", "about", "the", "earth", "s", "axis", "and", "position", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L46-L75
243,782
skyfielders/python-skyfield
skyfield/nutationlib.py
mean_obliquity
def mean_obliquity(jd_tdb): """Return the mean obliquity of the ecliptic in arcseconds. `jd_tt` - TDB time as a Julian date float, or NumPy array of floats """ # Compute time in Julian centuries from epoch J2000.0. t = (jd_tdb - T0) / 36525.0 # Compute the mean obliquity in arcseconds. Use expression from the # reference's eq. (39) with obliquity at J2000.0 taken from eq. (37) # or Table 8. epsilon = (((( - 0.0000000434 * t - 0.000000576 ) * t + 0.00200340 ) * t - 0.0001831 ) * t - 46.836769 ) * t + 84381.406 return epsilon
python
def mean_obliquity(jd_tdb): # Compute time in Julian centuries from epoch J2000.0. t = (jd_tdb - T0) / 36525.0 # Compute the mean obliquity in arcseconds. Use expression from the # reference's eq. (39) with obliquity at J2000.0 taken from eq. (37) # or Table 8. epsilon = (((( - 0.0000000434 * t - 0.000000576 ) * t + 0.00200340 ) * t - 0.0001831 ) * t - 46.836769 ) * t + 84381.406 return epsilon
[ "def", "mean_obliquity", "(", "jd_tdb", ")", ":", "# Compute time in Julian centuries from epoch J2000.0.", "t", "=", "(", "jd_tdb", "-", "T0", ")", "/", "36525.0", "# Compute the mean obliquity in arcseconds. Use expression from the", "# reference's eq. (39) with obliquity at J20...
Return the mean obliquity of the ecliptic in arcseconds. `jd_tt` - TDB time as a Julian date float, or NumPy array of floats
[ "Return", "the", "mean", "obliquity", "of", "the", "ecliptic", "in", "arcseconds", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L79-L99
243,783
skyfielders/python-skyfield
skyfield/nutationlib.py
equation_of_the_equinoxes_complimentary_terms
def equation_of_the_equinoxes_complimentary_terms(jd_tt): """Compute the complementary terms of the equation of the equinoxes. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats """ # Interval between fundamental epoch J2000.0 and current date. t = (jd_tt - T0) / 36525.0 # Build array for intermediate results. shape = getattr(jd_tt, 'shape', ()) fa = zeros((14,) if shape == () else (14, shape[0])) # Mean Anomaly of the Moon. fa[0] = ((485868.249036 + (715923.2178 + ( 31.8792 + ( 0.051635 + ( -0.00024470) * t) * t) * t) * t) * ASEC2RAD + (1325.0*t % 1.0) * tau) # Mean Anomaly of the Sun. fa[1] = ((1287104.793048 + (1292581.0481 + ( -0.5532 + ( +0.000136 + ( -0.00001149) * t) * t) * t) * t) * ASEC2RAD + (99.0*t % 1.0) * tau) # Mean Longitude of the Moon minus Mean Longitude of the Ascending # Node of the Moon. fa[2] = (( 335779.526232 + ( 295262.8478 + ( -12.7512 + ( -0.001037 + ( 0.00000417) * t) * t) * t) * t) * ASEC2RAD + (1342.0*t % 1.0) * tau) # Mean Elongation of the Moon from the Sun. fa[3] = ((1072260.703692 + (1105601.2090 + ( -6.3706 + ( 0.006593 + ( -0.00003169) * t) * t) * t) * t) * ASEC2RAD + (1236.0*t % 1.0) * tau) # Mean Longitude of the Ascending Node of the Moon. fa[4] = (( 450160.398036 + (-482890.5431 + ( 7.4722 + ( 0.007702 + ( -0.00005939) * t) * t) * t) * t) * ASEC2RAD + (-5.0*t % 1.0) * tau) fa[ 5] = (4.402608842 + 2608.7903141574 * t) fa[ 6] = (3.176146697 + 1021.3285546211 * t) fa[ 7] = (1.753470314 + 628.3075849991 * t) fa[ 8] = (6.203480913 + 334.0612426700 * t) fa[ 9] = (0.599546497 + 52.9690962641 * t) fa[10] = (0.874016757 + 21.3299104960 * t) fa[11] = (5.481293872 + 7.4781598567 * t) fa[12] = (5.311886287 + 3.8133035638 * t) fa[13] = (0.024381750 + 0.00000538691 * t) * t fa %= tau # Evaluate the complementary terms. a = ke0_t.dot(fa) s0 = se0_t_0.dot(sin(a)) + se0_t_1.dot(cos(a)) a = ke1.dot(fa) s1 = se1_0 * sin(a) + se1_1 * cos(a) c_terms = s0 + s1 * t c_terms *= ASEC2RAD return c_terms
python
def equation_of_the_equinoxes_complimentary_terms(jd_tt): # Interval between fundamental epoch J2000.0 and current date. t = (jd_tt - T0) / 36525.0 # Build array for intermediate results. shape = getattr(jd_tt, 'shape', ()) fa = zeros((14,) if shape == () else (14, shape[0])) # Mean Anomaly of the Moon. fa[0] = ((485868.249036 + (715923.2178 + ( 31.8792 + ( 0.051635 + ( -0.00024470) * t) * t) * t) * t) * ASEC2RAD + (1325.0*t % 1.0) * tau) # Mean Anomaly of the Sun. fa[1] = ((1287104.793048 + (1292581.0481 + ( -0.5532 + ( +0.000136 + ( -0.00001149) * t) * t) * t) * t) * ASEC2RAD + (99.0*t % 1.0) * tau) # Mean Longitude of the Moon minus Mean Longitude of the Ascending # Node of the Moon. fa[2] = (( 335779.526232 + ( 295262.8478 + ( -12.7512 + ( -0.001037 + ( 0.00000417) * t) * t) * t) * t) * ASEC2RAD + (1342.0*t % 1.0) * tau) # Mean Elongation of the Moon from the Sun. fa[3] = ((1072260.703692 + (1105601.2090 + ( -6.3706 + ( 0.006593 + ( -0.00003169) * t) * t) * t) * t) * ASEC2RAD + (1236.0*t % 1.0) * tau) # Mean Longitude of the Ascending Node of the Moon. fa[4] = (( 450160.398036 + (-482890.5431 + ( 7.4722 + ( 0.007702 + ( -0.00005939) * t) * t) * t) * t) * ASEC2RAD + (-5.0*t % 1.0) * tau) fa[ 5] = (4.402608842 + 2608.7903141574 * t) fa[ 6] = (3.176146697 + 1021.3285546211 * t) fa[ 7] = (1.753470314 + 628.3075849991 * t) fa[ 8] = (6.203480913 + 334.0612426700 * t) fa[ 9] = (0.599546497 + 52.9690962641 * t) fa[10] = (0.874016757 + 21.3299104960 * t) fa[11] = (5.481293872 + 7.4781598567 * t) fa[12] = (5.311886287 + 3.8133035638 * t) fa[13] = (0.024381750 + 0.00000538691 * t) * t fa %= tau # Evaluate the complementary terms. a = ke0_t.dot(fa) s0 = se0_t_0.dot(sin(a)) + se0_t_1.dot(cos(a)) a = ke1.dot(fa) s1 = se1_0 * sin(a) + se1_1 * cos(a) c_terms = s0 + s1 * t c_terms *= ASEC2RAD return c_terms
[ "def", "equation_of_the_equinoxes_complimentary_terms", "(", "jd_tt", ")", ":", "# Interval between fundamental epoch J2000.0 and current date.", "t", "=", "(", "jd_tt", "-", "T0", ")", "/", "36525.0", "# Build array for intermediate results.", "shape", "=", "getattr", "(", ...
Compute the complementary terms of the equation of the equinoxes. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
[ "Compute", "the", "complementary", "terms", "of", "the", "equation", "of", "the", "equinoxes", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L101-L189
243,784
skyfielders/python-skyfield
skyfield/nutationlib.py
iau2000a
def iau2000a(jd_tt): """Compute Earth nutation based on the IAU 2000A nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each value is either a float, or a NumPy array with the same dimensions as the input argument. """ # Interval between fundamental epoch J2000.0 and given date. t = (jd_tt - T0) / 36525.0 # Compute fundamental arguments from Simon et al. (1994), in radians. a = fundamental_arguments(t) # ** Luni-solar nutation ** # Summation of luni-solar nutation series (in reverse order). arg = nals_t.dot(a) fmod(arg, tau, out=arg) sarg = sin(arg) carg = cos(arg) stsc = array((sarg, t * sarg, carg)).T ctcs = array((carg, t * carg, sarg)).T dpsi = tensordot(stsc, lunisolar_longitude_coefficients) deps = tensordot(ctcs, lunisolar_obliquity_coefficients) # Compute and add in planetary components. if getattr(t, 'shape', ()) == (): a = t * anomaly_coefficient + anomaly_constant else: a = (outer(anomaly_coefficient, t).T + anomaly_constant).T a[-1] *= t fmod(a, tau, out=a) arg = napl_t.dot(a) fmod(arg, tau, out=arg) sc = array((sin(arg), cos(arg))).T dpsi += tensordot(sc, nutation_coefficients_longitude) deps += tensordot(sc, nutation_coefficients_obliquity) return dpsi, deps
python
def iau2000a(jd_tt): # Interval between fundamental epoch J2000.0 and given date. t = (jd_tt - T0) / 36525.0 # Compute fundamental arguments from Simon et al. (1994), in radians. a = fundamental_arguments(t) # ** Luni-solar nutation ** # Summation of luni-solar nutation series (in reverse order). arg = nals_t.dot(a) fmod(arg, tau, out=arg) sarg = sin(arg) carg = cos(arg) stsc = array((sarg, t * sarg, carg)).T ctcs = array((carg, t * carg, sarg)).T dpsi = tensordot(stsc, lunisolar_longitude_coefficients) deps = tensordot(ctcs, lunisolar_obliquity_coefficients) # Compute and add in planetary components. if getattr(t, 'shape', ()) == (): a = t * anomaly_coefficient + anomaly_constant else: a = (outer(anomaly_coefficient, t).T + anomaly_constant).T a[-1] *= t fmod(a, tau, out=a) arg = napl_t.dot(a) fmod(arg, tau, out=arg) sc = array((sin(arg), cos(arg))).T dpsi += tensordot(sc, nutation_coefficients_longitude) deps += tensordot(sc, nutation_coefficients_obliquity) return dpsi, deps
[ "def", "iau2000a", "(", "jd_tt", ")", ":", "# Interval between fundamental epoch J2000.0 and given date.", "t", "=", "(", "jd_tt", "-", "T0", ")", "/", "36525.0", "# Compute fundamental arguments from Simon et al. (1994), in radians.", "a", "=", "fundamental_arguments", "(", ...
Compute Earth nutation based on the IAU 2000A nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each value is either a float, or a NumPy array with the same dimensions as the input argument.
[ "Compute", "Earth", "nutation", "based", "on", "the", "IAU", "2000A", "nutation", "model", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L222-L271
243,785
skyfielders/python-skyfield
skyfield/nutationlib.py
iau2000b
def iau2000b(jd_tt): """Compute Earth nutation based on the faster IAU 2000B nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each is either a float, or a NumPy array with the same dimensions as the input argument. The result will not take as long to compute as the full IAU 2000A series, but should still agree with ``iau2000a()`` to within a milliarcsecond between the years 1995 and 2020. """ dpplan = -0.000135 * 1e7 deplan = 0.000388 * 1e7 t = (jd_tt - T0) / 36525.0 # TODO: can these be replaced with fa0 and f1? el = fmod (485868.249036 + t * 1717915923.2178, ASEC360) * ASEC2RAD; elp = fmod (1287104.79305 + t * 129596581.0481, ASEC360) * ASEC2RAD; f = fmod (335779.526232 + t * 1739527262.8478, ASEC360) * ASEC2RAD; d = fmod (1072260.70369 + t * 1602961601.2090, ASEC360) * ASEC2RAD; om = fmod (450160.398036 - t * 6962890.5431, ASEC360) * ASEC2RAD; a = array((el, elp, f, d, om)) arg = nals_t[:77].dot(a) fmod(arg, tau, out=arg) sarg = sin(arg) carg = cos(arg) stsc = array((sarg, t * sarg, carg)).T ctcs = array((carg, t * carg, sarg)).T dp = tensordot(stsc, lunisolar_longitude_coefficients[:77,]) de = tensordot(ctcs, lunisolar_obliquity_coefficients[:77,]) dpsi = dpplan + dp deps = deplan + de return dpsi, deps
python
def iau2000b(jd_tt): dpplan = -0.000135 * 1e7 deplan = 0.000388 * 1e7 t = (jd_tt - T0) / 36525.0 # TODO: can these be replaced with fa0 and f1? el = fmod (485868.249036 + t * 1717915923.2178, ASEC360) * ASEC2RAD; elp = fmod (1287104.79305 + t * 129596581.0481, ASEC360) * ASEC2RAD; f = fmod (335779.526232 + t * 1739527262.8478, ASEC360) * ASEC2RAD; d = fmod (1072260.70369 + t * 1602961601.2090, ASEC360) * ASEC2RAD; om = fmod (450160.398036 - t * 6962890.5431, ASEC360) * ASEC2RAD; a = array((el, elp, f, d, om)) arg = nals_t[:77].dot(a) fmod(arg, tau, out=arg) sarg = sin(arg) carg = cos(arg) stsc = array((sarg, t * sarg, carg)).T ctcs = array((carg, t * carg, sarg)).T dp = tensordot(stsc, lunisolar_longitude_coefficients[:77,]) de = tensordot(ctcs, lunisolar_obliquity_coefficients[:77,]) dpsi = dpplan + dp deps = deplan + de return dpsi, deps
[ "def", "iau2000b", "(", "jd_tt", ")", ":", "dpplan", "=", "-", "0.000135", "*", "1e7", "deplan", "=", "0.000388", "*", "1e7", "t", "=", "(", "jd_tt", "-", "T0", ")", "/", "36525.0", "# TODO: can these be replaced with fa0 and f1?", "el", "=", "fmod", "(", ...
Compute Earth nutation based on the faster IAU 2000B nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each is either a float, or a NumPy array with the same dimensions as the input argument. The result will not take as long to compute as the full IAU 2000A series, but should still agree with ``iau2000a()`` to within a milliarcsecond between the years 1995 and 2020.
[ "Compute", "Earth", "nutation", "based", "on", "the", "faster", "IAU", "2000B", "nutation", "model", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L273-L325
243,786
skyfielders/python-skyfield
skyfield/data/hipparcos.py
load_dataframe
def load_dataframe(fobj, compression='gzip'): """Given an open file for `hip_main.dat.gz`, return a parsed dataframe. If your copy of ``hip_main.dat`` has already been unzipped, pass the optional argument ``compression=None``. """ try: from pandas import read_fwf except ImportError: raise ImportError(PANDAS_MESSAGE) names, colspecs = zip( ('hip', (2, 14)), ('magnitude', (41, 46)), ('ra_degrees', (51, 63)), ('dec_degrees', (64, 76)), ('parallax_mas', (79, 86)), # TODO: have Star load this ('ra_mas_per_year', (87, 95)), ('dec_mas_per_year', (96, 104)), ) df = read_fwf(fobj, colspecs, names=names, compression=compression) df = df.assign( ra_hours = df['ra_degrees'] / 15.0, epoch_year = 1991.25, ) return df.set_index('hip')
python
def load_dataframe(fobj, compression='gzip'): try: from pandas import read_fwf except ImportError: raise ImportError(PANDAS_MESSAGE) names, colspecs = zip( ('hip', (2, 14)), ('magnitude', (41, 46)), ('ra_degrees', (51, 63)), ('dec_degrees', (64, 76)), ('parallax_mas', (79, 86)), # TODO: have Star load this ('ra_mas_per_year', (87, 95)), ('dec_mas_per_year', (96, 104)), ) df = read_fwf(fobj, colspecs, names=names, compression=compression) df = df.assign( ra_hours = df['ra_degrees'] / 15.0, epoch_year = 1991.25, ) return df.set_index('hip')
[ "def", "load_dataframe", "(", "fobj", ",", "compression", "=", "'gzip'", ")", ":", "try", ":", "from", "pandas", "import", "read_fwf", "except", "ImportError", ":", "raise", "ImportError", "(", "PANDAS_MESSAGE", ")", "names", ",", "colspecs", "=", "zip", "("...
Given an open file for `hip_main.dat.gz`, return a parsed dataframe. If your copy of ``hip_main.dat`` has already been unzipped, pass the optional argument ``compression=None``.
[ "Given", "an", "open", "file", "for", "hip_main", ".", "dat", ".", "gz", "return", "a", "parsed", "dataframe", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/data/hipparcos.py#L44-L71
243,787
skyfielders/python-skyfield
skyfield/toposlib.py
Topos._altaz_rotation
def _altaz_rotation(self, t): """Compute the rotation from the ICRF into the alt-az system.""" R_lon = rot_z(- self.longitude.radians - t.gast * tau / 24.0) return einsum('ij...,jk...,kl...->il...', self.R_lat, R_lon, t.M)
python
def _altaz_rotation(self, t): R_lon = rot_z(- self.longitude.radians - t.gast * tau / 24.0) return einsum('ij...,jk...,kl...->il...', self.R_lat, R_lon, t.M)
[ "def", "_altaz_rotation", "(", "self", ",", "t", ")", ":", "R_lon", "=", "rot_z", "(", "-", "self", ".", "longitude", ".", "radians", "-", "t", ".", "gast", "*", "tau", "/", "24.0", ")", "return", "einsum", "(", "'ij...,jk...,kl...->il...'", ",", "self...
Compute the rotation from the ICRF into the alt-az system.
[ "Compute", "the", "rotation", "from", "the", "ICRF", "into", "the", "alt", "-", "az", "system", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/toposlib.py#L70-L73
243,788
skyfielders/python-skyfield
skyfield/toposlib.py
Topos._at
def _at(self, t): """Compute the GCRS position and velocity of this Topos at time `t`.""" pos, vel = terra(self.latitude.radians, self.longitude.radians, self.elevation.au, t.gast) pos = einsum('ij...,j...->i...', t.MT, pos) vel = einsum('ij...,j...->i...', t.MT, vel) if self.x: R = rot_y(self.x * ASEC2RAD) pos = einsum('ij...,j...->i...', R, pos) if self.y: R = rot_x(self.y * ASEC2RAD) pos = einsum('ij...,j...->i...', R, pos) # TODO: also rotate velocity return pos, vel, pos, None
python
def _at(self, t): pos, vel = terra(self.latitude.radians, self.longitude.radians, self.elevation.au, t.gast) pos = einsum('ij...,j...->i...', t.MT, pos) vel = einsum('ij...,j...->i...', t.MT, vel) if self.x: R = rot_y(self.x * ASEC2RAD) pos = einsum('ij...,j...->i...', R, pos) if self.y: R = rot_x(self.y * ASEC2RAD) pos = einsum('ij...,j...->i...', R, pos) # TODO: also rotate velocity return pos, vel, pos, None
[ "def", "_at", "(", "self", ",", "t", ")", ":", "pos", ",", "vel", "=", "terra", "(", "self", ".", "latitude", ".", "radians", ",", "self", ".", "longitude", ".", "radians", ",", "self", ".", "elevation", ".", "au", ",", "t", ".", "gast", ")", "...
Compute the GCRS position and velocity of this Topos at time `t`.
[ "Compute", "the", "GCRS", "position", "and", "velocity", "of", "this", "Topos", "at", "time", "t", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/toposlib.py#L75-L89
243,789
skyfielders/python-skyfield
skyfield/elementslib.py
osculating_elements_of
def osculating_elements_of(position, reference_frame=None): """Produce the osculating orbital elements for a position. The ``position`` should be an :class:`~skyfield.positionlib.ICRF` instance like that returned by the ``at()`` method of any Solar System body, specifying a position, a velocity, and a time. An instance of :class:`~skyfield.elementslib.OsculatingElements` is returned. """ mu = GM_dict.get(position.center, 0) + GM_dict.get(position.target, 0) if reference_frame is not None: position_vec = Distance(reference_frame.dot(position.position.au)) velocity_vec = Velocity(reference_frame.dot(position.velocity.au_per_d)) else: position_vec = position.position velocity_vec = position.velocity return OsculatingElements(position_vec, velocity_vec, position.t, mu)
python
def osculating_elements_of(position, reference_frame=None): mu = GM_dict.get(position.center, 0) + GM_dict.get(position.target, 0) if reference_frame is not None: position_vec = Distance(reference_frame.dot(position.position.au)) velocity_vec = Velocity(reference_frame.dot(position.velocity.au_per_d)) else: position_vec = position.position velocity_vec = position.velocity return OsculatingElements(position_vec, velocity_vec, position.t, mu)
[ "def", "osculating_elements_of", "(", "position", ",", "reference_frame", "=", "None", ")", ":", "mu", "=", "GM_dict", ".", "get", "(", "position", ".", "center", ",", "0", ")", "+", "GM_dict", ".", "get", "(", "position", ".", "target", ",", "0", ")",...
Produce the osculating orbital elements for a position. The ``position`` should be an :class:`~skyfield.positionlib.ICRF` instance like that returned by the ``at()`` method of any Solar System body, specifying a position, a velocity, and a time. An instance of :class:`~skyfield.elementslib.OsculatingElements` is returned.
[ "Produce", "the", "osculating", "orbital", "elements", "for", "a", "position", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/elementslib.py#L12-L34
243,790
skyfielders/python-skyfield
skyfield/sgp4lib.py
theta_GMST1982
def theta_GMST1982(jd_ut1): """Return the angle of Greenwich Mean Standard Time 1982 given the JD. This angle defines the difference between the idiosyncratic True Equator Mean Equinox (TEME) frame of reference used by SGP4 and the more standard Pseudo Earth Fixed (PEF) frame of reference. From AIAA 2006-6753 Appendix C. """ t = (jd_ut1 - T0) / 36525.0 g = 67310.54841 + (8640184.812866 + (0.093104 + (-6.2e-6) * t) * t) * t dg = 8640184.812866 + (0.093104 * 2.0 + (-6.2e-6 * 3.0) * t) * t theta = (jd_ut1 % 1.0 + g * _second % 1.0) * tau theta_dot = (1.0 + dg * _second / 36525.0) * tau return theta, theta_dot
python
def theta_GMST1982(jd_ut1): t = (jd_ut1 - T0) / 36525.0 g = 67310.54841 + (8640184.812866 + (0.093104 + (-6.2e-6) * t) * t) * t dg = 8640184.812866 + (0.093104 * 2.0 + (-6.2e-6 * 3.0) * t) * t theta = (jd_ut1 % 1.0 + g * _second % 1.0) * tau theta_dot = (1.0 + dg * _second / 36525.0) * tau return theta, theta_dot
[ "def", "theta_GMST1982", "(", "jd_ut1", ")", ":", "t", "=", "(", "jd_ut1", "-", "T0", ")", "/", "36525.0", "g", "=", "67310.54841", "+", "(", "8640184.812866", "+", "(", "0.093104", "+", "(", "-", "6.2e-6", ")", "*", "t", ")", "*", "t", ")", "*",...
Return the angle of Greenwich Mean Standard Time 1982 given the JD. This angle defines the difference between the idiosyncratic True Equator Mean Equinox (TEME) frame of reference used by SGP4 and the more standard Pseudo Earth Fixed (PEF) frame of reference. From AIAA 2006-6753 Appendix C.
[ "Return", "the", "angle", "of", "Greenwich", "Mean", "Standard", "Time", "1982", "given", "the", "JD", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/sgp4lib.py#L160-L175
243,791
skyfielders/python-skyfield
skyfield/sgp4lib.py
TEME_to_ITRF
def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0): """Convert TEME position and velocity into standard ITRS coordinates. This converts a position and velocity vector in the idiosyncratic True Equator Mean Equinox (TEME) frame of reference used by the SGP4 theory into vectors into the more standard ITRS frame of reference. The velocity should be provided in units per day, not per second. From AIAA 2006-6753 Appendix C. """ theta, theta_dot = theta_GMST1982(jd_ut1) zero = theta_dot * 0.0 angular_velocity = array([zero, zero, -theta_dot]) R = rot_z(-theta) if len(rTEME.shape) == 1: rPEF = (R).dot(rTEME) vPEF = (R).dot(vTEME) + cross(angular_velocity, rPEF) else: rPEF = einsum('ij...,j...->i...', R, rTEME) vPEF = einsum('ij...,j...->i...', R, vTEME) + cross( angular_velocity, rPEF, 0, 0).T if xp == 0.0 and yp == 0.0: rITRF = rPEF vITRF = vPEF else: W = (rot_x(yp)).dot(rot_y(xp)) rITRF = (W).dot(rPEF) vITRF = (W).dot(vPEF) return rITRF, vITRF
python
def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0): theta, theta_dot = theta_GMST1982(jd_ut1) zero = theta_dot * 0.0 angular_velocity = array([zero, zero, -theta_dot]) R = rot_z(-theta) if len(rTEME.shape) == 1: rPEF = (R).dot(rTEME) vPEF = (R).dot(vTEME) + cross(angular_velocity, rPEF) else: rPEF = einsum('ij...,j...->i...', R, rTEME) vPEF = einsum('ij...,j...->i...', R, vTEME) + cross( angular_velocity, rPEF, 0, 0).T if xp == 0.0 and yp == 0.0: rITRF = rPEF vITRF = vPEF else: W = (rot_x(yp)).dot(rot_y(xp)) rITRF = (W).dot(rPEF) vITRF = (W).dot(vPEF) return rITRF, vITRF
[ "def", "TEME_to_ITRF", "(", "jd_ut1", ",", "rTEME", ",", "vTEME", ",", "xp", "=", "0.0", ",", "yp", "=", "0.0", ")", ":", "theta", ",", "theta_dot", "=", "theta_GMST1982", "(", "jd_ut1", ")", "zero", "=", "theta_dot", "*", "0.0", "angular_velocity", "=...
Convert TEME position and velocity into standard ITRS coordinates. This converts a position and velocity vector in the idiosyncratic True Equator Mean Equinox (TEME) frame of reference used by the SGP4 theory into vectors into the more standard ITRS frame of reference. The velocity should be provided in units per day, not per second. From AIAA 2006-6753 Appendix C.
[ "Convert", "TEME", "position", "and", "velocity", "into", "standard", "ITRS", "coordinates", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/sgp4lib.py#L177-L208
243,792
skyfielders/python-skyfield
skyfield/sgp4lib.py
EarthSatellite.ITRF_position_velocity_error
def ITRF_position_velocity_error(self, t): """Return the ITRF position, velocity, and error at time `t`. The position is an x,y,z vector measured in au, the velocity is an x,y,z vector measured in au/day, and the error is a vector of possible error messages for the time or vector of times `t`. """ rTEME, vTEME, error = self._position_and_velocity_TEME_km(t) rTEME /= AU_KM vTEME /= AU_KM vTEME *= DAY_S rITRF, vITRF = TEME_to_ITRF(t.ut1, rTEME, vTEME) return rITRF, vITRF, error
python
def ITRF_position_velocity_error(self, t): rTEME, vTEME, error = self._position_and_velocity_TEME_km(t) rTEME /= AU_KM vTEME /= AU_KM vTEME *= DAY_S rITRF, vITRF = TEME_to_ITRF(t.ut1, rTEME, vTEME) return rITRF, vITRF, error
[ "def", "ITRF_position_velocity_error", "(", "self", ",", "t", ")", ":", "rTEME", ",", "vTEME", ",", "error", "=", "self", ".", "_position_and_velocity_TEME_km", "(", "t", ")", "rTEME", "/=", "AU_KM", "vTEME", "/=", "AU_KM", "vTEME", "*=", "DAY_S", "rITRF", ...
Return the ITRF position, velocity, and error at time `t`. The position is an x,y,z vector measured in au, the velocity is an x,y,z vector measured in au/day, and the error is a vector of possible error messages for the time or vector of times `t`.
[ "Return", "the", "ITRF", "position", "velocity", "and", "error", "at", "time", "t", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/sgp4lib.py#L136-L149
243,793
skyfielders/python-skyfield
skyfield/sgp4lib.py
EarthSatellite._at
def _at(self, t): """Compute this satellite's GCRS position and velocity at time `t`.""" rITRF, vITRF, error = self.ITRF_position_velocity_error(t) rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF) return rGCRS, vGCRS, rGCRS, error
python
def _at(self, t): rITRF, vITRF, error = self.ITRF_position_velocity_error(t) rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF) return rGCRS, vGCRS, rGCRS, error
[ "def", "_at", "(", "self", ",", "t", ")", ":", "rITRF", ",", "vITRF", ",", "error", "=", "self", ".", "ITRF_position_velocity_error", "(", "t", ")", "rGCRS", ",", "vGCRS", "=", "ITRF_to_GCRS2", "(", "t", ",", "rITRF", ",", "vITRF", ")", "return", "rG...
Compute this satellite's GCRS position and velocity at time `t`.
[ "Compute", "this", "satellite", "s", "GCRS", "position", "and", "velocity", "at", "time", "t", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/sgp4lib.py#L151-L155
243,794
skyfielders/python-skyfield
skyfield/data/earth_orientation.py
morrison_and_stephenson_2004_table
def morrison_and_stephenson_2004_table(): """Table of smoothed Delta T values from Morrison and Stephenson, 2004.""" import pandas as pd f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html') tables = pd.read_html(f.read()) df = tables[0] return pd.DataFrame({'year': df[0], 'delta_t': df[1]})
python
def morrison_and_stephenson_2004_table(): import pandas as pd f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html') tables = pd.read_html(f.read()) df = tables[0] return pd.DataFrame({'year': df[0], 'delta_t': df[1]})
[ "def", "morrison_and_stephenson_2004_table", "(", ")", ":", "import", "pandas", "as", "pd", "f", "=", "load", ".", "open", "(", "'http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html'", ")", "tables", "=", "pd", ".", "read_html", "(", "f", ".", "read", "(", ")", ")...
Table of smoothed Delta T values from Morrison and Stephenson, 2004.
[ "Table", "of", "smoothed", "Delta", "T", "values", "from", "Morrison", "and", "Stephenson", "2004", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/data/earth_orientation.py#L8-L14
243,795
skyfielders/python-skyfield
skyfield/functions.py
angle_between
def angle_between(u_vec, v_vec): """Given 2 vectors in `v` and `u`, return the angle separating them. This works whether `v` and `u` each have the shape ``(3,)``, or whether they are each whole arrays of corresponding x, y, and z coordinates and have shape ``(3, N)``. The returned angle will be between 0 and 180 degrees. This formula is from Section 12 of: https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf """ u = length_of(u_vec) v = length_of(v_vec) num = v*u_vec - u*v_vec denom = v*u_vec + u*v_vec return 2*arctan2(length_of(num), length_of(denom))
python
def angle_between(u_vec, v_vec): u = length_of(u_vec) v = length_of(v_vec) num = v*u_vec - u*v_vec denom = v*u_vec + u*v_vec return 2*arctan2(length_of(num), length_of(denom))
[ "def", "angle_between", "(", "u_vec", ",", "v_vec", ")", ":", "u", "=", "length_of", "(", "u_vec", ")", "v", "=", "length_of", "(", "v_vec", ")", "num", "=", "v", "*", "u_vec", "-", "u", "*", "v_vec", "denom", "=", "v", "*", "u_vec", "+", "u", ...
Given 2 vectors in `v` and `u`, return the angle separating them. This works whether `v` and `u` each have the shape ``(3,)``, or whether they are each whole arrays of corresponding x, y, and z coordinates and have shape ``(3, N)``. The returned angle will be between 0 and 180 degrees. This formula is from Section 12 of: https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf
[ "Given", "2", "vectors", "in", "v", "and", "u", "return", "the", "angle", "separating", "them", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/functions.py#L26-L42
243,796
skyfielders/python-skyfield
skyfield/starlib.py
Star._compute_vectors
def _compute_vectors(self): """Compute the star's position as an ICRF position and velocity.""" # Use 1 gigaparsec for stars whose parallax is zero. parallax = self.parallax_mas if parallax <= 0.0: parallax = 1.0e-6 # Convert right ascension, declination, and parallax to position # vector in equatorial system with units of au. dist = 1.0 / sin(parallax * 1.0e-3 * ASEC2RAD) r = self.ra.radians d = self.dec.radians cra = cos(r) sra = sin(r) cdc = cos(d) sdc = sin(d) self._position_au = array(( dist * cdc * cra, dist * cdc * sra, dist * sdc, )) # Compute Doppler factor, which accounts for change in light # travel time to star. k = 1.0 / (1.0 - self.radial_km_per_s / C * 1000.0) # Convert proper motion and radial velocity to orthogonal # components of motion with units of au/day. pmr = self.ra_mas_per_year / (parallax * 365.25) * k pmd = self.dec_mas_per_year / (parallax * 365.25) * k rvl = self.radial_km_per_s * DAY_S / self.au_km * k # Transform motion vector to equatorial system. self._velocity_au_per_d = array(( - pmr * sra - pmd * sdc * cra + rvl * cdc * cra, pmr * cra - pmd * sdc * sra + rvl * cdc * sra, pmd * cdc + rvl * sdc, ))
python
def _compute_vectors(self): # Use 1 gigaparsec for stars whose parallax is zero. parallax = self.parallax_mas if parallax <= 0.0: parallax = 1.0e-6 # Convert right ascension, declination, and parallax to position # vector in equatorial system with units of au. dist = 1.0 / sin(parallax * 1.0e-3 * ASEC2RAD) r = self.ra.radians d = self.dec.radians cra = cos(r) sra = sin(r) cdc = cos(d) sdc = sin(d) self._position_au = array(( dist * cdc * cra, dist * cdc * sra, dist * sdc, )) # Compute Doppler factor, which accounts for change in light # travel time to star. k = 1.0 / (1.0 - self.radial_km_per_s / C * 1000.0) # Convert proper motion and radial velocity to orthogonal # components of motion with units of au/day. pmr = self.ra_mas_per_year / (parallax * 365.25) * k pmd = self.dec_mas_per_year / (parallax * 365.25) * k rvl = self.radial_km_per_s * DAY_S / self.au_km * k # Transform motion vector to equatorial system. self._velocity_au_per_d = array(( - pmr * sra - pmd * sdc * cra + rvl * cdc * cra, pmr * cra - pmd * sdc * sra + rvl * cdc * sra, pmd * cdc + rvl * sdc, ))
[ "def", "_compute_vectors", "(", "self", ")", ":", "# Use 1 gigaparsec for stars whose parallax is zero.", "parallax", "=", "self", ".", "parallax_mas", "if", "parallax", "<=", "0.0", ":", "parallax", "=", "1.0e-6", "# Convert right ascension, declination, and parallax to posi...
Compute the star's position as an ICRF position and velocity.
[ "Compute", "the", "star", "s", "position", "as", "an", "ICRF", "position", "and", "velocity", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/starlib.py#L126-L170
243,797
skyfielders/python-skyfield
skyfield/units.py
_to_array
def _to_array(value): """As a convenience, turn Python lists and tuples into NumPy arrays.""" if isinstance(value, (tuple, list)): return array(value) elif isinstance(value, (float, int)): return np.float64(value) else: return value
python
def _to_array(value): if isinstance(value, (tuple, list)): return array(value) elif isinstance(value, (float, int)): return np.float64(value) else: return value
[ "def", "_to_array", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "array", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "(", "float", ",", "int", ")", ")", ":", "...
As a convenience, turn Python lists and tuples into NumPy arrays.
[ "As", "a", "convenience", "turn", "Python", "lists", "and", "tuples", "into", "NumPy", "arrays", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L12-L19
243,798
skyfielders/python-skyfield
skyfield/units.py
_sexagesimalize_to_float
def _sexagesimalize_to_float(value): """Decompose `value` into units, minutes, and seconds. Note that this routine is not appropriate for displaying a value, because rounding to the smallest digit of display is necessary before showing a value to the user. Use `_sexagesimalize_to_int()` for data being displayed to the user. This routine simply decomposes the floating point `value` into a sign (+1.0 or -1.0), units, minutes, and seconds, returning the result in a four-element tuple. >>> _sexagesimalize_to_float(12.05125) (1.0, 12.0, 3.0, 4.5) >>> _sexagesimalize_to_float(-12.05125) (-1.0, 12.0, 3.0, 4.5) """ sign = np.sign(value) n = abs(value) minutes, seconds = divmod(n * 3600.0, 60.0) units, minutes = divmod(minutes, 60.0) return sign, units, minutes, seconds
python
def _sexagesimalize_to_float(value): sign = np.sign(value) n = abs(value) minutes, seconds = divmod(n * 3600.0, 60.0) units, minutes = divmod(minutes, 60.0) return sign, units, minutes, seconds
[ "def", "_sexagesimalize_to_float", "(", "value", ")", ":", "sign", "=", "np", ".", "sign", "(", "value", ")", "n", "=", "abs", "(", "value", ")", "minutes", ",", "seconds", "=", "divmod", "(", "n", "*", "3600.0", ",", "60.0", ")", "units", ",", "mi...
Decompose `value` into units, minutes, and seconds. Note that this routine is not appropriate for displaying a value, because rounding to the smallest digit of display is necessary before showing a value to the user. Use `_sexagesimalize_to_int()` for data being displayed to the user. This routine simply decomposes the floating point `value` into a sign (+1.0 or -1.0), units, minutes, and seconds, returning the result in a four-element tuple. >>> _sexagesimalize_to_float(12.05125) (1.0, 12.0, 3.0, 4.5) >>> _sexagesimalize_to_float(-12.05125) (-1.0, 12.0, 3.0, 4.5)
[ "Decompose", "value", "into", "units", "minutes", "and", "seconds", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L310-L332
243,799
skyfielders/python-skyfield
skyfield/units.py
_sexagesimalize_to_int
def _sexagesimalize_to_int(value, places=0): """Decompose `value` into units, minutes, seconds, and second fractions. This routine prepares a value for sexagesimal display, with its seconds fraction expressed as an integer with `places` digits. The result is a tuple of five integers: ``(sign [either +1 or -1], units, minutes, seconds, second_fractions)`` The integers are properly rounded per astronomical convention so that, for example, given ``places=3`` the result tuple ``(1, 11, 22, 33, 444)`` means that the input was closer to 11u 22' 33.444" than to either 33.443" or 33.445" in its value. """ sign = int(np.sign(value)) value = abs(value) power = 10 ** places n = int(7200 * power * value + 1) // 2 n, fraction = divmod(n, power) n, seconds = divmod(n, 60) n, minutes = divmod(n, 60) return sign, n, minutes, seconds, fraction
python
def _sexagesimalize_to_int(value, places=0): sign = int(np.sign(value)) value = abs(value) power = 10 ** places n = int(7200 * power * value + 1) // 2 n, fraction = divmod(n, power) n, seconds = divmod(n, 60) n, minutes = divmod(n, 60) return sign, n, minutes, seconds, fraction
[ "def", "_sexagesimalize_to_int", "(", "value", ",", "places", "=", "0", ")", ":", "sign", "=", "int", "(", "np", ".", "sign", "(", "value", ")", ")", "value", "=", "abs", "(", "value", ")", "power", "=", "10", "**", "places", "n", "=", "int", "("...
Decompose `value` into units, minutes, seconds, and second fractions. This routine prepares a value for sexagesimal display, with its seconds fraction expressed as an integer with `places` digits. The result is a tuple of five integers: ``(sign [either +1 or -1], units, minutes, seconds, second_fractions)`` The integers are properly rounded per astronomical convention so that, for example, given ``places=3`` the result tuple ``(1, 11, 22, 33, 444)`` means that the input was closer to 11u 22' 33.444" than to either 33.443" or 33.445" in its value.
[ "Decompose", "value", "into", "units", "minutes", "seconds", "and", "second", "fractions", "." ]
51d9e042e06457f6b1f2415296d50a38cb3a300f
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L334-L356