code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Determines the teacher backend link to the filtered list of gradable submissions for this assignment. ''' grading_url="%s?coursefilter=%u&assignmentfilter=%u&statefilter=tobegraded"%( reverse('teacher:opensubmit_submission_changelist'), ...
def grading_url(self)
Determines the teacher backend link to the filtered list of gradable submissions for this assignment.
17.541733
7.67049
2.286912
''' Figure out if any submission for this assignment has performance data being available. ''' num_results = SubmissionTestResult.objects.filter(perf_data__isnull=False).filter(submission_file__submissions__assignment=self).count() return num_results != 0
def has_perf_results(self)
Figure out if any submission for this assignment has performance data being available.
10.423643
4.286417
2.431785
''' Return absolute URL for assignment description. ''' if self.pk: if self.has_description(): return request.build_absolute_uri(reverse('assignment_description_file', args=[self.pk])) else: return self.download else: ...
def url(self, request)
Return absolute URL for assignment description.
6.115518
3.922298
1.559167
''' Central access control for submitting things related to assignments. ''' if user: # Super users, course owners and tutors should be able to test their validations # before the submission is officially possible. # They should also be able to sub...
def can_create_submission(self, user=None)
Central access control for submitting things related to assignments.
4.391956
3.847013
1.141654
''' Search for duplicates of submission file uploads for this assignment. This includes the search in other course, whether inactive or not. Returns a list of lists, where each latter is a set of duplicate submissions with at least on of them for this assignment ''' ...
def duplicate_files(self)
Search for duplicates of submission file uploads for this assignment. This includes the search in other course, whether inactive or not. Returns a list of lists, where each latter is a set of duplicate submissions with at least on of them for this assignment
8.235559
3.26536
2.522098
''' Main operation of the executor. Returns True when a job was downloaded and executed. Returns False when no job could be downloaded. ''' job = fetch_job(config) if job: job._run_validate() return True else: return False
def download_and_run(config)
Main operation of the executor. Returns True when a job was downloaded and executed. Returns False when no job could be downloaded.
8.68404
3.580788
2.425176
''' Local-only operation of the executor. Intended for validation script developers, and the test suite. Please not that this function only works correctly if the validator has one of the following names: - validator.py - validator.zip Returns True when a job was prepared a...
def copy_and_run(config, src_dir)
Local-only operation of the executor. Intended for validation script developers, and the test suite. Please not that this function only works correctly if the validator has one of the following names: - validator.py - validator.zip Returns True when a job was prepared and executed....
11.921677
2.138999
5.573483
''' The main entry point for the production administration script 'opensubmit-exec', installed by setuptools. ''' if len(sys.argv) == 1: print("opensubmit-exec [configcreate <server_url>|configtest|run|test <dir>|unlock|help] [-c config_file]") return 0 if "help"...
def console_script()
The main entry point for the production administration script 'opensubmit-exec', installed by setuptools.
4.464769
3.872364
1.152983
k = 0 for key,val in d.items(): k ^= hash(key) ^ hash(val) return k
def hashdict(d)
Hash a dictionary
3.499609
3.655127
0.957452
pop = cls(1,1,1,1,1) #dummy population pop.orbpop_long = OrbitPopulation.from_df(df_long) pop.orbpop_short = OrbitPopulation.from_df(df_short) return pop
def from_df(cls, df_long, df_short)
Builds TripleOrbitPopulation from DataFrame ``DataFrame`` objects must be of appropriate form to pass to :func:`OrbitPopulation.from_df`. :param df_long, df_short: :class:`pandas.DataFrame` objects to pass to :func:`OrbitPopulation.from_df`.
4.233851
4.183361
1.012069
df_long = pd.read_hdf(filename,'{}/long/df'.format(path)) df_short = pd.read_hdf(filename,'{}/short/df'.format(path)) return cls.from_df(df_long, df_short)
def load_hdf(cls, filename, path='')
Load TripleOrbitPopulation from saved .h5 file. :param filename: HDF file name. :param path: Path within HDF file where data is stored.
2.734327
3.21897
0.849442
if type(dt) != Quantity: dt *= u.day mean_motions = np.sqrt(G*(self.mred)*MSUN/(self.semimajor*AU)**3) mean_motions = np.sqrt(const.G*(self.mred)/(self.semimajor)**3) newM = self.M + mean_motions * dt pos,vel = orbit_posvel(newM,self.ecc,self.semimajor.valu...
def dRV(self,dt,com=False)
Change in RV of star 1 for time separation dt (default=days) :param dt: Time separation for which to compute RV change. If not a ``Quantity``, then assumed to be in days. :type dt: float, array-like, or ``Quantity`` :param com: (``bool``, optional) ...
5.970173
5.847863
1.020915
if type(ts) != Quantity: ts *= u.day if not recalc and hasattr(self,'RV_measurements'): if (ts == self.ts).all(): return self._RV_measurements else: pass RVs = Quantity(np.zeros((len(ts),self.N)),unit='km/s') ...
def RV_timeseries(self,ts,recalc=False)
Radial Velocity time series for star 1 at given times ts. :param ts: Times. If not ``Quantity``, assumed to be in days. :type ts: array-like or ``Quantity`` :param recalc: (optional) If ``False``, then if called with the exact same ``ts`` as las...
3.268298
3.503004
0.932999
return cls(df['M1'], df['M2'], df['P'], ecc=df['ecc'], mean_anomaly=df['mean_anomaly'], obsx=df['obsx'], obsy=df['obsy'], obsz=df['obsz'])
def from_df(cls, df)
Creates an OrbitPopulation from a DataFrame. :param df: :class:`pandas.DataFrame` object. Must contain the following columns: ``['M1','M2','P','ecc','mean_anomaly','obsx','obsy','obsz']``, i.e., as what is accessed via :attr:`OrbitPopulation.dataframe`. :return: ...
4.265654
2.210108
1.930065
df = pd.read_hdf(filename,'{}/df'.format(path)) return cls.from_df(df)
def load_hdf(cls, filename, path='')
Loads OrbitPopulation from HDF file. :param filename: HDF file :param path: Path within HDF file store where :class:`OrbitPopulation` is saved.
4.347116
5.875171
0.739913
pers = draw_raghavan_periods(n) eccs = draw_eccs(n,pers,**kwargs) return pers,eccs
def draw_pers_eccs(n,**kwargs)
Draw random periods and eccentricities according to empirical survey data.
7.514551
5.947167
1.263551
if np.size(per) == 1 or np.std(np.atleast_1d(per))==0: if np.size(per)>1: per = per[0] if per==0: es = np.zeros(n) else: ne=0 while ne<10: mask = np.absolute(np.log10(MSC_TRIPLEPERS)-np.log10(per))<binsize/2. ...
def draw_eccs(n,per=10,binsize=0.1,fuzz=0.05,maxecc=0.97)
draws eccentricities appropriate to given periods, generated according to empirical data from Multiple Star Catalog
3.09174
3.022162
1.023022
q = M1/M2 return ((R1+R2)*RSUN) > (rochelobe(q)*semimajors*AU)
def withinroche(semimajors,M1,R1,M2,R2)
Returns boolean array that is True where two stars are within Roche lobe
12.43577
10.755333
1.156242
return ((P*DAY/2/np.pi)**2*G*mstar*MSUN)**(1./3)/AU
def semimajor(P,mstar=1)
Returns semimajor axis in AU given P in days, mstar in solar masses.
9.869441
7.757694
1.272213
Ftot = 0 for mag in mags: Ftot += 10**(-0.4*mag) F1 = 10**(-0.4*mags[0]) return F1/Ftot
def fluxfrac(*mags)
Returns fraction of total flux in first argument, assuming all are magnitudes.
2.635865
2.320248
1.136027
if np.size(dm)>1: dm = np.atleast_1d(dm) return 10**(1+dm/5)
def dfromdm(dm)
Returns distance given distance modulus.
5.018775
4.965669
1.010695
if type(d)==Quantity: x = d.to('pc').value else: x = d #assumed to be pc if np.size(x)>1: d = np.atleast_1d(x) return 5*np.log10(x/10)
def distancemodulus(d)
Returns distance modulus given d in parsec.
4.268814
3.990934
1.069628
if np.size(mA) > 1: n = len(mA) else: mA = np.ones(n) * mA r = rand.random(n) is_single = r > (f_binary + f_triple) is_double = (r > f_triple) & (r < (f_binary + f_triple)) is_triple = r <= f_triple CwA = rand.random(n) < 0.5 CwB = ~CwA #these for Triples: ...
def mult_masses(mA, f_binary=0.4, f_triple=0.12, minmass=0.11, qmin=0.1, n=1e5)
Returns m1, m2, and m3 appropriate for TripleStarPopulation, given "primary" mass (most massive of system) and binary/triple fractions. star with m1 orbits (m2 + m3). This means that the primary mass mA will correspond either to m1 or m2. Any mass set to 0 means that component does not exist.
2.701729
2.675416
1.009835
coords = SkyCoord(ra,dec,unit='deg',frame=frame).transform_to('icrs') rah,ram,ras = coords.ra.hms decd,decm,decs = coords.dec.dms if decd > 0: decsign = '%2B' else: decsign = '%2D' url = 'http://ned.ipac.caltech.edu/cgi-bin/nph-calc?in_csys=Equatorial&in_equinox=J2000.0&obs...
def get_AV_infinity(ra,dec,frame='icrs')
Gets the A_V exctinction at infinity for a given line of sight. Queries the NED database using ``curl``. .. note:: It would be desirable to rewrite this to avoid dependence on ``curl``. :param ra,dec: Desired coordinates, in degrees. :param frame: (optional) Frame of...
2.576401
2.64621
0.973619
parts = [] path, tail = os.path.split(path) while path and tail: parts.append(tail) path, tail = os.path.split(path) parts.append(os.path.join(path, tail)) return map(os.path.normpath, parts)[::-1]
def split_path(path)
"/tmp/test" Becomes: ("/", "tmp", "test")
2.379101
2.721976
0.874035
return_files = [] for root, dirs, files in os.walk(path): # Skip hidden files files = [f for f in files if not f[0] == '.'] dirs[:] = [d for d in dirs if not d[0] == '.'] for filename in files: return_files.append(os.path.join(root, filename)) return return...
def get_files(path)
Returns a recursive list of all non-hidden files in and below the current directory.
1.781044
1.785758
0.99736
with open(filename, 'wb') as fout: pickle.dump(self, fout)
def save_pkl(self, filename)
Pickles TransitSignal.
2.753208
3.041568
0.905194
setfig(fig) plt.plot(self.ts,self.fs,'.',**kwargs) if plot_trap and hasattr(self,'trapfit'): if trap_kwargs is None: trap_kwargs = {} plt.plot(self.ts, traptransit(self.ts,self.trapfit), color=trap_color, **trap_kwargs) ...
def plot(self, fig=None, plot_trap=False, name=False, trap_color='g', trap_kwargs=None, **kwargs)
Makes a simple plot of signal :param fig: (optional) Argument for :func:`plotutils.setfig`. :param plot_trap: (optional) Whether to plot the (best-fit least-sq) trapezoid fit. :param name: (optional) Whether to annotate plot with the name of the signal; ...
2.865333
2.884665
0.993298
if xmin is None: xmin = kde.dataset.min() if xmax is None: xmax = kde.dataset.max() x = np.linspace(xmin,xmax,npts) return conf_interval(x,kde(x),shortest=shortest,conf=conf, conftol=conftol,return_max=return_max)
def kdeconf(kde,conf=0.683,xmin=None,xmax=None,npts=500, shortest=True,conftol=0.001,return_max=False)
Returns desired confidence interval for provided KDE object
1.861518
1.95795
0.950749
s = np.sort(x) n = np.size(x) lo = s[int(n*quant)] hi = s[int(n*(1-quant))] if top: w = np.where(x>=lo) elif bottom: w = np.where(x<=hi) else: w = np.where((x>=lo)&(x<=hi)) return np.std(x[w])
def qstd(x,quant=0.05,top=False,bottom=False)
returns std, ignoring outer 'quant' pctiles
1.89246
1.869991
1.012015
cum = np.cumsum(L) cdf = cum/cum.max() if shortest: maxind = L.argmax() if maxind==0: #hack alert maxind = 1 if maxind==len(L)-1: maxind = len(L)-2 Lval = L[maxind] lox = x[0:maxind] loL = L[0:maxind] locdf = cdf[0:maxin...
def conf_interval(x,L,conf=0.683,shortest=True, conftol=0.001,return_max=False)
Returns desired 1-d confidence interval for provided x, L[PDF]
2.935814
2.939451
0.998763
if units in self._units: raise ValueError('%s already defined' % units) if factor == 1: raise ValueError('Factor cannot be equal to 1') if latexrepr is None: latexrepr = units self._units[units] = factor self._latexrepr[units] = latex...
def add_units(self, units, factor, latexrepr=None)
Add new possible units. :arg units: units :type units: :class:`str` :arg factor: multiplication factor to convert new units into base units :type factor: :class:`float` :arg latexrepr: LaTeX representation of units (if ``None``, use *units) :ty...
2.338182
2.64858
0.882806
return value * self._units[units] / self._units[newunits]
def convert(self, value, units, newunits)
Converts a value expressed in certain *units* to a new units.
4.48525
4.191739
1.070021
if fig: plt.figure(fig,**kwargs) plt.clf() elif fig==0: pass else: plt.figure(**kwargs)
def setfig(fig=None,**kwargs)
Sets figure to 'fig' and clears; if fig is 0, does nothing (e.g. for overplotting) if fig is None (or anything else), creates new figure I use this for basically every function I write to make a plot. I give the function a "fig=None" kw argument, so that it will by default create a new figure. ...
3.366036
4.127364
0.815541
setfig(fig) if pts_only: plt.plot(xdata,ydata,**kwargs) return ok = (~np.isnan(xdata) & ~np.isnan(ydata) & ~np.isinf(xdata) & ~np.isinf(ydata)) if ~ok.sum() > 0: logging.warning('{} x values and {} y values are nan'.format(np.isnan(xdata).sum(), ...
def plot2dhist(xdata,ydata,cmap='binary',interpolation='nearest', fig=None,logscale=True,xbins=None,ybins=None, nbins=50,pts_only=False,**kwargs)
Plots a 2d density histogram of provided data :param xdata,ydata: (array-like) Data to plot. :param cmap: (optional) Colormap to use for density plot. :param interpolation: (optional) Interpolation scheme for display (passed to ``plt.imshow``). :param fig: (optional) ...
1.870491
1.964053
0.952363
teffs = np.atleast_1d(teff) loggs = np.atleast_1d(logg) Tmin,Tmax = (LDPOINTS[:,0].min(),LDPOINTS[:,0].max()) gmin,gmax = (LDPOINTS[:,1].min(),LDPOINTS[:,1].max()) teffs[(teffs < Tmin)] = Tmin + 1 teffs[(teffs > Tmax)] = Tmax - 1 loggs[(loggs < gmin)] = gmin + 0.01 loggs[(loggs > ...
def ldcoeffs(teff,logg=4.5,feh=0)
Returns limb-darkening coefficients in Kepler band.
2.081173
2.070871
1.004975
b_tra = a*AU*np.cos(inc)/(R*RSUN) * (1-ecc**2)/(1 + ecc*np.sin(w)) if return_occ: b_tra = a*AU*np.cos(inc)/(R*RSUN) * (1-ecc**2)/(1 - ecc*np.sin(w)) return b_tra, b_occ else: return b_tra
def impact_parameter(a, R, inc, ecc=0, w=0, return_occ=False)
a in AU, R in Rsun, inc & w in radians
3.129553
2.924796
1.070007
k = Rp*REARTH/(Rs*RSUN) if max_only: return 1 - mafn(k,b,u1,u2) if np.size(b) == 1: x = np.linspace(0,np.sqrt(1-b**2),npts) y = b zs = np.sqrt(x**2 + y**2) fs = mafn(k,zs,u1,u2) # returns array of shape (nks,nzs) depth = 1-fs else: xmax ...
def eclipse_depth(mafn,Rp,Rs,b,u1=0.394,u2=0.261,max_only=False,npts=100,force_1d=False)
Calculates average (or max) eclipse depth ***why does b>1 take so freaking long?...
3.569126
3.676159
0.970885
P,M1,M2,R1,R2 = (np.atleast_1d(P), np.atleast_1d(M1), np.atleast_1d(M2), np.atleast_1d(R1), np.atleast_1d(R2)) semimajors = semimajor(P,M1+M2) rads = ((R1+R2)*RSUN/(semimajors*AU)) ok = (~np.isnan(rads) & ~withinroc...
def minimum_inclination(P,M1,M2,R1,R2)
Returns the minimum inclination at which two bodies from two given sets eclipse Only counts systems not within each other's Roche radius :param P: Orbital periods. :param M1,M2,R1,R2: Masses and radii of primary and secondary stars.
2.94311
2.83778
1.037117
if planet: M2 *= REARTH/RSUN R2 *= MEARTH/MSUN return semimajor(P,M1+M2)*AU/(R1*RSUN)
def a_over_Rs(P,R2,M2,M1=1,R1=1,planet=True)
Returns a/Rs for given parameters.
10.152778
10.126059
1.002639
a = semimajor(P,M1+M2) if sec: b = a*AU*np.cos(inc*np.pi/180)/(R1*RSUN) * (1-ecc**2)/(1 - ecc*np.sin(w*np.pi/180)) #aR = a*AU/(R2*RSUN) #I feel like this was to correct a bug, but this should not be. #p0 = R1/R2 #why this also? else: b = a*AU*np.cos(inc*np.pi/180)/(R1*RS...
def eclipse_pars(P,M1,M2,R1,R2,ecc=0,inc=90,w=0,sec=False)
retuns p,b,aR from P,M1,M2,R1,R2,ecc,inc,w
3.239081
3.068675
1.055531
ts,fs = eclipse(p0=p0,b=b,aR=aR,P=P,ecc=ecc,w=w,npts=npts,u1=u1,u2=u2, conv=conv,cadence=cadence,frac=frac,sec=sec,tol=tol,width=width) #logging.debug('{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}'.format(p0,b,aR,P,ecc,w,xmax,npts,u1,u2,leastsq,conv,cadence,frac,s...
def eclipse_tt(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,conv=True, cadence=1626./86400,frac=1,sec=False,pars0=None,tol=1e-4,width=3)
Trapezoidal parameters for simulated orbit. All arguments passed to :func:`eclipse` except the following: :param pars0: (optional) Initial guess for least-sq optimization for trapezoid parameters. :return dur,dep,slope: Best-fit duration, depth, and T/tau for eclipse shape.
3.094413
3.252263
0.951465
pfit,success = leastsq(traptransit_resid,p0,args=(ts,fs)) if success not in [1,2,3,4]: raise NoFitError #logging.debug('success = {}'.format(success)) return pfit
def fit_traptransit(ts,fs,p0)
Fits trapezoid model to provided ts,fs
3.960328
4.100379
0.965844
if pars[0] < 0 or pars[1] < 0 or pars[2] < 2 or pars[2] > maxslope: return -np.inf fmod = traptransit(ts, pars) tot = 0 for i in range(len(ts)): tot += -0.5*(fmod[i] - fs[i])*(fmod[i] - fs[i]) / (sigs[i]*sigs[i]) #tot += np.log(1./pars[2]) #logflat prior on slope retur...
def traptransit_lhood(pars, ts, fs, sigs, maxslope=MAXSLOPE)
Params: depth, duration, slope, t0
3.148282
3.198336
0.98435
model = TraptransitModel(ts,fs,dfs,maxslope=maxslope) sampler = emcee.EnsembleSampler(nwalkers,4,model,threads=threads) T0 = p0[0]*(1+rand.normal(size=nwalkers)*0.1) d0 = p0[1]*(1+rand.normal(size=nwalkers)*0.1) slope0 = p0[2]*(1+rand.normal(size=nwalkers)*0.1) ep0 = p0[3]+rand.normal(size=...
def traptransit_MCMC(ts,fs,dfs=1e-5,nwalkers=200,nburn=300,niter=1000, threads=1,p0=[0.1,0.1,3,0],return_sampler=False, maxslope=MAXSLOPE)
Fit trapezoidal model to provided ts, fs, [dfs] using MCMC. Standard emcee usage.
1.739207
1.878033
0.926079
vault = VaultLib(get_vault_password(password_file)) with open(path, 'r') as f: encrypted_data = f.read() # Normally we'd just try and catch the exception, but the # exception raised here is not very specific (just # `AnsibleError`), so this feels safer to avoid suppressing ...
def backup(path, password_file=None)
Replaces the contents of a file with its decrypted counterpart, storing the original encrypted version and a hash of the file contents for later retrieval.
3.575937
3.564822
1.003118
vault = VaultLib(get_vault_password(password_file)) atk_path = os.path.join(ATK_VAULT, path) # Load stored data with open(os.path.join(atk_path, 'encrypted'), 'rb') as f: old_data = f.read() with open(os.path.join(atk_path, 'hash'), 'rb') as f: old_hash = f.read() # Load n...
def restore(path, password_file=None)
Retrieves a file from the atk vault and restores it to its original location, re-encrypting it if it has changed. :param path: path to original file
2.204529
2.213758
0.995831
r = (self.orbpop.Rsky/self.distance) return r.to('arcsec',equivalencies=u.dimensionless_angles())
def Rsky(self)
Projected angular distance between "primary" and "secondary" (exact meaning varies)
9.216099
8.184862
1.125993
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 combine them.') if ...
def append(self, other)
Appends stars from another StarPopulations, in place. :param other: Another :class:`StarPopulation`; must have same columns as ``self``.
3.956434
3.497379
1.131257
bands = [] for c in self.stars.columns: if re.search('_mag',c): bands.append(c) return bands
def bands(self)
Bandpasses for which StarPopulation has magnitude data
5.397959
3.914664
1.378907
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_distmod logg...
def distance(self,value)
New distance value must be a ``Quantity`` object
6.734417
5.946814
1.132441
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
def distok(self)
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.
6.064911
4.317186
1.40483
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
def countok(self)
Boolean array showing which stars pass all count constraints. A "count constraint" is a constraint that affects the number of stars.
8.064535
5.782385
1.394673
if mask is not None: inds = np.where(mask)[0] else: if selected: inds = self.selected.index else: inds = self.stars.index if selected: xvals = self.selected[propx].iloc[inds].values yvals = sel...
def prophist2d(self,propx,propy, mask=None, logx=False,logy=False, fig=None,selected=False,**kwargs)
Makes a 2d density histogram of two given properties :param propx,propy: Names of properties to histogram. Must be names of columns in ``self.stars`` table. :param mask: (optional) Boolean mask (``True`` is good) to say which indices to plot. Must be sa...
2.439579
2.267274
1.075997
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)) inds = self.selected.index else: #inds = np.arange(le...
def prophist(self,prop,fig=None,log=False, mask=None, selected=False,**kwargs)
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. ...
3.096037
3.042909
1.01746
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: continue c = self.constraints[nam...
def constraint_stats(self,primarylist=None)
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 ...
3.047045
3.022752
1.008037
setfig(fig,figsize=(6,6)) stats = self.constraint_stats(primarylist=primarylist) if primarylist is None: primarylist = [] if len(primarylist)==1: primaryname = primarylist[0] else: primaryname = '' for name in primarylist:...
def constraint_piechart(self,primarylist=None, fig=None,title='',colordict=None, legend=True,nolabels=False)
Makes piechart illustrating constraints on population :param primarylist: (optional) List of most import constraints to show (see :func:`StarPopulation.constraint_stats`) :param fig: (optional) Passed to :func:`plotutils.setfig`. :param title: (optional) ...
2.105155
2.096857
1.003957
try: return self._constraints except AttributeError: self._constraints = ConstraintDict() return self._constraints
def constraints(self)
Constraints applied to the population.
4.579884
3.869232
1.183667
try: return self._hidden_constraints except AttributeError: self._hidden_constraints = ConstraintDict() return self._hidden_constraints
def hidden_constraints(self)
Constraints applied to the population, but temporarily removed.
3.331918
3.020216
1.103205
#grab properties constraints = self.constraints my_selectfrac_skip = self.selectfrac_skip my_distribution_skip = self.distribution_skip if constraint.name in constraints and not overwrite: logging.warning('constraint already applied: {}'.format(constraint.na...
def apply_constraint(self,constraint,selectfrac_skip=False, distribution_skip=False,overwrite=False)
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
2.996261
3.388112
0.884345
hidden_constraints = self.hidden_constraints if name in hidden_constraints: c = hidden_constraints[name] self.apply_constraint(c,selectfrac_skip=selectfrac_skip, distribution_skip=distribution_skip) del hidden_constraints[nam...
def replace_constraint(self,name,selectfrac_skip=False,distribution_skip=False)
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`
2.940973
2.955916
0.994945
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] = constraints[name] del constrain...
def remove_constraint(self,name)
Remove a constraint (make it "hidden") :param name: Name of constraint.
2.610716
2.689123
0.970843
if prop in self.constraints: logging.info('re-doing {} constraint'.format(prop)) self.remove_constraint(prop) if measurement is not None: val,dval = measurement self.apply_constraint(MeasurementConstraint(getattr(self.stars,prop), ...
def constrain_property(self,prop,lo=-np.inf,hi=np.inf, measurement=None,thresh=3, selectfrac_skip=False,distribution_skip=False)
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...
2.4205
2.571872
0.941144
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(dRVs, limit) c2 = LowerLimit(self.Plong, dt*4) self.apply_constraint(JointConstraintOr(c1,c2,na...
def apply_trend_constraint(self, limit, dt, distribution_skip=False, **kwargs)
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. ...
6.466494
4.862367
1.329907
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)
def apply_cc(self, cc, distribution_skip=False, **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...
9.404558
4.759861
1.975805
rvs = self.RV.value dmags = self.dmag(vcc.band) self.apply_constraint(VelocityContrastCurveConstraint(rvs,dmags,vcc, name='secondary spectrum'), distribution_skip=distribution_skip, **kwargs)
def apply_vcc(self, vcc, distribution_skip=False, **kwargs)
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...
12.738177
5.884196
2.164812
self.maxrad = maxrad self.apply_constraint(UpperLimit(self.Rsky,maxrad, name='Max Rsky'), overwrite=True, distribution_skip=distribution_skip)
def set_maxrad(self,maxrad, distribution_skip=True)
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 ...
8.107311
5.944071
1.363932
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
def constraint_df(self)
A DataFrame representing all constraints, hidden or not
3.377128
2.778013
1.215663
if os.path.exists(filename): with pd.HDFStore(filename) as store: if path in store: if overwrite: os.remove(filename) elif not append: raise IOError('{} in {} exists. '.format(path,filen...
def save_hdf(self,filename,path='',properties=None, overwrite=False, append=False)
Saves to HDF5 file. Subclasses should be sure to define ``_properties`` attribute to ensure that all correct attributes get saved. Load a saved population with :func:`StarPopulation.load_hdf`. Example usage:: >>> from vespa.stars import Raghavan_BinaryPopulation, ...
3.38345
3.482915
0.971442
stars = pd.read_hdf(filename,path+'/stars') constraint_df = pd.read_hdf(filename,path+'/constraints') with pd.HDFStore(filename) as store: has_orbpop = '{}/orbpop/df'.format(path) in store has_triple_orbpop = '{}/orbpop/long/df'.format(path) in store ...
def load_hdf(cls, filename, path='')
Loads StarPopulation from .h5 file Correct properties should be restored to object, and object will be original type that was saved. Complement to :func:`StarPopulation.save_hdf`. Example usage:: >>> from vespa.stars import Raghavan_BinaryPopulation, StarPopulation ...
4.085737
4.223425
0.967399
subdf = self.stars.query(query) nbinaries = (subdf['mass_B'] > 0).sum() frac = nbinaries/len(subdf) return frac, frac/np.sqrt(nbinaries)
def binary_fraction(self,query='mass_A >= 0')
Binary fraction of stars passing given query :param query: Query to pass to stars ``DataFrame``.
4.423762
4.992807
0.886027
mag2 = self.stars['{}_mag_B'.format(band)] mag1 = self.stars['{}_mag_A'.format(band)] return mag2-mag1
def dmag(self,band)
Difference in magnitude between primary and secondary stars :param band: Photometric bandpass.
4.049394
4.642201
0.8723
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,smooth=smooth) return dist
def rsky_distribution(self,rmax=None,smooth=0.1,nbins=100)
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...
3.388051
3.565356
0.95027
dist = self.rsky_distribution(**kwargs) return dist(rsky)
def rsky_lhood(self,rsky,**kwargs)
Evaluates Rsky likelihood at provided position(s) :param rsky: position :param **kwargs: Keyword arguments passed to :func:`BinaryPopulation.rsky_distribution`
7.311396
6.994016
1.045379
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.minmass/M)) P = self.P_fn(n) ecc = self.ecc_fn(n,P) mass = np.ascontiguousarray(n...
def generate(self, M, age=9.6, feh=0.0, ichrone='mist', n=1e4, bands=None, **kwargs)
Function that generates population. Called by ``__init__`` if ``M`` is passed.
3.422505
3.626358
0.943786
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)
def dmag(self, band)
Difference in magnitudes between fainter and brighter components in band. :param band: Photometric bandpass.
3.315945
3.75372
0.883376
mA = self.stars['{}_mag_A'.format(band)] mBC = addmags(self.stars['{}_mag_B'.format(band)], self.stars['{}_mag_C'.format(band)]) return mA < mBC
def A_brighter(self, band='g')
Instances where star A is brighter than (B+C)
4.752012
3.63686
1.306625
return (self.orbpop.dRV_1(dt)*self.A_brighter(band) + self.orbpop.dRV_2(dt)*self.BC_brighter(band))
def dRV(self, dt, band='g')
Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter
8.051139
5.787158
1.391208
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
def triple_fraction(self,query='mass_A > 0', unc=False)
Triple fraction of stars following given query
2.798991
2.700805
1.036354
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: e_mag = mag_errs[b] ...
def starmodel_props(self)
Default mag_err is 0.05, arbitrarily
2.068981
1.950953
1.060498
ichrone = get_ichrone(ichrone, bands=bands) n = int(n) #star with m1 orbits (m2+m3). So mA (most massive) # will correspond to either m1 or m2. m1, m2, m3 = self.multmass_fn(mA, f_binary=self.f_binary, f_triple=self.f_triple, ...
def generate(self, mA=1, age=9.6, feh=0.0, n=1e5, ichrone='mist', orbpop=None, bands=None, **kwargs)
Generates population. Called if :class:`MultipleStarPopulation` is initialized without providing ``stars``, and if ``mA`` is provided.
2.634753
2.671444
0.986266
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]
def dmag(self,band)
Magnitude difference between primary star and BG stars
7.097583
6.690147
1.060901
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._timing) se...
def send(self)
I send data through a wormhole and return True/False depending on whether or not the hash matched at the receive side.
8.101114
7.226672
1.121002
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 Confirmed!') ...
def receive(self)
I receive data+hash, check for a match, confirm or not confirm to the sender, and return the data payload.
6.288065
5.809943
1.082294
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()
def validator(ch)
Update screen if necessary and release the lock so receiveThread can run
8.044226
4.799675
1.675994
new = copy.deepcopy(self) for arr in self.arrays: x = getattr(new, arr) setattr(new, arr, x[inds]) return new
def resample(self, inds)
Returns copy of constraint, with mask rearranged according to indices
4.245183
4.236289
1.0021
self.save_popset(overwrite=overwrite) self.save_signal()
def save(self, overwrite=True)
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...
13.787428
8.496959
1.622631
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)
def load(cls, folder)
Loads PopulationSet from folder ``popset.h5`` and ``trsig.pkl`` must exist in folder. :param folder: Folder from which to load.
3.668102
2.761625
1.32824
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,tag=tag) self.plotsignal(folder=folder,saveplot=True,figfo...
def FPPplots(self, folder=None, format='png', tag=None, **kwargs)
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...
3.853676
3.076428
1.252646
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()
def plotsignal(self,fig=None,saveplot=True,folder=None,figformat='png',**kwargs)
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...
4.589975
4.947919
0.927658
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_{0} L_{0} pr_{0} '.format(m) header += 'fpV fp FPP' if to_fi...
def write_results(self,folder=None, filename='results.txt', to_file=True)
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. ...
3.424531
3.578346
0.957015
self.popset.save_hdf(os.path.join(self.folder,filename))
def save_popset(self,filename='popset.h5',**kwargs)
Saves the PopulationSet Calls :func:`PopulationSet.save_hdf`.
4.180567
4.48055
0.933048
if filename is None: filename = os.path.join(self.folder,'trsig.pkl') self.trsig.save(filename)
def save_signal(self,filename=None)
Saves TransitSignal. Calls :func:`TransitSignal.save`; default filename is ``trsig.pkl`` in ``self.folder``.
4.252032
2.576774
1.650138
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 = ROBOVETDATA.ix[tce] except ...
def modelshift_weaksec(koi)
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)
3.664864
3.08413
1.188298
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))
def use_property(kepid, prop)
Returns true if provenance of property is SPE or AST
10.482559
7.186885
1.458568
folder = os.path.join(KOI_FPPDIR, ku.koiname(koi)) if not os.path.exists(folder): os.makedirs(folder) config = ConfigObj(os.path.join(folder,'star.ini')) koi = ku.koiname(koi) maxAV = koi_maxAV(koi) config['maxAV'] = maxAV mags = ku.KICmags(koi) for band in bands: ...
def star_config(koi, bands=['g','r','i','z','J','H','K'], unc=dict(g=0.05, r=0.05, i=0.05, z=0.05, J=0.02, H=0.02, K=0.02), **kwargs)
returns star config object for given KOI
2.191169
2.220921
0.986604
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) config['ra'] = ra config...
def fpp_config(koi, **kwargs)
returns config object for given KOI
4.983454
4.899036
1.017231
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))
def apply_default_constraints(self)
Applies default secthresh & exclusion radius constraints
19.210077
12.998304
1.477891
r = re.compile(r'index ([a-fA-F\d]*)') return r.search(diff_part).groups()[0]
def get_old_sha(diff_part)
Returns the SHA for the original file that was changed in a diff part.
4.611524
4.106813
1.122896
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: return match.groups()[0] rai...
def get_old_filename(diff_part)
Returns the filename for the original file that was changed in a diff part.
3.799957
3.679816
1.032649