INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Parse data for related objects.
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...
Execute the query without fetching data. Returns the number of elements in the query.
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...
Perform ordering with respect model fields.
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...
Generator of load_related arguments
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 = ...
Remove and return a range from the ordered set by rank ( index ).
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 score.
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), ...
Extract model metadata for lua script stdnet/ lib/ lua/ odm. lua
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
Execute a session in redis.
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...
Flush all model keys from the database
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)
Returns the covariance matrix for a given light curve segment.
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 ...
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.
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...
Returns the negative log - likelihood function and its gradient.
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 ...
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.
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 ...
Generates dates between * atrt * and * end *.
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...
A little routine to initialize the logging functionality.
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 custom exception handler that logs errors to file.
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 with: py: obj: pdb post - mortem for debugging.
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...
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 necessarily be in th...
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 ...
Progress bar range with tqdm
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 ...
Return the front pair of the structure
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 back pair of the structure
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]
Converts the backend into the database connection parameters. It returns a ( scheme host params ) tuple.
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, '' ...
get a: class: BackendDataServer.
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...
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
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...
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.
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...
Create a backend: class: stdnet. odm. Structure handler.: param instance: a: class: stdnet. odm. Structure: param client: Optional client handler.
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:...
Why is my target not in the EVEREST database?
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...
Download a given: py: mod: everest file from MAST.
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 ...
Show the data validation summary ( DVS ) for a given target.
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...
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. Basecamp. compute.
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 ...
Computes the PLD flux normalization array.
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...
Load the FITS file from disk and populate the class instance with its data.
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 ...
Plot sample postage stamps for the target with the aperture outline marked as well as a high - res target image ( if available ).
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` '''...
Plots the final de - trended light curve.
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` ...
Shows the data validation summary ( DVS ) for the target.
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)
Plots the light curve for the target de - trended with a given pipeline.
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...
Returns the time and flux arrays for the target obtained by a given pipeline.
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...
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.
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...
.. warning:: Untested!
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...
Saves all of the de - trending information to disk in an npz file
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) ...
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.
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, ...
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.
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 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.
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...
Masks certain elements in the array y and linearly interpolates over them returning an array y of the same length.
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 ...
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.
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: ...
Smooth data by convolving on a given timescale.
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: ...
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 ).
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...
Subtracts a second order Savitsky - Golay filter with window size win and returns the result. This acts as a high pass filter.
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
Return the number of regressors for npix pixels and PLD order pld_order.
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: ...
Downbins an array to a smaller size.
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...
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.
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...
Add this: class: Field to the fields of: attr: model.
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)
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.
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...
Retrieve the value: class: Field from a: class: StdModel instance.
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...
Set the value for this: class: Field in a instance of a: class: StdModel.
def set_value(self, instance, value): '''Set the ``value`` for this :class:`Field` in a ``instance`` of a :class:`StdModel`.''' setattr(instance, self.attname, self.to_python(value))
lookup the value of the var_name on the stack of contexts
def lookup(var_name, contexts=(), start=0): """lookup the value of the var_name on the stack of contexts :var_name: TODO :contexts: TODO :returns: None if not found """ start = len(contexts) if start >=0 else start for context in reversed(contexts[:start]): try: if var_...
convert delimiters to corresponding regular expressions
def delimiters_to_re(delimiters): """convert delimiters to corresponding regular expressions""" # caching delimiters = tuple(delimiters) if delimiters in re_delimiters: re_tag = re_delimiters[delimiters] else: open_tag, close_tag = delimiters # escape open_tag = ''....
check if the string text [ start: end ] is standalone by checking forwards and backwards for blankspaces: text: TODO: ( start end ): TODO: returns: the start of next index after text [ start: end ]
def is_standalone(text, start, end): """check if the string text[start:end] is standalone by checking forwards and backwards for blankspaces :text: TODO :(start, end): TODO :returns: the start of next index after text[start:end] """ left = False start -= 1 while start >= 0 and text[...
Compile a template into token tree
def compiled(template, delimiters=DEFAULT_DELIMITERS): """Compile a template into token tree :template: TODO :delimiters: TODO :returns: the root token """ re_tag = delimiters_to_re(delimiters) # variable to save states tokens = [] index = 0 sections = [] tokens_stack = []...
Escape text according to self. escape
def _escape(self, text): """Escape text according to self.escape""" ret = EMPTYSTRING if text is None else str(text) if self.escape: return html_escape(ret) else: return ret
lookup value for names like a. b. c and handle filters as well
def _lookup(self, dot_name, contexts): """lookup value for names like 'a.b.c' and handle filters as well""" # process filters filters = [x for x in map(lambda x: x.strip(), dot_name.split('|'))] dot_name = filters[0] filters = filters[1:] # should support paths like '.....
Render the children tokens
def _render_children(self, contexts, partials): """Render the children tokens""" ret = [] for child in self.children: ret.append(child._render(contexts, partials)) return EMPTYSTRING.join(ret)
render variable
def _render(self, contexts, partials): """render variable""" value = self._lookup(self.value, contexts) # lambda if callable(value): value = inner_render(str(value()), contexts, partials) return self._escape(value)
render section
def _render(self, contexts, partials): """render section""" val = self._lookup(self.value, contexts) if not val: # false value return EMPTYSTRING # normally json has types: number/string/list/map # but python has more, so we decide that map and string sho...
render inverted section
def _render(self, contexts, partials): """render inverted section""" val = self._lookup(self.value, contexts) if val: return EMPTYSTRING return self._render_children(contexts, partials)
render partials
def _render(self, contexts, partials): """render partials""" try: partial = partials[self.value] except KeyError as e: return self._escape(EMPTYSTRING) partial = re_insert_indent.sub(r'\1' + ' '*self.indent, partial) return inner_render(partial, contexts...
Called when the code is installed. Sets up directories and downloads the K2 catalog.
def Setup(): ''' Called when the code is installed. Sets up directories and downloads the K2 catalog. ''' if not os.path.exists(os.path.join(EVEREST_DAT, 'k2', 'cbv')): os.makedirs(os.path.join(EVEREST_DAT, 'k2', 'cbv')) GetK2Stars(clobber=False)
Compute the proxy 6 - hr CDPP metric.
def CDPP(flux, mask=[], cadence='lc'): ''' Compute the proxy 6-hr CDPP metric. :param array_like flux: The flux array to compute the CDPP for :param array_like mask: The indices to be masked :param str cadence: The light curve cadence. Default `lc` ''' # 13 cadences is 6.5 hours rmswi...
Returns a: py: obj: DataContainer instance with the raw data for the target.
def GetData(EPIC, season=None, cadence='lc', clobber=False, delete_raw=False, aperture_name='k2sff_15', saturated_aperture_name='k2sff_19', max_pixels=75, download_only=False, saturation_tolerance=-0.1, bad_bits=[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17], get_hir...
Return neighbors random bright stars on the same module as EPIC.
def GetNeighbors(EPIC, season=None, model=None, neighbors=10, mag_range=(11., 13.), cdpp_range=None, aperture_name='k2sff_15', cadence='lc', **kwargs): ''' Return `neighbors` random bright stars on the same module as `EPIC`. :param int EPIC: The EPIC ID nu...
Computes and plots the CDPP statistics comparison between model and compare_to for all known K2 planets.
def PlanetStatistics(model='nPLD', compare_to='k2sff', **kwargs): ''' Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all known K2 planets. :param str model: The :py:obj:`everest` model name :param str compare_to: The :py:obj:`everest` model name or \ ...
Computes and plots the CDPP statistics comparison between short cadence and long cadence de - trended light curves
def ShortCadenceStatistics(campaign=None, clobber=False, model='nPLD', plot=True, **kwargs): ''' Computes and plots the CDPP statistics comparison between short cadence and long cadence de-trended light curves :param campaign: The campaign number or list of campaign numbers. ...
Computes and plots the CDPP statistics comparison between model and compare_to for all long cadence light curves in a given campaign
def Statistics(season=None, clobber=False, model='nPLD', injection=False, compare_to='kepler', plot=True, cadence='lc', planets=False, **kwargs): ''' Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all long cadence light curves in a given ...
Returns True if short cadence data is available for this target.
def HasShortCadence(EPIC, season=None): ''' Returns `True` if short cadence data is available for this target. :param int EPIC: The EPIC ID number :param int season: The campaign number. Default :py:obj:`None` ''' if season is None: season = Campaign(EPIC) if season is None: ...
Computes and plots the statistics for injection/ recovery tests.
def InjectionStatistics(campaign=0, clobber=False, model='nPLD', plot=True, show=True, **kwargs): ''' Computes and plots the statistics for injection/recovery tests. :param int campaign: The campaign number. Default 0 :param str model: The :py:obj:`everest` model name :param...
Generates HDU cards for inclusion in the de - trended light curve FITS file. Used internally.
def HDUCards(headers, hdu=0): ''' Generates HDU cards for inclusion in the de-trended light curve FITS file. Used internally. ''' if headers is None: return [] if hdu == 0: # Get info from the TPF Primary HDU Header tpf_header = headers[0] entries = ['TELESCOP'...
Returns the location of the: py: mod: everest data on disk for a given target.
def TargetDirectory(ID, season, relative=False, **kwargs): ''' Returns the location of the :py:mod:`everest` data on disk for a given target. :param ID: The target ID :param int season: The target season number :param bool relative: Relative path? Default :py:obj:`False` ''' if season...
Returns the name of the DVS PDF for a given target.
def DVSFile(ID, season, cadence='lc'): ''' Returns the name of the DVS PDF for a given target. :param ID: The target ID :param int season: The target season number :param str cadence: The cadence type. Default `lc` ''' if cadence == 'sc': strcadence = '_sc' else: strca...
Returns the design matrix of CBVs for the given target.
def GetTargetCBVs(model): ''' Returns the design matrix of CBVs for the given target. :param model: An instance of the :py:obj:`everest` model for the target ''' # Get the info season = model.season name = model.name # We use the LC light curves as CBVs; there aren't # enough SC ...
Fits the CBV design matrix to the de - trended flux of a given target. This is called internally whenever the user accesses the: py: attr: fcor attribute.
def FitCBVs(model): ''' Fits the CBV design matrix to the de-trended flux of a given target. This is called internally whenever the user accesses the :py:attr:`fcor` attribute. :param model: An instance of the :py:obj:`everest` model for the target ''' # Get cbvs? if model.XCBV is Non...
Generate the CSV file used in the search database for the documentation.
def StatsToCSV(campaign, model='nPLD'): ''' Generate the CSV file used in the search database for the documentation. ''' statsfile = os.path.join(EVEREST_SRC, 'missions', 'k2', 'tables', 'c%02d_%s.cdpp' % (campaign, model)) csvfile = os.path.join(os.path.dirname(EVEREST_...
Remove item for the: class: zset it it exists. If found it returns the score of the item removed.
def remove(self, item): '''Remove ``item`` for the :class:`zset` it it exists. If found it returns the score of the item removed.''' score = self._dict.pop(item, None) if score is not None: self._sl.remove(score) return score
Return a tuple of ordered fields for this: class: ColumnTS.
def fields(self): '''Return a tuple of ordered fields for this :class:`ColumnTS`.''' key = self.id + ':fields' encoding = self.client.encoding return tuple(sorted((f.decode(encoding) for f in self.client.smembers(key))))
Handle any pending relations to the sending model. Sent from class_prepared.
def do_pending_lookups(event, sender, **kwargs): """Handle any pending relations to the sending model. Sent from class_prepared.""" key = (sender._meta.app_label, sender._meta.name) for callback in pending_lookups.pop(key, []): callback(sender)
Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys.
def Many2ManyThroughModel(field): '''Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys.''' from stdnet.odm import ModelType, StdModel, ForeignKey, CompositeIdField name_model = field.model._meta.name name_relmodel = field.relmodel....
formodel is the model which the manager.
def makeMany2ManyRelatedManager(formodel, name_relmodel, name_formodel): '''formodel is the model which the manager .''' class _Many2ManyRelatedManager(Many2ManyRelatedManager): pass _Many2ManyRelatedManager.formodel = formodel _Many2ManyRelatedManager.name_relmodel = name_relmodel ...
Override: meth: Manager. session so that this: class: RelatedManager can retrieve the session from the: attr: related_instance if available.
def session(self, session=None): '''Override :meth:`Manager.session` so that this :class:`RelatedManager` can retrieve the session from the :attr:`related_instance` if available. ''' if self.related_instance: session = self.related_instance.session # we...
Add value an instance of: attr: formodel to the: attr: through model. This method can only be accessed by an instance of the model for which this related manager is an attribute.
def add(self, value, session=None, **kwargs): '''Add ``value``, an instance of :attr:`formodel` to the :attr:`through` model. This method can only be accessed by an instance of the model for which this related manager is an attribute.''' s, instance = self.session_instance('add', value, session, **k...
Remove * value * an instance of self. model from the set of elements contained by the field.
def remove(self, value, session=None): '''Remove *value*, an instance of ``self.model`` from the set of elements contained by the field.''' s, instance = self.session_instance('remove', value, session) # update state so that the instance does look persistent instance.get_state(iid=i...
Double metaphone word processor.
def metaphone_processor(words): '''Double metaphone word processor.''' for word in words: for w in double_metaphone(word): if w: w = w.strip() if w: yield w
Double metaphone word processor slightly modified so that when no words are returned by the algorithm the original word is returned.
def tolerant_metaphone_processor(words): '''Double metaphone word processor slightly modified so that when no words are returned by the algorithm, the original word is returned.''' for word in words: r = 0 for w in double_metaphone(word): if w: w = w.strip() ...
Porter Stemmer word processor
def stemming_processor(words): '''Porter Stemmer word processor''' stem = PorterStemmer().stem for word in words: word = stem(word, 0, len(word)-1) yield word
Chooses between the different pools. If pool == AnyPool chooses based on availability.
def Pool(pool='AnyPool', **kwargs): ''' Chooses between the different pools. If ``pool == 'AnyPool'``, chooses based on availability. ''' if pool == 'MPIPool': return MPIPool(**kwargs) elif pool == 'MultiPool': return MultiPool(**kwargs) elif pool == 'SerialPool': r...
If this isn t the master process wait for instructions.
def wait(self): """ If this isn't the master process, wait for instructions. """ if self.is_master(): raise RuntimeError("Master node told to await jobs.") status = MPI.Status() while True: # Event loop. # Sit here and await instruct...
Like the built - in: py: func: map function apply a function to all of the values in a list and return the list of results.
def map(self, function, tasks): """ Like the built-in :py:func:`map` function, apply a function to all of the values in a list and return the list of results. :param function: The function to apply to the list. :param tasks: The list of elements. ...
Just send a message off to all the pool members which contains the special: class: _close_pool_message sentinel.
def close(self): """ Just send a message off to all the pool members which contains the special :class:`_close_pool_message` sentinel. """ if self.is_master(): for i in range(self.size): self.comm.isend(_close_pool_message(), dest=i + 1)
Decorator for committing changes when the instance session is not in a transaction.
def commit_when_no_transaction(f): '''Decorator for committing changes when the instance session is not in a transaction.''' def _(self, *args, **kwargs): r = f(self, *args, **kwargs) return self.session.add(self) if self.session is not None else r _.__name__ = f.__name__ _.__doc_...
Returns the: class: stdnet. BackendStructure.
def backend(self): '''Returns the :class:`stdnet.BackendStructure`. ''' session = self.session if session is not None: if self._field: return session.model(self._field.model).backend else: return session.model(self).backend
Returns the: class: stdnet. BackendStructure.
def read_backend(self): '''Returns the :class:`stdnet.BackendStructure`. ''' session = self.session if session is not None: if self._field: return session.model(self._field.model).read_backend else: return session.model(self...
Number of elements in the: class: Structure.
def size(self): '''Number of elements in the :class:`Structure`.''' if self.cache.cache is None: return self.read_backend_structure().size() else: return len(self.cache.cache)