sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def name(self): ''' Returns the name of the current :py:class:`Detrender` subclass. ''' if self.cadence == 'lc': return self.__class__.__name__ else: return '%s.sc' % self.__class__.__name__
Returns the name of the current :py:class:`Detrender` subclass.
entailment
def cv_precompute(self, mask, b): ''' Pre-compute the matrices :py:obj:`A` and :py:obj:`B` (cross-validation step only) for chunk :py:obj:`b`. ''' # Get current chunk and mask outliers m1 = self.get_masked_chunk(b) flux = self.fraw[m1] K = GetCov...
Pre-compute the matrices :py:obj:`A` and :py:obj:`B` (cross-validation step only) for chunk :py:obj:`b`.
entailment
def cv_compute(self, b, A, B, C, mK, f, m1, m2): ''' Compute the model (cross-validation step only) for chunk :py:obj:`b`. ''' A = np.sum([l * a for l, a in zip(self.lam[b], A) if l is not None], axis=0) B = np.sum([l * b for l, b in zip(self.lam[b], B) ...
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
entailment
def get_outliers(self): ''' Performs iterative sigma clipping to get outliers. ''' log.info("Clipping outliers...") log.info('Iter %d/%d: %d outliers' % (0, self.oiter, len(self.outmask))) def M(x): return np.delete(x, np.concatenate( [self...
Performs iterative sigma clipping to get outliers.
entailment
def optimize_lambda(self, validation): ''' Returns the index of :py:attr:`self.lambda_arr` that minimizes the validation scatter in the segment with minimum at the lowest value of :py:obj:`lambda`, with fractional tolerance :py:attr:`self.leps`. :param numpy.ndarray vali...
Returns the index of :py:attr:`self.lambda_arr` that minimizes the validation scatter in the segment with minimum at the lowest value of :py:obj:`lambda`, with fractional tolerance :py:attr:`self.leps`. :param numpy.ndarray validation: The scatter in the validation set \ ...
entailment
def cross_validate(self, ax, info=''): ''' Cross-validate to find the optimal value of :py:obj:`lambda`. :param ax: The current :py:obj:`matplotlib.pyplot` axis instance to \ plot the cross-validation results. :param str info: The label to show in the bottom right-hand co...
Cross-validate to find the optimal value of :py:obj:`lambda`. :param ax: The current :py:obj:`matplotlib.pyplot` axis instance to \ plot the cross-validation results. :param str info: The label to show in the bottom right-hand corner \ of the plot. Default `''`
entailment
def get_ylim(self): ''' Computes the ideal y-axis limits for the light curve plot. Attempts to set the limits equal to those of the raw light curve, but if more than 1% of the flux lies either above or below these limits, auto-expands to include those points. At the end, adds 5% ...
Computes the ideal y-axis limits for the light curve plot. Attempts to set the limits equal to those of the raw light curve, but if more than 1% of the flux lies either above or below these limits, auto-expands to include those points. At the end, adds 5% padding to both the top and the ...
entailment
def plot_lc(self, ax, info_left='', info_right='', color='b'): ''' Plots the current light curve. This is called at several stages to plot the de-trending progress as a function of the different *PLD* orders. :param ax: The current :py:obj:`matplotlib.pyplot` axis instance ...
Plots the current light curve. This is called at several stages to plot the de-trending progress as a function of the different *PLD* orders. :param ax: The current :py:obj:`matplotlib.pyplot` axis instance :param str info_left: Information to display at the left of the \ ...
entailment
def plot_final(self, ax): ''' Plots the final de-trended light curve. ''' # Plot the light curve bnmask = np.array( list(set(np.concatenate([self.badmask, self.nanmask]))), dtype=int) def M(x): return np.delete(x, bnmask) if (self.cadence == 'lc') o...
Plots the final de-trended light curve.
entailment
def plot_cbv(self, ax, flux, info, show_cbv=False): ''' Plots the final CBV-corrected light curve. ''' # Plot the light curve bnmask = np.array( list(set(np.concatenate([self.badmask, self.nanmask]))), dtype=int) def M(x): return np.delete(x, bnmask) ...
Plots the final CBV-corrected light curve.
entailment
def load_tpf(self): ''' Loads the target pixel file. ''' if not self.loaded: if self._data is not None: data = self._data else: data = self._mission.GetData( self.ID, season=self.season, ...
Loads the target pixel file.
entailment
def load_model(self, name=None): ''' Loads a saved version of the model. ''' if self.clobber: return False if name is None: name = self.name file = os.path.join(self.dir, '%s.npz' % name) if os.path.exists(file): if not self....
Loads a saved version of the model.
entailment
def save_model(self): ''' Saves all of the de-trending information to disk in an `npz` file and saves the DVS as a `pdf`. ''' # Save the data log.info("Saving data to '%s.npz'..." % self.name) d = dict(self.__dict__) d.pop('_weights', None) d.pop...
Saves all of the de-trending information to disk in an `npz` file and saves the DVS as a `pdf`.
entailment
def exception_handler(self, pdb): ''' A custom exception handler. :param pdb: If :py:obj:`True`, enters PDB post-mortem \ mode for debugging. ''' # Grab the exception exctype, value, tb = sys.exc_info() # Log the error and create a .err file ...
A custom exception handler. :param pdb: If :py:obj:`True`, enters PDB post-mortem \ mode for debugging.
entailment
def update_gp(self): ''' Calls :py:func:`gp.GetKernelParams` to optimize the GP and obtain the covariance matrix for the regression. ''' self.kernel_params = GetKernelParams(self.time, self.flux, self.fraw_err, ...
Calls :py:func:`gp.GetKernelParams` to optimize the GP and obtain the covariance matrix for the regression.
entailment
def init_kernel(self): ''' Initializes the covariance matrix with a guess at the GP kernel parameters. ''' if self.kernel_params is None: X = self.apply_mask(self.fpix / self.flux.reshape(-1, 1)) y = self.apply_mask(self.flux) - np.dot(X, np.linalg.solve...
Initializes the covariance matrix with a guess at the GP kernel parameters.
entailment
def run(self): ''' Runs the de-trending step. ''' try: # Load raw data log.info("Loading target data...") self.load_tpf() self.mask_planets() self.plot_aperture([self.dvs.top_right() for i in range(4)]) self.init_...
Runs the de-trending step.
entailment
def publish(self, **kwargs): ''' Correct the light curve with the CBVs, generate a cover page for the DVS figure, and produce a FITS file for publication. ''' try: # HACK: Force these params for publication self.cbv_win = 999 self.cb...
Correct the light curve with the CBVs, generate a cover page for the DVS figure, and produce a FITS file for publication.
entailment
def setup(self, **kwargs): ''' This is called during production de-trending, prior to calling the :py:obj:`Detrender.run()` method. :param tuple cdpp_range: If :py:obj:`parent_model` is set, \ neighbors are selected only if \ their de-trended CDPPs fall wit...
This is called during production de-trending, prior to calling the :py:obj:`Detrender.run()` method. :param tuple cdpp_range: If :py:obj:`parent_model` is set, \ neighbors are selected only if \ their de-trended CDPPs fall within this range. Default `None` :param t...
entailment
def setup(self, **kwargs): ''' This is called during production de-trending, prior to calling the :py:obj:`Detrender.run()` method. :param str parent_model: The name of the model to operate on. \ Default `nPLD` ''' # Load the parent model self.pa...
This is called during production de-trending, prior to calling the :py:obj:`Detrender.run()` method. :param str parent_model: The name of the model to operate on. \ Default `nPLD`
entailment
def setup(self, **kwargs): ''' This is called during production de-trending, prior to calling the :py:obj:`Detrender.run()` method. :param inter piter: The number of iterations in the minimizer. \ Default 3 :param int pmaxf: The maximum number of function evaluati...
This is called during production de-trending, prior to calling the :py:obj:`Detrender.run()` method. :param inter piter: The number of iterations in the minimizer. \ Default 3 :param int pmaxf: The maximum number of function evaluations per \ iteration. Default 300...
entailment
def run(self): ''' Runs the de-trending. ''' try: # Plot original self.plot_aperture([self.dvs.top_right() for i in range(4)]) self.plot_lc(self.dvs.left(), info_right='nPLD', color='k') # Cross-validate self.cross_validate(...
Runs the de-trending.
entailment
def cross_validate(self, ax): ''' Performs the cross-validation step. ''' # The CDPP to beat cdpp_opt = self.get_cdpp_arr() # Loop over all chunks for b, brkpt in enumerate(self.breakpoints): log.info("Cross-validating chunk %d/%d..." % ...
Performs the cross-validation step.
entailment
def validation_scatter(self, log_lam, b, masks, pre_v, gp, flux, time, med): ''' Computes the scatter in the validation set. ''' # Update the lambda matrix self.lam[b] = 10 ** log_lam # Validation set scatter scatter = [None for i in ...
Computes the scatter in the validation set.
entailment
def populate(datatype='string', size=10, start=None, end=None, converter=None, choice_from=None, **kwargs): '''Utility function for populating lists with random data. Useful for populating database with data for fuzzy testing. Supported data-types * *string* For example:: populat...
Utility function for populating lists with random data. Useful for populating database with data for fuzzy testing. Supported data-types * *string* For example:: populate('string',100, min_len=3, max_len=10) create a 100 elements list with random strings with random length between 3 and...
entailment
def Search(star, pos_tol=2.5, neg_tol=50., **ps_kwargs): ''' NOTE: `pos_tol` is the positive (i.e., above the median) outlier tolerance in standard deviations. NOTE: `neg_tol` is the negative (i.e., below the median) outlier tolerance in standard deviations. ''' # Smooth the light curve ...
NOTE: `pos_tol` is the positive (i.e., above the median) outlier tolerance in standard deviations. NOTE: `neg_tol` is the negative (i.e., below the median) outlier tolerance in standard deviations.
entailment
def iterdirty(self): '''Ordered iterator over dirty elements.''' return iter(chain(itervalues(self._new), itervalues(self._modified)))
Ordered iterator over dirty elements.
entailment
def add(self, instance, modified=True, persistent=None, force_update=False): '''Add a new instance to this :class:`SessionModel`. :param modified: Optional flag indicating if the ``instance`` has been modified. By default its value is ``True``. :param force_update: if ``instance`` is pers...
Add a new instance to this :class:`SessionModel`. :param modified: Optional flag indicating if the ``instance`` has been modified. By default its value is ``True``. :param force_update: if ``instance`` is persistent, it forces an update of the data rather than a full replacement. This is used by the ...
entailment
def delete(self, instance, session): '''delete an *instance*''' if instance._meta.type == 'structure': return self._delete_structure(instance) inst = self.pop(instance) instance = inst if inst is not None else instance if instance is not None: state...
delete an *instance*
entailment
def pop(self, instance): '''Remove ``instance`` from the :class:`SessionModel`. Instance could be a :class:`Model` or an id. :parameter instance: a :class:`Model` or an ``id``. :rtype: the :class:`Model` removed from session or ``None`` if it was not in the session. ''' if isinstance(instan...
Remove ``instance`` from the :class:`SessionModel`. Instance could be a :class:`Model` or an id. :parameter instance: a :class:`Model` or an ``id``. :rtype: the :class:`Model` removed from session or ``None`` if it was not in the session.
entailment
def expunge(self, instance): '''Remove *instance* from the :class:`Session`. Instance could be a :class:`Model` or an id. :parameter instance: a :class:`Model` or an *id* :rtype: the :class:`Model` removed from session or ``None`` if it was not in the session. ''' instance = self.pop(instan...
Remove *instance* from the :class:`Session`. Instance could be a :class:`Model` or an id. :parameter instance: a :class:`Model` or an *id* :rtype: the :class:`Model` removed from session or ``None`` if it was not in the session.
entailment
def post_commit(self, results): '''\ Process results after a commit. :parameter results: iterator over :class:`stdnet.instance_session_result` items. :rtype: a two elements tuple containing a list of instances saved and a list of ids of instances deleted.''' tpy = self._meta.pk_to_pytho...
\ Process results after a commit. :parameter results: iterator over :class:`stdnet.instance_session_result` items. :rtype: a two elements tuple containing a list of instances saved and a list of ids of instances deleted.
entailment
def commit(self, callback=None): '''Close the transaction and commit session to the backend.''' if self.executed: raise InvalidTransaction('Invalid operation. ' 'Transaction already executed.') session = self.session self.session = N...
Close the transaction and commit session to the backend.
entailment
def dirty(self): '''The set of instances in this :class:`Session` which have been modified.''' return frozenset(chain(*tuple((sm.dirty for sm in itervalues(self._models)))))
The set of instances in this :class:`Session` which have been modified.
entailment
def begin(self, **options): '''Begin a new :class:`Transaction`. If this :class:`Session` is already in a :ref:`transactional state <transactional-state>`, an error will occur. It returns the :attr:`transaction` attribute. This method is mostly used within a ``with`` statement block:: with session....
Begin a new :class:`Transaction`. If this :class:`Session` is already in a :ref:`transactional state <transactional-state>`, an error will occur. It returns the :attr:`transaction` attribute. This method is mostly used within a ``with`` statement block:: with session.begin() as t: t.add(...) ...
entailment
def query(self, model, **kwargs): '''Create a new :class:`Query` for *model*.''' sm = self.model(model) query_class = sm.manager.query_class or Query return query_class(sm._meta, self, **kwargs)
Create a new :class:`Query` for *model*.
entailment
def update_or_create(self, model, **kwargs): '''Update or create a new instance of ``model``. This method can raise an exception if the ``kwargs`` dictionary contains field data that does not validate. :param model: a :class:`StdModel` :param kwargs: dictionary of parame...
Update or create a new instance of ``model``. This method can raise an exception if the ``kwargs`` dictionary contains field data that does not validate. :param model: a :class:`StdModel` :param kwargs: dictionary of parameters. :returns: A two elements tuple containing ...
entailment
def add(self, instance, modified=True, **params): '''Add an ``instance`` to the session. If the session is not in a :ref:`transactional state <transactional-state>`, this operation commits changes to the back-end server immediately. :parameter instance: a :class:`Model` ...
Add an ``instance`` to the session. If the session is not in a :ref:`transactional state <transactional-state>`, this operation commits changes to the back-end server immediately. :parameter instance: a :class:`Model` instance. It must be registered with the :attr:`r...
entailment
def delete(self, instance_or_query): '''Delete an ``instance`` or a ``query``. Adds ``instance_or_query`` to this :class:`Session` list of data to be deleted. If the session is not in a :ref:`transactional state <transactional-state>`, this operation commits changes to the...
Delete an ``instance`` or a ``query``. Adds ``instance_or_query`` to this :class:`Session` list of data to be deleted. If the session is not in a :ref:`transactional state <transactional-state>`, this operation commits changes to the backend server immediately. :paramete...
entailment
def model(self, model, create=True): '''Returns the :class:`SessionModel` for ``model`` which can be :class:`Model`, or a :class:`MetaClass`, or an instance of :class:`Model`.''' manager = self.manager(model) sm = self._models.get(manager) if sm is None and create: sm ...
Returns the :class:`SessionModel` for ``model`` which can be :class:`Model`, or a :class:`MetaClass`, or an instance of :class:`Model`.
entailment
def expunge(self, instance=None): '''Remove ``instance`` from this :class:`Session`. If ``instance`` is not given, it removes all instances from this :class:`Session`.''' if instance is not None: sm = self._models.get(instance._meta) if sm: return sm.expunge...
Remove ``instance`` from this :class:`Session`. If ``instance`` is not given, it removes all instances from this :class:`Session`.
entailment
def manager(self, model): '''Retrieve the :class:`Manager` for ``model`` which can be any of the values valid for the :meth:`model` method.''' try: return self.router[model] except KeyError: meta = getattr(model, '_meta', model) if meta.type == 'structu...
Retrieve the :class:`Manager` for ``model`` which can be any of the values valid for the :meth:`model` method.
entailment
def new(self, *args, **kwargs): '''Create a new instance of :attr:`model` and commit it to the backend server. This a shortcut method for the more verbose:: instance = manager.session().add(MyModel(**kwargs)) ''' return self.session().add(self.model(*args, **kwargs))
Create a new instance of :attr:`model` and commit it to the backend server. This a shortcut method for the more verbose:: instance = manager.session().add(MyModel(**kwargs))
entailment
def query(self, session=None): '''Returns a new :class:`Query` for :attr:`Manager.model`.''' if session is None or session.router is not self.router: session = self.session() return session.query(self.model)
Returns a new :class:`Query` for :attr:`Manager.model`.
entailment
def search(self, text, lookup=None): '''Returns a new :class:`Query` for :attr:`Manager.model` with a full text search value.''' return self.query().search(text, lookup=lookup)
Returns a new :class:`Query` for :attr:`Manager.model` with a full text search value.
entailment
def pairs_to_dict(response, encoding): "Create a dict given a list of key/value pairs" it = iter(response) return dict(((k.decode(encoding), v) for k, v in zip(it, it)))
Create a dict given a list of key/value pairs
entailment
def load_related(self, meta, fname, data, fields, encoding): '''Parse data for related objects.''' field = meta.dfields[fname] if field in meta.multifields: fmeta = field.structure_class()._meta if fmeta.name in ('hashtable', 'zset'): return ((native...
Parse data for related objects.
entailment
def _execute_query(self): '''Execute the query without fetching data. Returns the number of elements in the query.''' pipe = self.pipe if not self.card: if self.meta.ordering: self.ismember = getattr(self.backend.client, 'zrank') self.card = get...
Execute the query without fetching data. Returns the number of elements in the query.
entailment
def order(self, last): '''Perform ordering with respect model fields.''' desc = last.desc field = last.name nested = last.nested nested_args = [] while nested: meta = nested.model._meta nested_args.extend((self.backend.basekey(meta), nested...
Perform ordering with respect model fields.
entailment
def related_lua_args(self): '''Generator of load_related arguments''' related = self.queryelem.select_related if related: meta = self.meta for rel in related: field = meta.dfields[rel] relmodel = field.relmodel bk = ...
Generator of load_related arguments
entailment
def ipop_range(self, start, stop=None, withscores=True, **options): '''Remove and return a range from the ordered set by rank (index).''' return self.backend.execute( self.client.zpopbyrank(self.id, start, stop, withscores=withscores, **options), ...
Remove and return a range from the ordered set by rank (index).
entailment
def pop_range(self, start, stop=None, withscores=True, **options): '''Remove and return a range from the ordered set by score.''' return self.backend.execute( self.client.zpopbyscore(self.id, start, stop, withscores=withscores, **options), ...
Remove and return a range from the ordered set by score.
entailment
def meta(self, meta): '''Extract model metadata for lua script stdnet/lib/lua/odm.lua''' data = meta.as_dict() data['namespace'] = self.basekey(meta) return data
Extract model metadata for lua script stdnet/lib/lua/odm.lua
entailment
def execute_session(self, session_data): '''Execute a session in redis.''' pipe = self.client.pipeline() for sm in session_data: # loop through model sessions meta = sm.meta if sm.structures: self.flush_structure(sm, pipe) delquery = No...
Execute a session in redis.
entailment
def flush(self, meta=None): '''Flush all model keys from the database''' pattern = self.basekey(meta) if meta else self.namespace return self.client.delpattern('%s*' % pattern)
Flush all model keys from the database
entailment
def GetCovariance(kernel, kernel_params, time, errors): ''' Returns the covariance matrix for a given light curve segment. :param array_like kernel_params: A list of kernel parameters \ (white noise amplitude, red noise amplitude, and red noise timescale) :param array_like time: The time ...
Returns the covariance matrix for a given light curve segment. :param array_like kernel_params: A list of kernel parameters \ (white noise amplitude, red noise amplitude, and red noise timescale) :param array_like time: The time array (*N*) :param array_like errors: The data error array (*N*)...
entailment
def GetKernelParams(time, flux, errors, kernel='Basic', mask=[], giter=3, gmaxf=200, guess=None): ''' Optimizes the GP by training it on the current de-trended light curve. Returns the white noise amplitude, red noise amplitude, and red noise timescale. :param array_like time: T...
Optimizes the GP by training it on the current de-trended light curve. Returns the white noise amplitude, red noise amplitude, and red noise timescale. :param array_like time: The time array :param array_like flux: The flux array :param array_like errors: The flux errors array :param array_like...
entailment
def NegLnLike(x, time, flux, errors, kernel): ''' Returns the negative log-likelihood function and its gradient. ''' gp = GP(kernel, x, white=True) gp.compute(time, errors) if OLDGEORGE: nll = -gp.lnlikelihood(flux) # NOTE: There was a bug on this next line! Used to be ...
Returns the negative log-likelihood function and its gradient.
entailment
def missing_intervals(startdate, enddate, start, end, dateconverter=None, parseinterval=None, intervals=None): '''Given a ``startdate`` and an ``enddate`` dates, evaluate the date intervals from which data is not available. It return a list of ...
Given a ``startdate`` and an ``enddate`` dates, evaluate the date intervals from which data is not available. It return a list of two-dimensional tuples containing start and end date for the interval. The list could countain 0,1 or 2 tuples.
entailment
def dategenerator(start, end, step=1, desc=False): '''Generates dates between *atrt* and *end*.''' delta = timedelta(abs(step)) end = max(start, end) if desc: dt = end while dt >= start: yield dt dt -= delta else: dt = start while dt...
Generates dates between *atrt* and *end*.
entailment
def InitLog(file_name=None, log_level=logging.DEBUG, screen_level=logging.CRITICAL, pdb=False): ''' A little routine to initialize the logging functionality. :param str file_name: The name of the file to log to. \ Default :py:obj:`None` (set internally by :py:mod:`everest`) :para...
A little routine to initialize the logging functionality. :param str file_name: The name of the file to log to. \ Default :py:obj:`None` (set internally by :py:mod:`everest`) :param int log_level: The file logging level (0-50). Default 10 (debug) :param int screen_level: The screen logging level...
entailment
def ExceptionHook(exctype, value, tb): ''' A custom exception handler that logs errors to file. ''' for line in traceback.format_exception_only(exctype, value): log.error(line.replace('\n', '')) for line in traceback.format_tb(tb): log.error(line.replace('\n', '')) sys.__except...
A custom exception handler that logs errors to file.
entailment
def ExceptionHookPDB(exctype, value, tb): ''' A custom exception handler, with :py:obj:`pdb` post-mortem for debugging. ''' for line in traceback.format_exception_only(exctype, value): log.error(line.replace('\n', '')) for line in traceback.format_tb(tb): log.error(line.replace('\n...
A custom exception handler, with :py:obj:`pdb` post-mortem for debugging.
entailment
def sort_like(l, col1, col2): ''' Sorts the list :py:obj:`l` by comparing :py:obj:`col2` to :py:obj:`col1`. Specifically, finds the indices :py:obj:`i` such that ``col2[i] = col1`` and returns ``l[i]``. This is useful when comparing the CDPP values of catalogs generated by different pipelines. The ...
Sorts the list :py:obj:`l` by comparing :py:obj:`col2` to :py:obj:`col1`. Specifically, finds the indices :py:obj:`i` such that ``col2[i] = col1`` and returns ``l[i]``. This is useful when comparing the CDPP values of catalogs generated by different pipelines. The target IDs are all the same, but won't ...
entailment
def prange(*x): ''' Progress bar range with `tqdm` ''' try: root = logging.getLogger() if len(root.handlers): for h in root.handlers: if (type(h) is logging.StreamHandler) and \ (h.level != logging.CRITICAL): from ...
Progress bar range with `tqdm`
entailment
def front(self, *fields): '''Return the front pair of the structure''' ts = self.irange(0, 0, fields=fields) if ts: return ts.start(), ts[0]
Return the front pair of the structure
entailment
def back(self, *fields): '''Return the back pair of the structure''' ts = self.irange(-1, -1, fields=fields) if ts: return ts.end(), ts[0]
Return the back pair of the structure
entailment
def parse_backend(backend): """Converts the "backend" into the database connection parameters. It returns a (scheme, host, params) tuple.""" r = urlparse.urlsplit(backend) scheme, host = r.scheme, r.netloc path, query = r.path, r.query if path and not query: query, path = path, '' ...
Converts the "backend" into the database connection parameters. It returns a (scheme, host, params) tuple.
entailment
def getdb(backend=None, **kwargs): '''get a :class:`BackendDataServer`.''' if isinstance(backend, BackendDataServer): return backend backend = backend or settings.DEFAULT_BACKEND if not backend: return None scheme, address, params = parse_backend(backend) params.update(kw...
get a :class:`BackendDataServer`.
entailment
def basekey(self, meta, *args): """Calculate the key to access model data. :parameter meta: a :class:`stdnet.odm.Metaclass`. :parameter args: optional list of strings to prepend to the basekey. :rtype: a native string """ key = '%s%s' % (self.namespace, meta.modelkey) postfix = ':'.join...
Calculate the key to access model data. :parameter meta: a :class:`stdnet.odm.Metaclass`. :parameter args: optional list of strings to prepend to the basekey. :rtype: a native string
entailment
def make_objects(self, meta, data, related_fields=None): '''Generator of :class:`stdnet.odm.StdModel` instances with data from database. :parameter meta: instance of model :class:`stdnet.odm.Metaclass`. :parameter data: iterator over instances data. ''' make_object = meta.make_object re...
Generator of :class:`stdnet.odm.StdModel` instances with data from database. :parameter meta: instance of model :class:`stdnet.odm.Metaclass`. :parameter data: iterator over instances data.
entailment
def structure(self, instance, client=None): '''Create a backend :class:`stdnet.odm.Structure` handler. :param instance: a :class:`stdnet.odm.Structure` :param client: Optional client handler. ''' struct = self.struct_map.get(instance._meta.name) if struct is None:...
Create a backend :class:`stdnet.odm.Structure` handler. :param instance: a :class:`stdnet.odm.Structure` :param client: Optional client handler.
entailment
def Search(ID, mission='k2'): """Why is my target not in the EVEREST database?""" # Only K2 supported for now assert mission == 'k2', "Only the K2 mission is supported for now." print("Searching for target %d..." % ID) # First check if it is in the database season = missions.k2.Season(ID) i...
Why is my target not in the EVEREST database?
entailment
def DownloadFile(ID, season=None, mission='k2', cadence='lc', filename=None, clobber=False): ''' Download a given :py:mod:`everest` file from MAST. :param str mission: The mission name. Default `k2` :param str cadence: The light curve cadence. Default `lc` :param str filename: The ...
Download a given :py:mod:`everest` file from MAST. :param str mission: The mission name. Default `k2` :param str cadence: The light curve cadence. Default `lc` :param str filename: The name of the file to download. Default \ :py:obj:`None`, in which case the default \ FITS file is ret...
entailment
def DVS(ID, season=None, mission='k2', clobber=False, cadence='lc', model='nPLD'): ''' Show the data validation summary (DVS) for a given target. :param str mission: The mission name. Default `k2` :param str cadence: The light curve cadence. Default `lc` :param bool clobber: If :py:obj:`Tru...
Show the data validation summary (DVS) for a given target. :param str mission: The mission name. Default `k2` :param str cadence: The light curve cadence. Default `lc` :param bool clobber: If :py:obj:`True`, download and overwrite \ existing files. Default :py:obj:`False`
entailment
def compute(self): ''' Re-compute the :py:mod:`everest` model for the given value of :py:obj:`lambda`. For long cadence `k2` light curves, this should take several seconds. For short cadence `k2` light curves, it may take a few minutes. Note that this is a simple wrapper ...
Re-compute the :py:mod:`everest` model for the given value of :py:obj:`lambda`. For long cadence `k2` light curves, this should take several seconds. For short cadence `k2` light curves, it may take a few minutes. Note that this is a simple wrapper around :py:func:`everest.Baseca...
entailment
def _get_norm(self): ''' Computes the PLD flux normalization array. ..note :: `iPLD` model **only**. ''' log.info('Computing the PLD normalization...') # Loop over all chunks mod = [None for b in self.breakpoints] for b, brkpt in enumerate(self.breakpo...
Computes the PLD flux normalization array. ..note :: `iPLD` model **only**.
entailment
def load_fits(self): ''' Load the FITS file from disk and populate the class instance with its data. ''' log.info("Loading FITS file for %d." % (self.ID)) with pyfits.open(self.fitsfile) as f: # Params and long cadence data self.loaded = True ...
Load the FITS file from disk and populate the class instance with its data.
entailment
def plot_aperture(self, show=True): ''' Plot sample postage stamps for the target with the aperture outline marked, as well as a high-res target image (if available). :param bool show: Show the plot or return the `(fig, ax)` instance? \ Default :py:obj:`True` '''...
Plot sample postage stamps for the target with the aperture outline marked, as well as a high-res target image (if available). :param bool show: Show the plot or return the `(fig, ax)` instance? \ Default :py:obj:`True`
entailment
def plot(self, show=True, plot_raw=True, plot_gp=True, plot_bad=True, plot_out=True, plot_cbv=True, simple=False): ''' Plots the final de-trended light curve. :param bool show: Show the plot or return the `(fig, ax)` instance? \ Default :py:obj:`True` ...
Plots the final de-trended light curve. :param bool show: Show the plot or return the `(fig, ax)` instance? \ Default :py:obj:`True` :param bool plot_raw: Show the raw light curve? Default :py:obj:`True` :param bool plot_gp: Show the GP model prediction? \ Default ...
entailment
def dvs(self): ''' Shows the data validation summary (DVS) for the target. ''' DVS(self.ID, season=self.season, mission=self.mission, model=self.model_name, clobber=self.clobber)
Shows the data validation summary (DVS) for the target.
entailment
def plot_pipeline(self, pipeline, *args, **kwargs): ''' Plots the light curve for the target de-trended with a given pipeline. :param str pipeline: The name of the pipeline (lowercase). Options \ are 'everest2', 'everest1', and other mission-specific \ pipelines. F...
Plots the light curve for the target de-trended with a given pipeline. :param str pipeline: The name of the pipeline (lowercase). Options \ are 'everest2', 'everest1', and other mission-specific \ pipelines. For `K2`, the available pipelines are 'k2sff' \ and 'k2sc'...
entailment
def get_pipeline(self, *args, **kwargs): ''' Returns the `time` and `flux` arrays for the target obtained by a given pipeline. Options :py:obj:`args` and :py:obj:`kwargs` are passed directly to the :py:func:`pipelines.get` function of the mission. ''' return ge...
Returns the `time` and `flux` arrays for the target obtained by a given pipeline. Options :py:obj:`args` and :py:obj:`kwargs` are passed directly to the :py:func:`pipelines.get` function of the mission.
entailment
def mask_planet(self, t0, period, dur=0.2): ''' Mask all of the transits/eclipses of a given planet/EB. After calling this method, you must re-compute the model by calling :py:meth:`compute` in order for the mask to take effect. :param float t0: The time of first transit (same u...
Mask all of the transits/eclipses of a given planet/EB. After calling this method, you must re-compute the model by calling :py:meth:`compute` in order for the mask to take effect. :param float t0: The time of first transit (same units as light curve) :param float period: The period of ...
entailment
def _plot_weights(self, show=True): ''' .. warning:: Untested! ''' # Set up the axes fig = pl.figure(figsize=(12, 12)) fig.subplots_adjust(top=0.95, bottom=0.025, left=0.1, right=0.92) fig.canvas.set_window_title( '%s %d' % (self._mission.IDSTRING, s...
.. warning:: Untested!
entailment
def _save_npz(self): ''' Saves all of the de-trending information to disk in an `npz` file ''' # Save the data d = dict(self.__dict__) d.pop('_weights', None) d.pop('_A', None) d.pop('_B', None) d.pop('_f', None) d.pop('_mK', None) ...
Saves all of the de-trending information to disk in an `npz` file
entailment
def optimize(self, piter=3, pmaxf=300, ppert=0.1): ''' Runs :py:obj:`pPLD` on the target in an attempt to further optimize the values of the PLD priors. See :py:class:`everest.detrender.pPLD`. ''' self._save_npz() optimized = pPLD(self.ID, piter=piter, pmaxf=pmaxf, ...
Runs :py:obj:`pPLD` on the target in an attempt to further optimize the values of the PLD priors. See :py:class:`everest.detrender.pPLD`.
entailment
def plot_folded(self, t0, period, dur=0.2): ''' Plot the light curve folded on a given `period` and centered at `t0`. When plotting folded transits, please mask them using :py:meth:`mask_planet` and re-compute the model using :py:meth:`compute`. :param float t0: The time...
Plot the light curve folded on a given `period` and centered at `t0`. When plotting folded transits, please mask them using :py:meth:`mask_planet` and re-compute the model using :py:meth:`compute`. :param float t0: The time at which to center the plot \ (same units as lig...
entailment
def plot_transit_model(self, show=True, fold=None, ax=None): ''' Plot the light curve de-trended with a join instrumental + transit model with the best fit transit model overlaid. The transit model should be specified using the :py:obj:`transit_model` attribute and should be an i...
Plot the light curve de-trended with a join instrumental + transit model with the best fit transit model overlaid. The transit model should be specified using the :py:obj:`transit_model` attribute and should be an instance or list of instances of :py:class:`everest.transit.TransitModel`....
entailment
def Interpolate(time, mask, y): ''' Masks certain elements in the array `y` and linearly interpolates over them, returning an array `y'` of the same length. :param array_like time: The time array :param array_like mask: The indices to be interpolated over :param array_like y: The dependent ...
Masks certain elements in the array `y` and linearly interpolates over them, returning an array `y'` of the same length. :param array_like time: The time array :param array_like mask: The indices to be interpolated over :param array_like y: The dependent array
entailment
def Chunks(l, n, all=False): ''' Returns a generator of consecutive `n`-sized chunks of list `l`. If `all` is `True`, returns **all** `n`-sized chunks in `l` by iterating over the starting point. ''' if all: jarr = range(0, n - 1) else: jarr = [0] for j in jarr: ...
Returns a generator of consecutive `n`-sized chunks of list `l`. If `all` is `True`, returns **all** `n`-sized chunks in `l` by iterating over the starting point.
entailment
def Smooth(x, window_len=100, window='hanning'): ''' Smooth data by convolving on a given timescale. :param ndarray x: The data array :param int window_len: The size of the smoothing window. Default `100` :param str window: The window type. Default `hanning` ''' if window_len == 0: ...
Smooth data by convolving on a given timescale. :param ndarray x: The data array :param int window_len: The size of the smoothing window. Default `100` :param str window: The window type. Default `hanning`
entailment
def Scatter(y, win=13, remove_outliers=False): ''' Return the scatter in ppm based on the median running standard deviation for a window size of :py:obj:`win` = 13 cadences (for K2, this is ~6.5 hours, as in VJ14). :param ndarray y: The array whose CDPP is to be computed :param int win: The win...
Return the scatter in ppm based on the median running standard deviation for a window size of :py:obj:`win` = 13 cadences (for K2, this is ~6.5 hours, as in VJ14). :param ndarray y: The array whose CDPP is to be computed :param int win: The window size in cadences. Default `13` :param bool remove_o...
entailment
def SavGol(y, win=49): ''' Subtracts a second order Savitsky-Golay filter with window size `win` and returns the result. This acts as a high pass filter. ''' if len(y) >= win: return y - savgol_filter(y, win, 2) + np.nanmedian(y) else: return y
Subtracts a second order Savitsky-Golay filter with window size `win` and returns the result. This acts as a high pass filter.
entailment
def NumRegressors(npix, pld_order, cross_terms=True): ''' Return the number of regressors for `npix` pixels and PLD order `pld_order`. :param bool cross_terms: Include pixel cross-terms? Default :py:obj:`True` ''' res = 0 for k in range(1, pld_order + 1): if cross_terms: ...
Return the number of regressors for `npix` pixels and PLD order `pld_order`. :param bool cross_terms: Include pixel cross-terms? Default :py:obj:`True`
entailment
def Downbin(x, newsize, axis=0, operation='mean'): ''' Downbins an array to a smaller size. :param array_like x: The array to down-bin :param int newsize: The new size of the axis along which to down-bin :param int axis: The axis to operate on. Default 0 :param str operation: The operation to p...
Downbins an array to a smaller size. :param array_like x: The array to down-bin :param int newsize: The new size of the axis along which to down-bin :param int axis: The axis to operate on. Default 0 :param str operation: The operation to perform when down-binning. \ Default `mean`
entailment
def register_with_model(self, name, model): '''Called during the creation of a the :class:`StdModel` class when :class:`Metaclass` is initialised. It fills :attr:`Field.name` and :attr:`Field.model`. This is an internal function users should never call.''' if self.name: raise FieldError('Fie...
Called during the creation of a the :class:`StdModel` class when :class:`Metaclass` is initialised. It fills :attr:`Field.name` and :attr:`Field.model`. This is an internal function users should never call.
entailment
def add_to_fields(self): '''Add this :class:`Field` to the fields of :attr:`model`.''' meta = self.model._meta meta.scalarfields.append(self) if self.index: meta.indices.append(self)
Add this :class:`Field` to the fields of :attr:`model`.
entailment
def get_lookup(self, remaining, errorClass=ValueError): '''called by the :class:`Query` method when it needs to build lookup on fields with additional nested fields. This is the case of :class:`ForeignKey` and :class:`JSONField`. :param remaining: the :ref:`double underscored` fields if this :class:`Field` :pa...
called by the :class:`Query` method when it needs to build lookup on fields with additional nested fields. This is the case of :class:`ForeignKey` and :class:`JSONField`. :param remaining: the :ref:`double underscored` fields if this :class:`Field` :param errorClass: Optional exception class to use if the *remaining* ...
entailment
def get_value(self, instance, *bits): '''Retrieve the value :class:`Field` from a :class:`StdModel` ``instance``. :param instance: The :class:`StdModel` ``instance`` invoking this function. :param bits: Additional information for nested fields which derives from the :ref:`double underscore <tutorial-unders...
Retrieve the value :class:`Field` from a :class:`StdModel` ``instance``. :param instance: The :class:`StdModel` ``instance`` invoking this function. :param bits: Additional information for nested fields which derives from the :ref:`double underscore <tutorial-underscore>` notation. :return: the value of this :clas...
entailment