INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns a new DateTimeIndex, containing a subslice of the timestamps in this index, as specified by the given integer start and end locations. Parameters ---------- start : int The location of the start of the range, inclusive. end : int The location of t...
def islice(self, start, end): """ Returns a new DateTimeIndex, containing a subslice of the timestamps in this index, as specified by the given integer start and end locations. Parameters ---------- start : int The location of the start of the range, inclusiv...
Fit an autoregressive model with additional exogenous variables. The model predicts a value at time t of a dependent variable, Y, as a function of previous values of Y, and a combination of previous values of exogenous regressors X_i, and current values of exogenous regressors X_i. This is a generalization ...
def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None): """ Fit an autoregressive model with additional exogenous variables. The model predicts a value at time t of a dependent variable, Y, as a function of previous values of Y, and a combination of previous values of ...
Fits a GARCH(1, 1) model to the given time series. Parameters ---------- ts: the time series to which we want to fit a GARCH model as a Numpy array Returns a GARCH model
def fit_model(ts, sc=None): """ Fits a GARCH(1, 1) model to the given time series. Parameters ---------- ts: the time series to which we want to fit a GARCH model as a Numpy array Returns a GARCH model """ assert sc != None, "Missing SparkContext" jvm = sc....
Find the gradient of the log likelihood with respect to the given time series. Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf Returns an 3-element array containing the gradient for the alpha, beta, and omega parameters.
def gradient(self, ts): """ Find the gradient of the log likelihood with respect to the given time series. Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf Returns an 3-element array containing the gradient for the alpha, beta, and omega parameters. ...
Returns the log likelihood of the parameters on the given time series. Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf
def log_likelihood(self, ts): """ Returns the log likelihood of the parameters on the given time series. Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf """ likelihood = self._jmodel.logLikelihood(_py2java(self._ctx, Vectors.dense(ts))) return _java...
Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects. The series in the RDD are all expected to have the same DatetimeIndex. Parameters ---------- series_rdd : RDD of (string, pandas.Series) tuples sc : SparkContext
def time_series_rdd_from_pandas_series_rdd(series_rdd): """ Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects. The series in the RDD are all expected to have the same DatetimeIndex. Parameters ---------- series_rdd : RDD of (string, pandas.Series) tuples sc : SparkContext ...
Instantiates a TimeSeriesRDD from a DataFrame of observations. An observation is a row containing a timestamp, a string key, and float value. Parameters ---------- dt_index : DateTimeIndex The index of the RDD to create. Observations not contained in this index will be ignored. df : DataFr...
def time_series_rdd_from_observations(dt_index, df, ts_col, key_col, val_col): """ Instantiates a TimeSeriesRDD from a DataFrame of observations. An observation is a row containing a timestamp, a string key, and float value. Parameters ---------- dt_index : DateTimeIndex The index of t...
Returns a TimeSeriesRDD where each time series is differenced with the given order. The new RDD will be missing the first n date-times. Parameters ---------- n : int The order of differencing to perform.
def differences(self, n): """ Returns a TimeSeriesRDD where each time series is differenced with the given order. The new RDD will be missing the first n date-times. Parameters ---------- n : int The order of differencing to perform. ...
Returns a TimeSeriesRDD with missing values imputed using the given method. Parameters ---------- method : string "nearest" fills in NaNs with the closest non-NaN value, using the closest previous value in the case of a tie. "linear" does a linear interpolation ...
def fill(self, method): """ Returns a TimeSeriesRDD with missing values imputed using the given method. Parameters ---------- method : string "nearest" fills in NaNs with the closest non-NaN value, using the closest previous value in the case of a...
Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD. Either the series produced by the given function should conform to this TimeSeriesRDD's index, or a new DateTimeIndex should be given that they conform to. Parameters ---------- fn : f...
def map_series(self, fn, dt_index = None): """ Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD. Either the series produced by the given function should conform to this TimeSeriesRDD's index, or a new DateTimeIndex should be given that they conform to...
Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and a numpy array containing all the observations that occurred at that time.
def to_instants(self): """ Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and a numpy array containing all the observations that occurred at that time. """...
Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD.
def to_instants_dataframe(self, sql_ctx): """ Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD. """ ...
Returns a DataFrame of observations, each containing a timestamp, a key, and a value. Parameters ---------- sql_ctx : SQLContext ts_col : string The name for the timestamp column. key_col : string The name for the key column. val_col : string ...
def to_observations_dataframe(self, sql_ctx, ts_col='timestamp', key_col='key', val_col='value'): """ Returns a DataFrame of observations, each containing a timestamp, a key, and a value. Parameters ---------- sql_ctx : SQLContext ts_col : string The name for...
Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes
def to_pandas_series_rdd(self): """ Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes """ pd_index = self.index().to_pandas_index() return self.map(lambda x: (x[0], pd.Series(x[1], pd_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.
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...
Returns a TimeSeriesRDD rebased on top of a new index. Any timestamps that exist in the new index but not in the existing index will be filled in with NaNs. Parameters ---------- new_index : DateTimeIndex
def with_index(self, new_index): """ Returns a TimeSeriesRDD rebased on top of a new index. Any timestamps that exist in the new index but not in the existing index will be filled in with NaNs. Parameters ---------- new_index : DateTimeIndex """ ...
Notification settings. :title: notification title :msg: notification message :icon_path: path to the .ico file to custom notification :duration: delay in seconds before notification self-destruction
def _show_toast(self, title, msg, icon_path, duration): """Notification settings. :title: notification title :msg: notification message :icon_path: path to the .ico file to custom notification :duration: delay in seconds before notification self-destruction ...
Notification settings. :title: notification title :msg: notification message :icon_path: path to the .ico file to custom notification :duration: delay in seconds before notification self-destruction
def show_toast(self, title="Notification", msg="Here comes the message", icon_path=None, duration=5, threaded=False): """Notification settings. :title: notification title :msg: notification message :icon_path: path to the .ico file to custom notification :dur...
Set the row's header from a list.
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 = lis...
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 _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): ...
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: Wh...
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 TextT...
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.
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 r...
Sets table, with column headers and separators.
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 ourselv...
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 lis...
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 i...
Returns whole table, with whitespace padding and row delimiters. Args: width: An int, the max width we want the table to fit in. force_display: A bool, if set to True will display table when the table can't be made to fit to the width. ml_delimiter: A bool, if set to False will not disp...
def FormattedTable(self, width=80, force_display=False, ml_delimiter=True, color=True, display_header=True, columns=None): """Returns whole table, with whitespace padding and row delimiters. Args: width: An int, the max width we want the table to fit in. force_display: A bool, ...
Returns whole table as rows of name/value pairs. One (or more) column entries are used for the row prefix label. The remaining columns are each displayed as a row entry with the prefix labels appended. Use the first column as the label if label_list is None. Args: label_list: A list of pref...
def LabelValueTable(self, label_list=None): """Returns whole table as rows of name/value pairs. One (or more) column entries are used for the row prefix label. The remaining columns are each displayed as a row entry with the prefix labels appended. Use the first column as the label if label_list i...
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.
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) exc...
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.
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 wa...
Executed against each field of each row read from index table.
def _PreParse(self, key, value): """Executed against each field of each row read from index table.""" if key == 'Command': return re.sub(r'(\[\[.+?\]\])', self._Completion, value) else: return value
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)?)?)?)?'.
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 ...
Validate text parsed with FSM or validate an FSM via command line.
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(__...
Returns a list of valid option names.
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
Clear this Value.
def ClearVar(self): """Clear this Value.""" self.value = None # Call OnClearVar on options. _ = [option.OnClearVar() for option in self.options]
Clear this Value.
def ClearAllVar(self): """Clear this Value.""" self.value = None # Call OnClearAllVar on options. _ = [option.OnClearAllVar() for option in self.options]
Fetch the header name of this Value.
def Header(self): """Fetch the header name of this Value.""" # Call OnGetValue on options. _ = [option.OnGetValue() for option in self.options] return self.name
Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error.
def Parse(self, value): """Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error. """ value_line = value.split(' ') if len(value_line) < 3: raise TextFSMTemplat...
Preserves FSM but resets starting state and current record.
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()
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.
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 o...
Returns header.
def _GetHeader(self): """Returns header.""" header = [] for value in self.values: try: header.append(value.Header()) except SkipValue: continue return header
Returns the TextFSMValue object natching the requested name.
def _GetValue(self, name): """Returns the TextFSMValue object natching the requested name.""" for value in self.values: if value.name == name: return value
Adds current record to result if well formed.
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 ...
Parses template file for FSM structure. Args: template: Valid template file. Raises: TextFSMTemplateError: If template file syntax is invalid.
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. ...
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 ...
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 to...
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...
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 rou...
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: TextFSMTemplateErro...
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. Ra...
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. Rai...
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. ...
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 trig...
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 parsin...
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.
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...
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. ...
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...
Returns the list of values that have a particular attribute.
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.OptionNa...
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.
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 d...
Wrap text in ANSI/SGR escape codes. Args: text: String to encase in sgr escape sequence. command_list: List of strings, each string represents an sgr value. e.g. 'fg_blue', 'bg_yellow' reset: Boolean, if to add a reset sequence to the suffix of the text. Returns: String with sgr characters a...
def AnsiText(text, command_list=None, reset=True): """Wrap text in ANSI/SGR escape codes. Args: text: String to encase in sgr escape sequence. command_list: List of strings, each string represents an sgr value. e.g. 'fg_blue', 'bg_yellow' reset: Boolean, if to add a reset sequence to the suffix o...
Enclose ANSI/SGR escape sequences with ANSI_START and ANSI_END.
def EncloseAnsiText(text): """Enclose ANSI/SGR escape sequences with ANSI_START and ANSI_END.""" return sgr_re.sub(lambda x: ANSI_START + x.group(1) + ANSI_END, text)
Returns terminal length and width as a tuple.
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.enviro...
Break line to fit screen width, factoring in ANSI/SGR escape sequences. Args: text: String to line wrap. omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length. Returns: Text with additional line wraps inserted for lines grater than the width.
def LineWrap(text, omit_sgr=False): """Break line to fit screen width, factoring in ANSI/SGR escape sequences. Args: text: String to line wrap. omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length. Returns: Text with additional line wraps inserted for lines grater than the width. """ ...
Routine to page text or determine window size via command line.
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...
Reset the pager to the top of the text.
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
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.
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_li...
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, ...
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 us...
Set attributes to scroll the buffer correctly. Args: lines: An int, number of lines to scroll. If None, scrolls by the terminal length.
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 s...
Prompt the user for the next action. Returns: A string, the character entered by the user.
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 = '' ...
Read a single character from the user. Returns: A string, the character read.
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) ==...
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 Bool...
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 gi...
Returns the difference in light-time, for a star, between the barycenter of the solar system and the observer (or the geocenter).
def light_time_difference(position, observer_position): """Returns the difference in light-time, for a star, between the barycenter of the solar system and the observer (or the geocenter). """ # From 'pos1', form unit vector 'u1' in direction of star or light # source. dis = length_of(...
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 w...
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 `posit...
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...
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 `...
Starting with `code`, follow segments from target to 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
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', ...
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:...
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 ...
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 ...
Search a Loader data structure for a filename.
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: ...
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')
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('~/Downloa...
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.
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(fileob...
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...
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 ...
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]
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(fil...
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 foun...
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...
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 en...
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 ...
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 followi...
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 firs...
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, o...
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 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 ...
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 downl...
simple function to retrieve the header of a BSP file and return SPK object
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) ...
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...
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 the...
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 Sys...
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`` att...
When `value` is a plain Python sequence, return it as a NumPy 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)
Given a proleptic Gregorian calendar date, return a Julian day int.
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 ...
Given a proleptic Gregorian calendar date, return a Julian date float.
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
Convert Julian Day `jd_integer` into a Gregorian (year, month, day).
def calendar_date(jd_integer): """Convert Julian Day `jd_integer` into a Gregorian (year, month, day).""" k = jd_integer + 68569 n = 4 * k // 146097 k = k - (146097 * n + 3) // 4 m = 4000 * (k + 1) // 1461001 k = k - 1461 * m // 4 + 31 month = 80 * k // 2447 day = k - 2447 * month // 8...
Return a (year, month, day, hour, minute, second.fraction) tuple. The `offset` is added to the time before it is split into its components. This is useful if the user is going to round the result before displaying it. If the result is going to be displayed as seconds, for example, set `offset` to hal...
def calendar_tuple(jd_float, offset=0.0): """Return a (year, month, day, hour, minute, second.fraction) tuple. The `offset` is added to the time before it is split into its components. This is useful if the user is going to round the result before displaying it. If the result is going to be displ...
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.
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. ...
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.
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_ar...
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: ...
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 t...
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 ...
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 ...
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)
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 ...
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)
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 =...
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)
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.566406...
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
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 ...
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
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 ...
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
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.56...
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
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 estimat...
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...
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-pa...
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 timezo...
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 ...