code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def Rsky(self): r = (self.orbpop.Rsky/self.distance) return r.to('arcsec',equivalencies=u.dimensionless_angles())
Projected angular distance between "primary" and "secondary" (exact meaning varies)
def append(self, other): if not isinstance(other,StarPopulation): raise TypeError('Only StarPopulation objects can be appended to a StarPopulation.') if not np.all(self.stars.columns == other.stars.columns): raise ValueError('Two populations must have same columns to com...
Appends stars from another StarPopulations, in place. :param other: Another :class:`StarPopulation`; must have same columns as ``self``.
def bands(self): bands = [] for c in self.stars.columns: if re.search('_mag',c): bands.append(c) return bands
Bandpasses for which StarPopulation has magnitude data
def distance(self,value): self.stars['distance'] = value.to('pc').value old_distmod = self.stars['distmod'].copy() new_distmod = distancemodulus(self.stars['distance']) for m in self.bands: self.stars[m] += new_distmod - old_distmod self.stars['distmod'] =...
New distance value must be a ``Quantity`` object
def distok(self): ok = np.ones(len(self.stars)).astype(bool) for name in self.constraints: c = self.constraints[name] if c.name not in self.distribution_skip: ok &= c.ok return ok
Boolean array showing which stars pass all distribution constraints. A "distribution constraint" is a constraint that affects the distribution of stars, rather than just the number.
def countok(self): ok = np.ones(len(self.stars)).astype(bool) for name in self.constraints: c = self.constraints[name] if c.name not in self.selectfrac_skip: ok &= c.ok return ok
Boolean array showing which stars pass all count constraints. A "count constraint" is a constraint that affects the number of stars.
def prophist(self,prop,fig=None,log=False, mask=None, selected=False,**kwargs): setfig(fig) inds = None if mask is not None: inds = np.where(mask)[0] elif inds is None: if selected: #inds = np.arange(len(self.selected)) ...
Plots a 1-d histogram of desired property. :param prop: Name of property to plot. Must be column of ``self.stars``. :param fig: (optional) Argument for :func:`plotutils.setfig` :param log: (optional) Whether to plot the histogram of log10 of the property. ...
def constraint_stats(self,primarylist=None): if primarylist is None: primarylist = [] n = len(self.stars) primaryOK = np.ones(n).astype(bool) tot_reject = np.zeros(n) for name in self.constraints: if name in self.selectfrac_skip: ...
Returns information about effect of constraints on population. :param primarylist: List of constraint names that you want specific information on (i.e., not blended within "multiple constraints".) :return: ``dict`` of what percentage of population is ruled out by ...
def constraints(self): try: return self._constraints except AttributeError: self._constraints = ConstraintDict() return self._constraints
Constraints applied to the population.
def hidden_constraints(self): try: return self._hidden_constraints except AttributeError: self._hidden_constraints = ConstraintDict() return self._hidden_constraints
Constraints applied to the population, but temporarily removed.
def apply_constraint(self,constraint,selectfrac_skip=False, distribution_skip=False,overwrite=False): #grab properties constraints = self.constraints my_selectfrac_skip = self.selectfrac_skip my_distribution_skip = self.distribution_skip if cons...
Apply a constraint to the population :param constraint: Constraint to apply. :type constraint: :class:`Constraint` :param selectfrac_skip: (optional) If ``True``, then this constraint will not be considered towards diminishing the
def replace_constraint(self,name,selectfrac_skip=False,distribution_skip=False): hidden_constraints = self.hidden_constraints if name in hidden_constraints: c = hidden_constraints[name] self.apply_constraint(c,selectfrac_skip=selectfrac_skip, ...
Re-apply constraint that had been removed :param name: Name of constraint to replace :param selectfrac_skip,distribution_skip: (optional) Same as :func:`StarPopulation.apply_constraint`
def remove_constraint(self,name): constraints = self.constraints hidden_constraints = self.hidden_constraints my_distribution_skip = self.distribution_skip my_selectfrac_skip = self.selectfrac_skip if name in constraints: hidden_constraints[name] = constrain...
Remove a constraint (make it "hidden") :param name: Name of constraint.
def constrain_property(self,prop,lo=-np.inf,hi=np.inf, measurement=None,thresh=3, selectfrac_skip=False,distribution_skip=False): if prop in self.constraints: logging.info('re-doing {} constraint'.format(prop)) self.remove_co...
Apply constraint that constrains property. :param prop: Name of property. Must be column in ``self.stars``. :type prop: ``str`` :param lo,hi: (optional) Low and high allowed values for ``prop``. Defaults to ``-np.inf`` and ``np.inf`` to allow f...
def apply_trend_constraint(self, limit, dt, distribution_skip=False, **kwargs): if type(limit) != Quantity: limit = limit * u.m/u.s if type(dt) != Quantity: dt = dt * u.day dRVs = np.absolute(self.dRV(dt)) c1 = UpperLimit(d...
Constrains change in RV to be less than limit over time dt. Only works if ``dRV`` and ``Plong`` attributes are defined for population. :param limit: Radial velocity limit on trend. Must be :class:`astropy.units.Quantity` object, or else interpreted as m/s. ...
def apply_cc(self, cc, distribution_skip=False, **kwargs): rs = self.Rsky.to('arcsec').value dmags = self.dmag(cc.band) self.apply_constraint(ContrastCurveConstraint(rs,dmags,cc,name=cc.name), distribution_skip=distribution_skip, **kwargs)
Apply contrast-curve constraint to population. Only works if object has ``Rsky``, ``dmag`` attributes :param cc: Contrast curve. :type cc: :class:`ContrastCurveConstraint` :param distribution_skip: This is by default ``True``. *To be honest, I'm no...
def apply_vcc(self, vcc, distribution_skip=False, **kwargs): rvs = self.RV.value dmags = self.dmag(vcc.band) self.apply_constraint(VelocityContrastCurveConstraint(rvs,dmags,vcc, name='secondary spectrum'), ...
Applies "velocity contrast curve" to population. That is, the constraint that comes from not seeing two sets of spectral lines in a high resolution spectrum. Only works if population has ``dmag`` and ``RV`` attributes. :param vcc: Velocity contrast curve; dmag vs. delta-RV...
def set_maxrad(self,maxrad, distribution_skip=True): self.maxrad = maxrad self.apply_constraint(UpperLimit(self.Rsky,maxrad, name='Max Rsky'), overwrite=True, distribution_skip=distribution_skip...
Adds a constraint that rejects everything with Rsky > maxrad Requires ``Rsky`` attribute, which should always have units. :param maxrad: The maximum angular value of Rsky. :type maxrad: :class:`astropy.units.Quantity` :param distribution_skip: This ...
def constraint_df(self): df = pd.DataFrame() for name,c in self.constraints.items(): df[name] = c.ok for name,c in self.hidden_constraints.items(): df[name] = c.ok return df
A DataFrame representing all constraints, hidden or not
def binary_fraction(self,query='mass_A >= 0'): subdf = self.stars.query(query) nbinaries = (subdf['mass_B'] > 0).sum() frac = nbinaries/len(subdf) return frac, frac/np.sqrt(nbinaries)
Binary fraction of stars passing given query :param query: Query to pass to stars ``DataFrame``.
def dmag(self,band): mag2 = self.stars['{}_mag_B'.format(band)] mag1 = self.stars['{}_mag_A'.format(band)] return mag2-mag1
Difference in magnitude between primary and secondary stars :param band: Photometric bandpass.
def rsky_distribution(self,rmax=None,smooth=0.1,nbins=100): if rmax is None: if hasattr(self,'maxrad'): rmax = self.maxrad else: rmax = np.percentile(self.Rsky,99) dist = dists.Hist_Distribution(self.Rsky.value,bins=nbins,maxval=rmax,smoot...
Distribution of projected separations Returns a :class:`simpledists.Hist_Distribution` object. :param rmax: (optional) Maximum radius to calculate distribution. :param dr: (optional) Bin width for histogram :param smooth: (optional) Smoothing param...
def rsky_lhood(self,rsky,**kwargs): dist = self.rsky_distribution(**kwargs) return dist(rsky)
Evaluates Rsky likelihood at provided position(s) :param rsky: position :param **kwargs: Keyword arguments passed to :func:`BinaryPopulation.rsky_distribution`
def generate(self, M, age=9.6, feh=0.0, ichrone='mist', n=1e4, bands=None, **kwargs): ichrone = get_ichrone(ichrone, bands=bands) if np.size(M) > 1: n = np.size(M) else: n = int(n) M2 = M * self.q_fn(n, qmin=np.maximum(self.qmin,self.minm...
Function that generates population. Called by ``__init__`` if ``M`` is passed.
def dmag(self, band): m1 = self.stars['{}_mag_A'.format(band)] m2 = addmags(self.stars['{}_mag_B'.format(band)], self.stars['{}_mag_C'.format(band)]) return np.abs(m2-m1)
Difference in magnitudes between fainter and brighter components in band. :param band: Photometric bandpass.
def A_brighter(self, band='g'): mA = self.stars['{}_mag_A'.format(band)] mBC = addmags(self.stars['{}_mag_B'.format(band)], self.stars['{}_mag_C'.format(band)]) return mA < mBC
Instances where star A is brighter than (B+C)
def dRV(self, dt, band='g'): return (self.orbpop.dRV_1(dt)*self.A_brighter(band) + self.orbpop.dRV_2(dt)*self.BC_brighter(band))
Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter
def triple_fraction(self,query='mass_A > 0', unc=False): subdf = self.stars.query(query) ntriples = ((subdf['mass_B'] > 0) & (subdf['mass_C'] > 0)).sum() frac = ntriples/len(subdf) if unc: return frac, frac/np.sqrt(ntriples) else: return frac
Triple fraction of stars following given query
def starmodel_props(self): props = {} mags = self.mags mag_errs = self.mag_errs for b in mags.keys(): if np.size(mags[b])==2: props[b] = mags[b] elif np.size(mags[b])==1: mag = mags[b] try: ...
Default mag_err is 0.05, arbitrarily
def dmag(self,band): if self.mags is None: raise ValueError('dmag is not defined because primary mags are not defined for this population.') return self.stars['{}_mag'.format(band)] - self.mags[band]
Magnitude difference between primary star and BG stars
def send(self): def _confirm(input_message): if input_message == 'Confirmed!': self.confirmed = True yield self.start_tor() self._w = wormhole.create(u'axotor', RENDEZVOUS_RELAY, self._reactor, tor=self._tor, timing=self._ti...
I send data through a wormhole and return True/False depending on whether or not the hash matched at the receive side.
def receive(self): def _receive(input_message): self.data = input_message[:-64] _hash = input_message[-64:] if h.sha256(self.data).hexdigest() == _hash: self._w.send_message('Confirmed!') else: self._w.send_message('Not Con...
I receive data+hash, check for a match, confirm or not confirm to the sender, and return the data payload.
def validator(ch): global screen_needs_update try: if screen_needs_update: curses.doupdate() screen_needs_update = False return ch finally: winlock.release() sleep(0.01) # let receiveThread in if necessary winlock.acquire()
Update screen if necessary and release the lock so receiveThread can run
def resample(self, inds): new = copy.deepcopy(self) for arr in self.arrays: x = getattr(new, arr) setattr(new, arr, x[inds]) return new
Returns copy of constraint, with mask rearranged according to indices
def save(self, overwrite=True): self.save_popset(overwrite=overwrite) self.save_signal()
Saves PopulationSet and TransitSignal. Shouldn't need to use this if you're using :func:`FPPCalculation.from_ini`. Saves :class`PopulationSet` to ``[folder]/popset.h5]`` and :class:`TransitSignal` to ``[folder]/trsig.pkl``. :param overwrite: (optional) Whether to o...
def load(cls, folder): popset = PopulationSet.load_hdf(os.path.join(folder,'popset.h5')) sigfile = os.path.join(folder,'trsig.pkl') with open(sigfile, 'rb') as f: trsig = pickle.load(f) return cls(trsig, popset, folder=folder)
Loads PopulationSet from folder ``popset.h5`` and ``trsig.pkl`` must exist in folder. :param folder: Folder from which to load.
def FPPplots(self, folder=None, format='png', tag=None, **kwargs): if folder is None: folder = self.folder self.write_results(folder=folder) self.lhoodplots(folder=folder,figformat=format,tag=tag,**kwargs) self.FPPsummary(folder=folder,saveplot=True,figformat=format...
Make FPP diagnostic plots Makes likelihood "fuzz plot" for each model, a FPP summary figure, a plot of the :class:`TransitSignal`, and writes a ``results.txt`` file. :param folder: (optional) Destination folder for plots/``results.txt``. Default is ``self.folde...
def plotsignal(self,fig=None,saveplot=True,folder=None,figformat='png',**kwargs): if folder is None: folder = self.folder self.trsig.plot(plot_trap=True,fig=fig,**kwargs) if saveplot: plt.savefig('%s/signal.%s' % (folder,figformat)) plt.close()
Plots TransitSignal Calls :func:`TransitSignal.plot`, saves to provided folder. :param fig: (optional) Argument for :func:`plotutils.setfig`. :param saveplot: (optional) Whether to save figure. :param folder: (optional) Folder to which to save plot...
def write_results(self,folder=None, filename='results.txt', to_file=True): if folder is None: folder = self.folder if to_file: fout = open(os.path.join(folder,filename), 'w') header = '' for m in self.popset.shortmodelnames: header += 'lhood_{...
Writes text file of calculation summary. :param folder: (optional) Folder to which to write ``results.txt``. :param filename: Filename to write. Default=``results.txt``. :param to_file: If True, then writes file. Otherwise just return header, line. ...
def save_popset(self,filename='popset.h5',**kwargs): self.popset.save_hdf(os.path.join(self.folder,filename))
Saves the PopulationSet Calls :func:`PopulationSet.save_hdf`.
def save_signal(self,filename=None): if filename is None: filename = os.path.join(self.folder,'trsig.pkl') self.trsig.save(filename)
Saves TransitSignal. Calls :func:`TransitSignal.save`; default filename is ``trsig.pkl`` in ``self.folder``.
def modelshift_weaksec(koi): num = KOIDATA.ix[ku.koiname(koi), 'koi_tce_plnt_num'] if np.isnan(num): num = 1 kid = KOIDATA.ix[ku.koiname(koi), 'kepid'] tce = '{:09.0f}-{:02.0f}'.format(kid,num) #return largest depth between DV detrending and alternate detrending try: r = RO...
Max secondary depth based on model-shift secondary test from Jeff Coughlin secondary metric: mod_depth_sec_dv * (1 + 3*mod_fred_dv / mod_sig_sec_dv)
def use_property(kepid, prop): try: prov = kicu.DATA.ix[kepid, '{}_prov'.format(prop)] return any([prov.startswith(s) for s in ['SPE', 'AST']]) except KeyError: raise MissingStellarError('{} not in stellar table?'.format(kepid))
Returns true if provenance of property is SPE or AST
def fpp_config(koi, **kwargs): folder = os.path.join(KOI_FPPDIR, ku.koiname(koi)) if not os.path.exists(folder): os.makedirs(folder) config = ConfigObj(os.path.join(folder,'fpp.ini')) koi = ku.koiname(koi) rowefit = jrowe_fit(koi) config['name'] = koi ra,dec = ku.radec(koi) ...
returns config object for given KOI
def apply_default_constraints(self): try: self.apply_secthresh(pipeline_weaksec(self.koi)) except NoWeakSecondaryError: logging.warning('No secondary eclipse threshold set for {}'.format(self.koi)) self.set_maxrad(default_r_exclusion(self.koi))
Applies default secthresh & exclusion radius constraints
def get_old_sha(diff_part): r = re.compile(r'index ([a-fA-F\d]*)') return r.search(diff_part).groups()[0]
Returns the SHA for the original file that was changed in a diff part.
def get_old_filename(diff_part): regexps = ( # e.g. "+++ a/foo/bar" r'^--- a/(.*)', # e.g. "+++ /dev/null" r'^\-\-\- (.*)', ) for regexp in regexps: r = re.compile(regexp, re.MULTILINE) match = r.search(diff_part) if match is not None: ...
Returns the filename for the original file that was changed in a diff part.
def get_new_filename(diff_part): regexps = ( # e.g. "+++ b/foo/bar" r'^\+\+\+ b/(.*)', # e.g. "+++ /dev/null" r'^\+\+\+ (.*)', ) for regexp in regexps: r = re.compile(regexp, re.MULTILINE) match = r.search(diff_part) if match is not None: ...
Returns the filename for the updated file in a diff part.
def get_contents(diff_part): old_sha = get_old_sha(diff_part) old_filename = get_old_filename(diff_part) old_contents = get_old_contents(old_sha, old_filename) new_filename = get_new_filename(diff_part) new_contents = get_new_contents(new_filename) return old_contents, new_contents
Returns a tuple of old content and new content.
def decrypt_diff(diff_part, password_file=None): vault = VaultLib(get_vault_password(password_file)) old_contents, new_contents = get_contents(diff_part) if vault.is_encrypted(old_contents): old_contents = vault.decrypt(old_contents) if vault.is_encrypted(new_contents): new_contents...
Diff part is a string in the format: diff --git a/group_vars/foo b/group_vars/foo index c09080b..0d803bb 100644 --- a/group_vars/foo +++ b/group_vars/foo @@ -1,32 +1,33 @@ $ANSIBLE_VAULT;1.1;AES256 -613166623637303132306264323036623163303230643738666164366235656...
def fressin_occurrence(rp): rp = np.atleast_1d(rp) sq2 = np.sqrt(2) bins = np.array([1/sq2,1,sq2,2,2*sq2, 4,4*sq2,8,8*sq2, 16,16*sq2]) rates = np.array([0,0.155,0.155,0.165,0.17,0.065,0.02,0.01,0.012,0.01,0.002,0]) return rates[np.digitize(rp,bins)]
Occurrence rates per bin from Fressin+ (2013)
def _loadcache(cachefile): cache = {} if os.path.exists(cachefile): with open(cachefile) as f: for line in f: line = line.split() if len(line) == 2: try: cache[int(line[0])] = float(line[1]) ...
Returns a dictionary resulting from reading a likelihood cachefile
def eclipseprob(self): #TODO: incorporate eccentricity/omega for exact calculation? s = self.stars return ((s['radius_1'] + s['radius_2'])*RSUN / (semimajor(s['P'],s['mass_1'] + s['mass_2'])*AU))
Array of eclipse probabilities.
def modelshort(self): try: name = SHORT_MODELNAMES[self.model] #add index if specific model is indexed if hasattr(self,'index'): name += '-{}'.format(self.index) return name except KeyError: raise KeyError('No short ...
Short version of model name Dictionary defined in ``populations.py``:: SHORT_MODELNAMES = {'Planets':'pl', 'EBs':'eb', 'HEBs':'heb', 'BEBs':'beb', 'Blended Planets':'bpl', 'Specific BEB':'sbeb', ...
def constrain_secdepth(self, thresh): self.apply_constraint(UpperLimit(self.secondary_depth, thresh, name='secondary depth'))
Constrain the observed secondary depth to be less than a given value :param thresh: Maximum allowed fractional depth for diluted secondary eclipse depth
def prior(self): prior = self.prob * self.selectfrac for f in self.priorfactors: prior *= self.priorfactors[f] return prior
Model prior for particular model. Product of eclipse probability (``self.prob``), the fraction of scenario that is allowed by the various constraints (``self.selectfrac``), and all additional factors in ``self.priorfactors``.
def add_priorfactor(self,**kwargs): for kw in kwargs: if kw in self.priorfactors: logging.error('%s already in prior factors for %s. use change_prior function instead.' % (kw,self.model)) continue else: self.priorfactors[kw] = kwa...
Adds given values to priorfactors If given keyword exists already, error will be raised to use :func:`EclipsePopulation.change_prior` instead.
def change_prior(self, **kwargs): for kw in kwargs: if kw in self.priorfactors: self.priorfactors[kw] = kwargs[kw] logging.info('{0} changed to {1} for {2} model'.format(kw,kwargs[kw], sel...
Changes existing priorfactors. If given keyword isn't already in priorfactors, then will be ignored.
def _density(self, logd, dur, slope): if self.sklearn_kde: #TODO: fix preprocessing pts = np.array([(logd - self.mean_logdepth)/self.std_logdepth, (dur - self.mean_dur)/self.std_dur, (slope - self.mean_slope)/self.std_slope...
Evaluate KDE at given points. Prepares data according to whether sklearn or scipy KDE in use. :param log, dur, slope: Trapezoidal shape parameters.
def lhood(self, trsig, recalc=False, cachefile=None): if not hasattr(self,'kde'): self._make_kde() if cachefile is None: cachefile = self.lhoodcachefile if cachefile is None: cachefile = 'lhoodcache.dat' lhoodcache = _loadcache(cache...
Returns likelihood of transit signal Returns sum of ``trsig`` MCMC samples evaluated at ``self.kde``. :param trsig: :class:`vespa.TransitSignal` object. :param recalc: (optional) Whether to recalculate likelihood (if calculation is cached). ...
def load_hdf(cls, filename, path=''): #perhaps this doesn't need to be written? new = StarPopulation.load_hdf(filename, path=path) #setup lazy loading of starmodel if present try: with pd.HDFStore(filename) as store: if '{}/starmodel'.format(path) in store:...
Loads EclipsePopulation from HDF file Also runs :func:`EclipsePopulation._make_kde` if it can. :param filename: HDF file :param path: (optional) Path within HDF file
def resample(self): new = copy.deepcopy(self) N = len(new.stars) inds = np.random.randint(N, size=N) # Resample stars new.stars = new.stars.iloc[inds].reset_index() # Resample constraints if hasattr(new, '_constraints'): for c in new._constr...
Returns a copy of population with stars resampled (with replacement). Used in bootstrap estimate of FPP uncertainty. TODO: check to make sure constraints properly copied!
def constraints(self): cs = [] for pop in self.poplist: cs += [c for c in pop.constraints] return list(set(cs))
Unique list of constraints among all populations in set.
def save_hdf(self, filename, path='', overwrite=False): if os.path.exists(filename) and overwrite: os.remove(filename) for pop in self.poplist: name = pop.modelshort pop.save_hdf(filename, path='{}/{}'.format(path,name), append=True)
Saves PopulationSet to HDF file.
def load_hdf(cls, filename, path=''): with pd.HDFStore(filename) as store: models = [] types = [] for k in store.keys(): m = re.search('/(\S+)/stars', k) if m: models.append(m.group(1)) types.app...
Loads PopulationSet from file
def add_population(self,pop): if pop.model in self.modelnames: raise ValueError('%s model already in PopulationSet.' % pop.model) self.modelnames.append(pop.model) self.shortmodelnames.append(pop.modelshort) self.poplist.append(pop)
Adds population to PopulationSet
def remove_population(self,pop): iremove=None for i in range(len(self.poplist)): if self.modelnames[i]==self.poplist[i].model: iremove=i if iremove is not None: self.modelnames.pop(i) self.shortmodelnames.pop(i) self.poplis...
Removes population from PopulationSet
def colordict(self): d = {} i=0 n = len(self.constraints) for c in self.constraints: #self.colordict[c] = colors[i % 6] d[c] = cm.jet(1.*i/n) i+=1 return d
Dictionary holding colors that correspond to constraints.
def priorfactors(self): priorfactors = {} for pop in self.poplist: for f in pop.priorfactors: if f in priorfactors: if pop.priorfactors[f] != priorfactors[f]: raise ValueError('prior factor %s is inconsistent!' % f) ...
Combinartion of priorfactors from all populations
def change_prior(self,**kwargs): for kw,val in kwargs.items(): if kw=='area': logging.warning('cannot change area in this way--use change_maxrad instead') continue for pop in self.poplist: k = {kw:val} pop.change_pr...
Changes prior factor(s) in all populations
def apply_multicolor_transit(self,band,depth): if '{} band transit'.format(band) not in self.constraints: self.constraints.append('{} band transit'.format(band)) for pop in self.poplist: pop.apply_multicolor_transit(band,depth)
Applies constraint corresponding to measuring transit in different band This is not implemented yet.
def set_maxrad(self,newrad): if not isinstance(newrad, Quantity): newrad = newrad * u.arcsec #if 'Rsky' not in self.constraints: # self.constraints.append('Rsky') for pop in self.poplist: if not pop.is_specific: try: ...
Sets max allowed radius in populations. Doesn't operate via the :class:`stars.Constraint` protocol; rather just rescales the sky positions for the background objects and recalculates sky area, etc.
def apply_dmaglim(self,dmaglim=None): raise NotImplementedError if 'bright blend limit' not in self.constraints: self.constraints.append('bright blend limit') for pop in self.poplist: if not hasattr(pop,'dmaglim') or pop.is_specific: continue ...
Applies a constraint that sets the maximum brightness for non-target star :func:`stars.StarPopulation.set_dmaglim` not yet implemented.
def apply_trend_constraint(self, limit, dt, **kwargs): if 'RV monitoring' not in self.constraints: self.constraints.append('RV monitoring') for pop in self.poplist: if not hasattr(pop,'dRV'): continue pop.apply_trend_constraint(limit, dt, **kw...
Applies constraint corresponding to RV trend non-detection to each population See :func:`stars.StarPopulation.apply_trend_constraint`; all arguments passed to that function for each population.
def apply_secthresh(self, secthresh, **kwargs): if 'secondary depth' not in self.constraints: self.constraints.append('secondary depth') for pop in self.poplist: if not isinstance(pop, EclipsePopulation_Px2): pop.apply_secthresh(secthresh, **kwargs) ...
Applies secondary depth constraint to each population See :func:`EclipsePopulation.apply_secthresh`; all arguments passed to that function for each population.
def constrain_oddeven(self, diff, **kwargs): if 'odd-even' not in self.constraints: self.constraints.append('odd-even') for pop in self.poplist: if isinstance(pop, EclipsePopulation_Px2): pop.constrain_oddeven(diff, **kwargs) self.oddeven_diff = d...
Constrains the difference b/w primary and secondary to be < diff
def constrain_property(self,prop,**kwargs): if prop not in self.constraints: self.constraints.append(prop) for pop in self.poplist: try: pop.constrain_property(prop,**kwargs) except AttributeError: logging.info('%s model does n...
Constrains property for each population See :func:`vespa.stars.StarPopulation.constrain_property`; all arguments passed to that function for each population.
def replace_constraint(self,name,**kwargs): for pop in self.poplist: pop.replace_constraint(name,**kwargs) if name not in self.constraints: self.constraints.append(name)
Replaces removed constraint in each population. See :func:`vespa.stars.StarPopulation.replace_constraint`
def remove_constraint(self,*names): for name in names: for pop in self.poplist: if name in pop.constraints: pop.remove_constraint(name) else: logging.info('%s model does not have %s constraint' % (pop.model,name)) ...
Removes constraint from each population See :func:`vespa.stars.StarPopulation.remove_constraint
def apply_cc(self, cc, **kwargs): if type(cc)==type(''): pass if cc.name not in self.constraints: self.constraints.append(cc.name) for pop in self.poplist: if not pop.is_specific: try: pop.apply_cc(cc, **kwargs) ...
Applies contrast curve constraint to each population See :func:`vespa.stars.StarPopulation.apply_cc`; all arguments passed to that function for each population.
def apply_vcc(self,vcc): if 'secondary spectrum' not in self.constraints: self.constraints.append('secondary spectrum') for pop in self.poplist: if not pop.is_specific: try: pop.apply_vcc(vcc) except: ...
Applies velocity contrast curve constraint to each population See :func:`vespa.stars.StarPopulation.apply_vcc`; all arguments passed to that function for each population.
def log_wrapper(self): log = logging.getLogger('client.py') # Set the log format and log level try: debug = self.params["debug"] log.setLevel(logging.DEBUG) except KeyError: log.setLevel(logging.INFO) # Set the log format. st...
Wrapper to set logging parameters for output
def decode_setid(encoded): try: lo, hi = struct.unpack('<QQ', b32decode(encoded.upper() + '======')) except struct.error: raise ValueError('Cannot decode {!r}'.format(encoded)) return (hi << 64) + lo
Decode setid as uint128
def encode_setid(uint128): hi, lo = divmod(uint128, 2**64) return b32encode(struct.pack('<QQ', lo, hi))[:-6].lower()
Encode uint128 setid as stripped b32encoded string
def _reduce_opacity(self, watermark, opacity): if watermark.type() != ImageType.TrueColorMatteType: watermark.type(ImageType.TrueColorMatteType) depth = 255 - int(255 * opacity) watermark.quantumOperator(ChannelType.OpacityChannel, QuOp.MaxQuantumOp, depth)
Returns an image with reduced opacity. Converts image to RGBA if needs. Simple watermark.opacity(65535 - int(65535 * opacity) would not work for images with the Opacity channel (RGBA images). So we have to convert RGB or any other type to RGBA in this case
def cleanup_relations(self): collections = self.collections for relation in [x for col in collections.values() for x in col.model.relations.values()]: db.session.query(relation)\ .filter(~relation.listing.any())\ ...
Cleanup listing relations
def marvcli_cleanup(ctx, discarded, unused_tags): if not any([discarded, unused_tags]): click.echo(ctx.get_help()) ctx.exit(1) site = create_app().site if discarded: site.cleanup_discarded() if unused_tags: site.cleanup_tags() site.cleanup_relations()
Cleanup unused tags and discarded datasets.
def marvcli_develop_server(port, public): from flask_cors import CORS app = create_app(push=False) app.site.load_for_web() CORS(app) class IPDBMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): from ...
Run development webserver. ATTENTION: By default it is only served on localhost. To run it within a container and access it from the outside, you need to forward the port and tell it to listen on all IPs instead of only localhost.
def marvcli_discard(datasets, all_nodes, nodes, tags, comments, confirm): mark_discarded = not any([all_nodes, nodes, tags, comments]) site = create_app().site setids = parse_setids(datasets) if tags or comments: if confirm: msg = ' and '.join(filter(None, ['tags' if tags else...
Mark DATASETS to be discarded or discard associated data. Without any options the specified datasets are marked to be discarded via `marv cleanup --discarded`. Use `marv undiscard` to undo this operation. Otherwise, selected data associated with the specified datasets is discarded right away.
def marvcli_undiscard(datasets): create_app() setids = parse_setids(datasets, discarded=True) dataset = Dataset.__table__ stmt = dataset.update()\ .where(dataset.c.setid.in_(setids))\ .values(discarded=False) db.session.execute(stmt) db.session.commit()
Undiscard DATASETS previously discarded.
def marvcli_restore(file): data = json.load(file) site = create_app().site site.restore_database(**data)
Restore previously dumped database
def marvcli_query(ctx, list_tags, collections, discarded, outdated, path, tags, null): if not any([collections, discarded, list_tags, outdated, path, tags]): click.echo(ctx.get_help()) ctx.exit(1) sep = '\x00' if null else '\n' site = create_app().site if '*' in collections: ...
Query datasets. Use --collection=* to list all datasets across all collections.
def marvcli_tag(ctx, add, remove, datasets): if not any([add, remove]) or not datasets: click.echo(ctx.get_help()) ctx.exit(1) app = create_app() setids = parse_setids(datasets) app.site.tag(setids, add, remove)
Add or remove tags to datasets
def marvcli_comment_add(user, message, datasets): app = create_app() try: db.session.query(User).filter(User.name==user).one() except NoResultFound: click.echo("ERROR: No such user '{}'".format(user), err=True) sys.exit(1) ids = parse_setids(datasets, dbids=True) app.sit...
Add comment as user for one or more datasets
def marvcli_comment_list(datasets): app = create_app() ids = parse_setids(datasets, dbids=True) comments = db.session.query(Comment)\ .options(db.joinedload(Comment.dataset))\ .filter(Comment.dataset_id.in_(ids)) for comment in sorted(comments, key=...
Lists comments for datasets. Output: setid comment_id date time author message
def marvcli_comment_rm(ids): app = create_app() db.session.query(Comment)\ .filter(Comment.id.in_(ids))\ .delete(synchronize_session=False) db.session.commit()
Remove comments. Remove comments by id as given in second column of: marv comment list
def marvcli_user_add(ctx, username, password): if not re.match(r'[0-9a-zA-Z\-_\.@+]+$', username): click.echo('Invalid username: {}'.format(username), err=True) click.echo('Must only contain ASCII letters, numbers, dash, underscore and dot', err=True) sys.exit(1) ...
Add a user
def marvcli_user_list(): app = create_app() for name in db.session.query(User.name).order_by(User.name): click.echo(name[0])
List existing users
def marvcli_user_pw(ctx, username, password): app = create_app() try: app.um.user_pw(username, password) except ValueError as e: ctx.fail(e.args[0])
Change password
def marvcli_user_rm(ctx, username): app = create_app() try: app.um.user_rm(username) except ValueError as e: ctx.fail(e.args[0])
Remove a user