code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
for format in FORMATS: if extension in format.extensions: return format raise UnknownFormat('No format found with extension "%s"' % extension)
def find_by_extension(extension)
Find and return a format by extension. :param extension: A string describing the extension of the format.
4.523257
4.9955
0.905466
for format in FORMATS: if content_type in format.content_types: return format raise UnknownFormat('No format found with content type "%s"' % content_type)
def find_by_content_type(content_type)
Find and return a format by content type. :param content_type: A string describing the internet media type of the format.
3.944178
4.128607
0.955329
options = {} for method, function in map.items(): options[method] = function.__doc__ return self._render( request = request, template = 'options', context = { 'options': options }, status = 200, ...
def options(self, request, map, *args, **kwargs)
List communication options.
3.512081
3.427682
1.024623
# Derive a list of 'formats.Format' instances from the list of formats these views support. supported_formats = [formats.find(format) for format in self.supported_formats] # Determine format by extension... if '.' in request.path: extension = request.path.split('.'...
def _get_format(self, request)
Determine and return a 'formats.Format' instance describing the most desired response format that is supported by these views. :param request: A django.http.HttpRequest instance. Formats specified by extension (e.g. '/articles/index.html') take precedence over formats given in the HTTP...
3.595019
3.00523
1.196254
format = self._get_format(request) # Render 406 Not Acceptable if the requested format isn't supported. if not format: return HttpResponse(status=406) if template: if prefix_template_path: template_path = '%s.%s' % (self.template_path ...
def _render(self, request, template=None, status=200, context={}, headers={}, prefix_template_path=True)
Render a HTTP response. :param request: A django.http.HttpRequest instance. :param template: A string describing the path to a template. :param status: An integer describing the HTTP status code to respond with. :param context: A dictionary describing variables to populate the template ...
2.191151
2.096727
1.045034
return self._render( request = request, template = str(status), status = status, context = { 'error': kwargs }, headers = headers, prefix_template_path = prefix_template_path )
def _error(self, request, status, headers={}, prefix_template_path=False, **kwargs)
Convenience method to render an error response. The template is inferred from the status code. :param request: A django.http.HttpRequest instance. :param status: An integer describing the HTTP status code to respond with. :param headers: A dictionary describing HTTP headers. :param pref...
3.688787
3.454371
1.067861
try: serializer = SERIALIZERS[format] except KeyError: raise UnknownSerializer('No serializer found for %s' % format.acronym) return serializer
def find(format)
Find and return a serializer for the given format. Arguments: format -- A Format instance.
6.776724
5.308587
1.276559
def serialize(anything): def serialize_dictionary(dictionary): data = OrderedDict() # Serialize each of the dictionary's keys for key, value in dictionary.items(): data.update({ key: serialize(value) }) ...
def serialize(self, request)
Serialize the given object into into simple data types (e.g. lists, dictionaries, strings).
1.827886
1.81158
1.009001
update_data ={} sfdict = self.filter_class.get_search_fields() for fieldname in sfdict: try: has_multiple = sfdict[fieldname].get('multiple', False) except: has_multiple = False if has_multiple: value =...
def get_form_kwargs(self)
Returns the keyword arguments for instantiating the search form.
2.569042
2.501005
1.027204
rules = [ ['(?i)(quiz)$' , '\\1zes'], ['^(?i)(ox)$' , '\\1en'], ['(?i)([m|l])ouse$' , '\\1ice'], ['(?i)(matr|vert|ind)ix|ex$' , '\\1ices'], ['(?i)(x|ch|ss|sh)$' , '\\1es'], ['(?i)([^aeiouy]|qu)ies$' , '\\1y'], ['(?i)([...
def pluralize(word)
Pluralize an English noun.
1.702854
1.674381
1.017005
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
def us2mc(string)
Transform an underscore_case string to a mixedCase string
3.423477
2.688015
1.273608
_model, _fields, _exclude = model, fields, exclude class Form(form or forms.ModelForm): class Meta: model = _model if _fields is not False: fields = _fields if _exclude is not False: exclude = _exclude return Form
def generate_form(model, form=None, fields=False, exclude=False)
Generate a form from a model. :param model: A Django model. :param form: A Django form. :param fields: A list of fields to include in this form. :param exclude: A list of fields to exclude in this form.
2.525443
3.929349
0.642713
return _Route(regex, view, method, name)
def route(regex, view, method, name)
Route the given view. :param regex: A string describing a regular expression to which the request path will be matched. :param view: A string describing the name of the view to delegate the request to. :param method: A string describing the HTTP method that this view accepts. :param name: A string ...
4.988716
9.888269
0.504508
from scipy.special import erfinv # There's probably a better way to do this. We first draw percentiles # uniformly between 0 and 1. We want the peak of the distribution to occur # at `mean`. However, if we assign 50% of the samples to the lower half # and 50% to the upper half, the side with t...
def sample_double_norm(mean, std_upper, std_lower, size)
Note that this function requires Scipy.
4.360686
4.356643
1.000928
if alpha <= 0: raise ValueError('alpha must be positive; got %e' % alpha) if beta <= 0: raise ValueError('beta must be positive; got %e' % beta) return np.random.gamma(alpha, scale=1./beta, size=size)
def sample_gamma(alpha, beta, size)
This is mostly about recording the conversion between Numpy/Scipy conventions and Wikipedia conventions. Some equations: mean = alpha / beta variance = alpha / beta**2 mode = (alpha - 1) / beta [if alpha > 1; otherwise undefined] skewness = 2 / sqrt(alpha)
2.157032
2.446835
0.88156
if mode < 0: raise ValueError('input mode must be positive for gamma; got %e' % mode) var = std**2 beta = (mode + np.sqrt(mode**2 + 4 * var)) / (2 * var) j = 2 * var / mode**2 alpha = (j + 1 + np.sqrt(2 * j + 1)) / j if alpha <= 1: raise ValueError('couldn\'t compute self-...
def find_gamma_params(mode, std)
Given a modal value and a standard deviation, compute corresponding parameters for the gamma distribution. Intended to be used to replace normal distributions when the value must be positive and the uncertainty is comparable to the best value. Conversion equations determined from the relations given in...
4.073089
3.941369
1.03342
if x < 0: if polarity < 0: return Lval('toinf', x) return Lval('pastzero', x) elif polarity > 0: return Lval('toinf', x) return Lval('pastzero', x)
def _lval_add_towards_polarity(x, polarity)
Compute the appropriate Lval "kind" for the limit of value `x` towards `polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and the infinity direction of polarity.
3.942808
2.164517
1.821565
if np.isscalar(msmt): return float(msmt) if isinstance(msmt, (Uval, Lval)): return msmt if isinstance(msmt, Textual): return msmt.unwrap() raise ValueError('don\'t know how to treat %r as a measurement' % msmt)
def unwrap(msmt)
Convert the value into the most basic representation that we can do math on: float if possible, then Uval, then Lval.
4.653044
3.322364
1.400522
if np.isscalar(msmt): return float(msmt) if isinstance(msmt, Uval): return msmt.repvals(uval_default_repval_method)[0] if isinstance(msmt, Lval): if not limitsok and msmt.kind in('tozero', 'toinf', 'pastzero'): raise LimitError() return msmt.value if isi...
def repval(msmt, limitsok=False)
Get a best-effort representative value as a float. This is DANGEROUS because it discards limit information, which is rarely wise. m_liminfo() or m_unwrap() are recommended instead.
5.250868
5.254738
0.999263
if np.isscalar(msmt): return 0 if isinstance(msmt, Uval): return 0 if isinstance(msmt, Lval): if msmt.kind == 'undef': raise ValueError('no simple limit type for Lval %r' % msmt) # Quasi-hack here: limits of ('tozero', [positive number]) are # repor...
def limtype(msmt)
Return -1 if this value is some kind of upper limit, 1 if this value is some kind of lower limit, 0 otherwise.
7.867776
7.372815
1.067133
if isinstance(msmt, Textual): msmt = msmt.unwrap() if np.isscalar(msmt): return 0, msmt, msmt, msmt if isinstance(msmt, Uval): rep, plus1, minus1 = msmt.repvals(uval_default_repval_method) return 0, rep, plus1, minus1 if isinstance(msmt, Lval): return lim...
def errinfo(msmt)
Return (limtype, repval, errval1, errval2). Like m_liminfo, but also provides error bar information for values that have it.
5.133607
4.589456
1.118566
if value is None: raise ValueError('cannot format None!') if isinstance(value, text_type): return '', value, False if isinstance(value, bool): # Note: isinstance(True, int) = True, so this must come before the next case. if value: return 'b', 'y', False ...
def fmtinfo(value)
Returns (typetag, text, is_imprecise). Unlike other functions that operate on measurements, this also operates on bools, ints, and strings.
3.618635
3.073164
1.177495
if nevents < 0: raise ValueError('Poisson parameter `nevents` must be nonnegative') return Uval(np.random.gamma(nevents + 1, size=uval_nsamples))
def from_pcount(nevents)
We assume a Poisson process. nevents is the number of events in some interval. The distribution of values is the distribution of the Poisson rate parameter given this observed number of events, where the "rate" is in units of events per interval of the same duration. The max-likelihood v...
8.074291
6.124959
1.318261
if method == 'pct': return pk_scoreatpercentile(self.d, [50., 84.134, 15.866]) if method == 'gauss': m, s = self.d.mean(), self.d.std() return np.asarray([m, m + s, m - s]) raise ValueError('unknown representative-value method "%s"' % method)
def repvals(self, method)
Compute representative statistical values for this Uval. `method` may be either 'pct' or 'gauss'. Returns (best, plus_one_sigma, minus_one_sigma), where `best` is the "best" value in some sense, and the others correspond to values at the ~84 and 16 percentile limits, respectively. Becau...
6.140901
3.421805
1.794638
md, hi, lo = self.repvals(method) if hi == lo: return '%g' % lo, None, None, None if not np.isfinite([lo, md, hi]).all(): raise ValueError('got nonfinite values when formatting Uval') # Deltas. Round to limited # of places because we don't actually kno...
def text_pieces(self, method, uplaces=2, use_exponent=True)
Return (main, dhigh, dlow, sharedexponent), all as strings. The delta terms do not have sign indicators. Any item except the first may be None. `method` is passed to Uval.repvals() to compute representative statistical limits.
4.282757
4.034471
1.061541
if not limitsok and self.dkind in ('lower', 'upper'): raise LimitError() if self.dkind == 'unif': lower, upper = map(float, self.data) v = 0.5 * (lower + upper) elif self.dkind in _noextra_dkinds: v = float(self.data) elif self.d...
def repval(self, limitsok=False)
Get a best-effort representative value as a float. This can be DANGEROUS because it discards limit information, which is rarely wise.
4.908535
4.77194
1.028625
if vis is None: raise ValueError ('vis') helper.casans.plotants (vis=vis, figfile=figfile)
def in_casapy (helper, vis=None, figfile=None)
This function is run inside the weirdo casapy IPython environment! A strange set of modules is available, and the `pwkit.environments.casa.scripting` system sets up a very particular environment to allow encapsulated scripting.
11.613284
11.721037
0.990807
payload = { "node": node, "apiKey": api_key } if dataset: payload["datasetName"] = dataset if ll and ur: payload["lowerLeft"] = { "latitude": ll["latitude"], "longitude": ll["longitude"] } payload["upperRight"] = { ...
def datasets(dataset, node, ll=None, ur=None, start_date=None, end_date=None, api_key=None)
This method is used to find datasets available for searching. By passing no parameters except node, all available datasets are returned. Additional parameters such as temporal range and spatial bounding box can be used to find datasets that provide more specific data. The dataset name parameter can ...
1.768151
1.884581
0.93822
payload = { "datasetName": dataset, "node": node, "apiKey": api_key, "entityIds": entityids, "products": products } return json.dumps(payload)
def download(dataset, node, entityids, products, api_key=None)
The use of this request will be to obtain valid data download URLs. :param dataset: :param entityIds: list :param products: list :param node: :param api_key: API key is required.
2.881886
3.007621
0.958194
payload = { "apiKey": api_key, "datasetName": dataset, "node": node, "entityIds": entityids } return json.dumps(payload)
def download_options(dataset, node, entityids, api_key=None)
The use of the download options request is to discover the different download options for each scene. Some download options may exist but still be unavailable due to disk usage and many other factors. If a download is unavailable it may need to be ordered. :param dataset: :param node: ...
2.948718
3.701022
0.796731
payload = { "username": username, "password": password, "authType": "", "catalogId": catalogId } return json.dumps(payload)
def login(username, password, catalogId='EE')
This method requires SSL be used due to the sensitive nature of users passwords. Upon a successful login, an API key will be returned. This key will be active for one hour and should be destroyed upon final use of the service by calling the logout method. Users must have "Machine to Machine" access base...
3.218841
5.955341
0.540497
payload = { "apiKey": api_key, "datasetName": dataset, "node": node, "entityIds": entityids } return json.dumps(payload)
def metadata(dataset, node, entityids, api_key=None)
The use of the metadata request is intended for those who have acquired scene IDs from a different source. It will return the same metadata that is available via the search request. :param dataset: :param node: :param sceneid: :param api_key:
2.962184
4.187809
0.707335
payload = { "datasetName": dataset, "node": node, "apiKey": api_key, } # Latitude and longitude take precedence over ll and ur if lat and lng: lats, lngs = great_circle_dist(lat, lng, distance / 2.0) ll = { "longitude": min(*lngs), "latitude": min(*lats) ...
def search(dataset, node, lat=None, lng=None, distance=100, ll=None, ur=None, start_date=None, end_date=None, where=None, max_results=50000, starting_number=1, sort_order="DESC", api_key=None)
:param dataset: :param node: :param lat: :param lng: :param ll: :param distance: :param ur: :param start_date: :param end_date: :param where: Specify additional search criteria :param max_results: :param starting_...
3.190214
3.239914
0.98466
import scipy.interpolate as SI values = samples[0] if transform == 'none': pass elif transform == 'reverse': samples = samples[:,::-1] elif transform == 'sqrt': values = np.sqrt (values) else: raise ValueError ('unknown transformation: ' + str (transform)) ...
def approx_colormap (samples, transform='none', fitfactor=1.)
Given a colormap sampled at various values, compute splines that interpolate in R, G, and B (separately) for fast evaluation of the colormap for arbitrary float values. We have primitive support for some transformations, though these are generally best done upstream of the color mapping code. sampl...
2.552688
2.264028
1.127499
gamma = ((srgb + 0.055) / 1.055)**2.4 scale = srgb / 12.92 return np.where (srgb > 0.04045, gamma, scale)
def srgb_to_linsrgb (srgb)
Convert sRGB values to physically linear ones. The transformation is uniform in RGB, so *srgb* can be of any shape. *srgb* values should range between 0 and 1, inclusively.
2.771287
3.245692
0.853835
# From Wikipedia, but easy analogue to the above. gamma = 1.055 * linsrgb**(1./2.4) - 0.055 scale = linsrgb * 12.92 return np.where (linsrgb > 0.0031308, gamma, scale)
def linsrgb_to_srgb (linsrgb)
Convert physically linear RGB values into sRGB ones. The transform is uniform in the components, so *linsrgb* can be of any shape. *linsrgb* values should range between 0 and 1, inclusively.
4.314669
4.837587
0.891905
norm = xyz / refwhite pow = norm**0.333333333333333 scale = 7.787037 * norm + 16./116 mapped = np.where (norm > 0.008856, pow, scale) cielab = np.empty_like (xyz) cielab[...,L] = 116 * mapped[...,Y] - 16 cielab[...,A] = 500 * (mapped[...,X] - mapped[...,Y]) cielab[...,B] = 200 * (m...
def xyz_to_cielab (xyz, refwhite)
Convert CIE XYZ color values to CIE L*a*b*. *xyz* should be of shape (*, 3). *refwhite* is the reference white value, of shape (3, ). Return value will have same shape as *xyz*, but be in CIE L*a*b* coordinates.
2.469978
2.701642
0.914251
def func (t): pow = t**3 scale = 0.128419 * t - 0.0177129 return np.where (t > 0.206897, pow, scale) xyz = np.empty_like (cielab) lscale = 1./116 * (cielab[...,L] + 16) xyz[...,X] = func (lscale + 0.002 * cielab[...,A]) xyz[...,Y] = func (lscale) xyz[...,Z] = func (...
def cielab_to_xyz (cielab, refwhite)
Convert CIE L*a*b* color values to CIE XYZ, *cielab* should be of shape (*, 3). *refwhite* is the reference white value in the L*a*b* color space, of shape (3, ). Return value has same shape as *cielab*
3.701365
3.919998
0.944226
msh = np.empty_like (cielab) msh[...,M] = np.sqrt ((cielab**2).sum (axis=-1)) msh[...,S] = np.arccos (cielab[...,L] / msh[...,M]) msh[...,H] = np.arctan2 (cielab[...,B], cielab[...,A]) return msh
def cielab_to_msh (cielab)
Convert CIE L*a*b* to Moreland's Msh colorspace. *cielab* should be of shape (*, 3). Return value will have same shape.
2.264509
2.366334
0.956969
cielab = np.empty_like (msh) cielab[...,L] = msh[...,M] * np.cos (msh[...,S]) cielab[...,A] = msh[...,M] * np.sin (msh[...,S]) * np.cos (msh[...,H]) cielab[...,B] = msh[...,M] * np.sin (msh[...,S]) * np.sin (msh[...,H]) return cielab
def msh_to_cielab (msh)
Convert Moreland's Msh colorspace to CIE L*a*b*. *msh* should be of shape (*, 3). Return value will have same shape.
1.838157
1.853193
0.991886
if msh[M] >= m_unsat: return msh[H] # "Best we can do" hspin = (msh[S] * np.sqrt (m_unsat**2 - msh[M]**2) / (msh[M] * np.sin (msh[S]))) if msh[H] > -np.pi / 3: # "Spin away from purple" return msh[H] + hspin return msh[H] - hspin
def moreland_adjusthue (msh, m_unsat)
Moreland's AdjustHue procedure to adjust the hue value of an Msh color based on ... some criterion. *msh* should be of of shape (3, ). *m_unsat* is a scalar. Return value is the adjusted h (hue) value.
5.507841
5.356243
1.028303
msh1, msh2 = srgb_to_msh (np.asarray ([srgb1, srgb2], dtype=np.float), refwhite) raddiff = msh1[H] - msh2[H] while raddiff > np.pi: raddiff -= 2 * np.pi while raddiff < -np.pi: raddiff += 2 * np.pi raddiff = np.abs (raddiff) x = n...
def moreland_interpolate_sampled (srgb1, srgb2, refwhite=CIELAB_D65, nsamples=DEFAULT_SAMPLE_POINTS)
Adapted from Moreland's InterpolateColor. This uses the full transformations to compute a color mapping at a set of sampled points.
2.331102
2.345262
0.993962
data_dir = os.path.join(scriptdir, "..", "usgs", "data") cwic = map(lambda d: d["datasetName"], api.datasets(None, CWIC_LSI_EXPLORER_CATALOG_NODE)['data']) ee = map(lambda d: d["datasetName"], api.datasets(None, EARTH_EXPLORER_CATALOG_NODE)['data']) hdds = map(lambda d: d["datasetName"], api.data...
def get_datasets_in_nodes()
Get the node associated with each dataset. Some datasets will have an ambiguous node since they exists in more than one node.
2.277278
2.182643
1.043358
from scipy.integrate import simps return np.sqrt(simps(bpass.resp, bpass.wlen) / simps(bpass.resp / bpass.wlen**2, bpass.wlen))
def pivot_wavelength_ee(bpass)
Compute pivot wavelength assuming equal-energy convention. `bpass` should have two properties, `resp` and `wlen`. The units of `wlen` can be anything, and `resp` need not be normalized in any particular way.
4.200397
2.971054
1.413773
from scipy.interpolate import interp1d from scipy.optimize import fmin x = np.asarray(x) y = np.asarray(y) halfmax = 0.5 * y.max() # Guess from the actual samples. delta = y - halfmax guess1 = 0 while delta[guess1] < 0: guess1 += 1 guess2 = y.size - 1 while de...
def interpolated_halfmax_points(x, y)
Given a curve y(x), find the x coordinates of points that have half the value of max(y), using linear interpolation. We're assuming that y(x) has a bandpass-ish shape, i.e., a single maximum and a drop to zero as we go to the edges of the function's domain. We also assume that x is sorted increasingly.
2.489362
2.469909
1.007876
from six import itervalues reg = Registry() for fn in itervalues(builtin_registrars): fn(reg) return reg
def get_std_registry()
Get a Registry object pre-filled with information for standard telescopes.
8.128216
8.824004
0.921148
wl = self.registry._pivot_wavelengths.get((self.telescope, self.band)) if wl is not None: return wl wl = self.calc_pivot_wavelength() self.registry.register_pivot_wavelength(self.telescope, self.band, wl) return wl
def pivot_wavelength(self)
Get the bandpass' pivot wavelength. Unlike calc_pivot_wavelength(), this function will use a cached value if available.
3.47908
3.114119
1.117196
d = self._ensure_data() return interpolated_halfmax_points(d.wlen, d.resp)
def calc_halfmax_points(self)
Calculate the wavelengths of the filter half-maximum values.
22.156849
16.522314
1.341026
t = self.registry._halfmaxes.get((self.telescope, self.band)) if t is not None: return t t = self.calc_halfmax_points() self.registry.register_halfmaxes(self.telescope, self.band, t[0], t[1]) return t
def halfmax_points(self)
Get the bandpass' half-maximum wavelengths. These can be used to compute a representative bandwidth, or for display purposes. Unlike calc_halfmax_points(), this function will use a cached value if available.
4.149767
3.615988
1.147617
if self.native_flux_kind == 'flam': return flam_ang_to_fnu_cgs(self.mag_to_flam(mag), self.pivot_wavelength()) raise PKError('dont\'t know how to get f_ν from mag for bandpass %s/%s', self.telescope, self.band)
def mag_to_fnu(self, mag)
Convert a magnitude in this band to a f_ν flux density. It is assumed that the magnitude has been computed in the appropriate photometric system. The definition of "appropriate" will vary from case to case.
11.642294
9.981237
1.166418
from scipy.interpolate import interp1d from scipy.integrate import romberg d = self._ensure_data() mflam = interp1d(wlen, flam, kind='linear', bounds_error=False, fill_value=0) mresp = interp1d(d.wlen, d.resp, ...
def synphot(self, wlen, flam)
`wlen` and `flam` give a tabulated model spectrum in wavelength and f_λ units. We interpolate linearly over both the model and the bandpass since they're both discretely sampled. Note that quadratic interpolation is both much slower and can blow up fatally in some cases. The latter issu...
2.767588
2.748282
1.007025
from scipy.integrate import simps d = self._ensure_data() # factor of pi is going from specific intensity (sr^-1) to unidirectional # inner factor of 1e-8 is Å to cm # outer factor of 1e-8 is f_λ in cm^-1 to f_λ in Å^-1 from .cgs import blambda numer_sa...
def blackbody(self, T)
Calculate the contribution of a blackbody through this filter. *T* is the blackbody temperature in Kelvin. Returns a band-averaged spectrum in f_λ units. We use the composite Simpson's rule to integrate over the points at which the filter response is sampled. Note that this is a differe...
7.927115
7.648868
1.036378
q = self._seen_bands.get(telescope) if q is None: return [] return list(q)
def bands(self, telescope)
Return a list of bands associated with the specified telescope.
5.541558
5.241507
1.057245
if (telescope, band) in self._pivot_wavelengths: raise AlreadyDefinedError('pivot wavelength for %s/%s already ' 'defined', telescope, band) self._note(telescope, band) self._pivot_wavelengths[telescope,band] = wlen return self
def register_pivot_wavelength(self, telescope, band, wlen)
Register precomputed pivot wavelengths.
3.516745
3.628683
0.969152
if (telescope, band) in self._halfmaxes: raise AlreadyDefinedError('half-max points for %s/%s already ' 'defined', telescope, band) self._note(telescope, band) self._halfmaxes[telescope,band] = (lower, upper) return self
def register_halfmaxes(self, telescope, band, lower, upper)
Register precomputed half-max points.
4.321145
4.053015
1.066156
if telescope in self._bpass_classes: raise AlreadyDefinedError('bandpass class for %s already ' 'defined', telescope) self._note(telescope, None) self._bpass_classes[telescope] = klass return self
def register_bpass(self, telescope, klass)
Register a Bandpass class.
5.153438
4.519695
1.140218
klass = self._bpass_classes.get(telescope) if klass is None: raise NotDefinedError('bandpass data for %s not defined', telescope) bp = klass() bp.registry = self bp.telescope = telescope bp.band = band return bp
def get(self, telescope, band)
Get a Bandpass object for a known telescope and filter.
4.911661
4.283469
1.146655
# `band` should be 'nuv' or 'fuv' df = bandpass_data_frame('filter_galex_' + band + '.dat', 'wlen resp') df.resp *= df.wlen # QE -> EE response convention. return df
def _load_data(self, band)
From Morrissey+ 2005, with the actual data coming from http://www.astro.caltech.edu/~capak/filters/. According to the latter, these are in QE units and thus need to be multiplied by the wavelength when integrating per-energy.
24.593765
19.56605
1.256961
# `band` should be 'Lp'. df = bandpass_data_frame('filter_mko_' + band + '.dat', 'wlen resp') # Put in increasing wavelength order: df = df[::-1] df.index = np.arange(df.shape[0]) df.wlen *= 1e4 # micron to Angstrom df.resp *= df.wlen # QE to equal-energy...
def _load_data(self, band)
Filter responses for MKO NIR filters as specified in Tokunaga+ 2002 (see also Tokunaga+ 2005). I downloaded the L' profile from http://irtfweb.ifa.hawaii.edu/~nsfcam/hist/filters.2006.html. Pivot wavelengths from Tokunaga+ 2005 (Table 2) confirm that the profile is in QE convention, alt...
10.704621
9.329576
1.147386
return cgs.cgsperjy * self._zeropoints[self.band] * 10**(-0.4 * mag)
def mag_to_fnu(self, mag)
Compute F_ν for an MKO IR filter band. There are some problems here since "MKO" is filters, not a photometric system, but people try to make Vega = 0.
9.695586
10.330714
0.93852
h = bandpass_data_fits('sdss3_filter_responses.fits') section = 'ugriz'.index(band[0]) + 1 d = h[section].data if d.wavelength.dtype.isnative: df = pd.DataFrame({'wlen': d.wavelength, 'resp': d.respt}) else: df = pd.DataFrame({'wlen': d.wavelength...
def _load_data(self, band)
Filter responses for SDSS. Data table from https://www.sdss3.org/binaries/filter_curves.fits, as linked from https://www.sdss3.org/instruments/camera.php#Filters. SHA1 hash of the file is d3f638c41e21489ba7d6dbe7bb8217d938f21184. "Determined by Jim Gunn in June 2001." Doi+ 2010 have upda...
7.002839
5.405086
1.295602
# `band` should be 'up', 'gp', 'rp', 'ip', or 'zp'. if len(band) != 2 or band[1] != 'p': raise ValueError('band: ' + band) return abmag_to_fnu_cgs(mag)
def mag_to_fnu(self, mag)
SDSS *primed* magnitudes to F_ν. The primed magnitudes are the "USNO" standard-star system defined in Smith+ (2002AJ....123.2121S) and Fukugita+ (1996AJ....111.1748F). This system is anchored to the AB magnitude system, and as far as I can tell it is not known to have measurable offsets ...
7.52981
7.390274
1.018881
d = bandpass_data_fits('sw' + self._band_map[band] + '_20041120v106.arf')[1].data # note: # data.WAVE_MIN[i] < data.WAVE_MIN[i+1], but # data.WAVE_MIN[i] > data.WAVE_MAX[i] (!) # data.WAVE_MIN[i] = data.WAVE_MAX[i+1] (!) wmid = 0.5 * (d.WAVE_MIN + d.WAVE_...
def _load_data(self, band)
In-flight effective areas for the Swift UVOT, as obtained from the CALDB. See Breeveld+ 2011. XXX: confirm that these are equal-energy, not quantum-efficiency.
5.302183
4.901393
1.081771
# `band` should be 1, 2, 3, or 4. df = bandpass_data_frame('filter_wise_' + str(band) + '.dat', 'wlen resp uncert') df.wlen *= 1e4 # micron to Angstrom df.uncert *= df.resp / 1000. # parts per thou. to absolute values. lo, hi = self._filter_subsets[band] df = df[...
def _load_data(self, band)
From the WISE All-Sky Explanatory Supplement, IV.4.h.i.1, and Jarrett+ 2011. These are relative response per erg and so can be integrated directly against F_nu spectra. Wavelengths are in micron, uncertainties are in parts per thousand.
11.104684
8.312096
1.335967
if len (args) not in (3, 6): raise multitool.UsageError ('c2m expected exactly 3 or 6 arguments') year = int (args[0]) month = int (args[1]) import astropy.time if len (args) == 3: day = float (args[2]) iday = int (math.floor (day)...
def invoke (self, args, **kwargs)
c2m - UTC calendar to MJD[TAI]
2.596439
2.266344
1.145651
config_file = kwconfig.manage( file_path=resource_filename(Requirement.parse('search_google'), 'search_google/config.json'), defaults={ 'build_serviceName': 'customsearch', 'build_version': 'v1', 'num': 3, 'fileType': 'png', 'option_silent': 'False', 'option_preview' : 1...
def run(argv=argv)
Runs the search_google command line tool. This function runs the search_google command line tool in a terminal. It was intended for use inside a py file (.py) to be executed using python. Notes: * ``[q]`` reflects key ``q`` in the ``cseargs`` parameter for :class:`api.results` * Optional argumen...
3.961691
3.448019
1.148976
body = _parser.unescape(body) body = re.sub(r'<a [^>]+>(.+?)</a>', r'\1', body) body = body.replace('<br>', '\n') body = re.sub(r'<.+?>', '', body) return body
def clean_comment_body(body)
Returns given comment HTML as plaintext. Converts all HTML tags and entities within 4chan comments into human-readable text equivalents.
2.919427
3.023206
0.965673
wcsmodule = _load_wcs_module () is_pywcs = hasattr (wcsmodule, 'UnitConverter') wcs = wcsmodule.WCS (fitsheader) wcs.wcs.set () wcs.wcs.fix () # I'm interested in MJD computation via datfix() if hasattr (wcs, 'wcs_pix2sky'): wcs.wcs_pix2world = wcs.wcs_pix2sky wcs.wcs_worl...
def _create_wcs (fitsheader)
For compatibility between astropy and pywcs.
4.733097
4.491552
1.053777
if isinstance(item, text_type): return item.encode('utf8') if isinstance(item, dict): return dict((sanitize_unicode(k), sanitize_unicode(v)) for k, v in six.iteritems(item)) if isinstance(item,(list, tuple)): return item.__class__(sanitize_unicode(x) for x in item) from ......
def sanitize_unicode(item)
Safely pass string values to the CASA tools. item A value to be passed to a CASA tool. In Python 2, the bindings to CASA tasks expect to receive all string values as binary data (:class:`str`) and not Unicode. But :mod:`pwkit` often uses the ``from __future__ import unicode_literals`` statement ...
2.445072
3.280485
0.745338
import os.path data = None if 'CASAPATH' in os.environ: data = os.path.join(os.environ['CASAPATH'].split()[0], 'data') if data is None: # The Conda CASA directory layout: try: import casadef except ImportError: pass else: ...
def datadir(*subdirs)
Get a path within the CASA data directory. subdirs Extra elements to append to the returned path. This function locates the directory where CASA resource data files (tables of time offsets, calibrator models, etc.) are stored. If called with no arguments, it simply returns that path. If argument...
3.144556
3.2673
0.962433
import os, shutil, tempfile cwd = os.getcwd() tempdir = None try: tempdir = tempfile.mkdtemp(prefix='casautil') try: os.chdir(tempdir) sink = tools.logsink() sink.setlogfile(sanitize_unicode(os.devnull)) try: os.unli...
def logger(filter='WARN')
Set up CASA to write log messages to standard output. filter The log level filter: less urgent messages will not be shown. Valid values are strings: "DEBUG1", "INFO5", ... "INFO1", "INFO", "WARN", "SEVERE". This function creates and returns a CASA ”log sink” object that is configured to write ...
4.647448
4.199895
1.106563
import sys, os readfd, writefd = os.pipe() pid = os.fork() if pid == 0: # Child process. We never leave this branch. # # Log messages of priority >WARN are sent to stderr regardless of the # status of log.showconsole(). The idea is for this subprocess to be ...
def forkandlog(function, filter='INFO5', debug=False)
Fork a child process and read its CASA log output. function A function to run in the child process filter The CASA log level filter to apply in the child process: less urgent messages will not be shown. Valid values are strings: "DEBUG1", "INFO5", ... "INFO1", "INFO", "WARN", "SEVERE". ...
6.659475
6.872814
0.968959
root = ElementTree.fromstring(resp.text) items = root.findall("eemetadata:metadataFields/eemetadata:metadataField", NAMESPACES) scene['extended'] = {item.attrib.get('name').strip(): xsi.get(item[0]) for item in items} return scene
def _get_extended(scene, resp)
Parse metadata returned from the metadataUrl of a USGS scene. :param scene: Dictionary representation of a USGS scene :param resp: Response object from requests/grequests
6.953513
7.410544
0.938327
session = FuturesSession(max_workers=30) futures = [ session.get(url) for url in urls ] return [ future.result() for future in futures ]
def _async_requests(urls)
Sends multiple non-blocking requests. Returns a list of responses. :param urls: List of urls
3.128876
4.457334
0.701961
api_key = _get_api_key(api_key) url = '{}/metadata'.format(USGS_API) payload = { "jsonRequest": payloads.metadata(dataset, node, entityids, api_key=api_key) } r = requests.post(url, payload) response = r.json() _check_for_usgs_error(response) if extended: metadata...
def metadata(dataset, node, entityids, extended=False, api_key=None)
Request metadata for a given scene in a USGS dataset. :param dataset: :param node: :param entityids: :param extended: Send a second request to the metadata url to get extended metadata on the scene. :param api_key:
3.479495
3.767688
0.923509
import sys if len(args): cstr = fmt % args else: cstr = text_type(fmt) ex = sys.exc_info()[1] if isinstance(ex, EnvironmentError): ex.strerror = '%s: %s' % (cstr, ex.strerror) ex.args = (ex.errno, ex.strerror) else: if len(ex.args): cst...
def reraise_context(fmt, *args)
Reraise an exception with its message modified to specify additional context. This function tries to help provide context when a piece of code encounters an exception while trying to get something done, and it wishes to propagate contextual information farther up the call stack. It only makes sense...
2.495389
2.830489
0.881611
new = self.__class__() new.__dict__ = dict(self.__dict__) return new
def copy(self)
Return a shallow copy of this object.
4.595695
3.577546
1.284594
if format == 'str': template = '%-*s = %s' elif format == 'repr': template = '%-*s = %r' else: raise ValueError('unrecognized value for "format": %r' % format) d = self.__dict__ maxlen = 0 for k in six.iterkeys(d): ...
def to_pretty(self, format='str')
Return a string with a prettified version of this object’s contents. The format is a multiline string where each line is of the form ``key = value``. If the *format* argument is equal to ``"str"``, each ``value`` is the stringification of the value; if it is ``"repr"``, it is its :func:...
2.578699
2.497349
1.032574
if asdm is None: raise ValueError ('asdm') if ms is None: raise ValueError ('ms') if tbuff is None: raise ValueError ('tbuff') helper.casans.importevla (asdm=asdm, vis=ms, ocorr_mode='co', online=True, tbuff=tbuff, flagpol=False, tolerance=1.3,...
def in_casapy (helper, asdm=None, ms=None, tbuff=None)
This function is run inside the weirdo casapy IPython environment! A strange set of modules is available, and the `pwkit.environments.casa.scripting` system sets up a very particular environment to allow encapsulated scripting.
7.593171
7.903925
0.960684
if sha1sum: import hashlib sha1 = hashlib.sha1 () else: sha1 = None inifile.write_stream (stream, _format_many (holders, defaultsection, extrapos, sha1), defaultsection=defaultsection, **kwargs) ...
def write_stream (stream, holders, defaultsection=None, extrapos=(), sha1sum=False, **kwargs)
`extrapos` is basically a hack for multi-step processing. We have some flux measurements that are computed from luminosities and distances. The flux value is therefore an unwrapped Uval, which doesn't retain memory of any positivity constraint it may have had. Therefore, if we write out such a value usi...
3.767023
4.002844
0.941087
"We've hacked the load order a bit to get t0 and mjd0 in _process_main()." if hdu.name == 'EVENTS': pass else: super (Events, self)._process_hdu (hdu)
def _process_hdu (self, hdu)
We've hacked the load order a bit to get t0 and mjd0 in _process_main().
16.649673
2.917098
5.707616
"*line* should be bytes" self.destination.write(b''.join([ self._cyan, b't=%07d' % (time.time() - self._t0), self._reset, self._kind_prefixes[kind], self.markers[kind], line, self._reset, ])) self.destina...
def output(self, kind, line)
*line* should be bytes
7.516378
6.091147
1.233984
"*text* should be bytes" binary_stderr.write(b''.join([ self._red, b't=%07d' % (time.time() - self._t0), self._reset, b' ', text, ])) binary_stderr.flush()
def output_stderr(self, text)
*text* should be bytes
8.14904
6.118622
1.331842
if isinstance(board_name_list, basestring): board_name_list = board_name_list.split() return [Board(name, *args, **kwargs) for name in board_name_list]
def get_boards(board_name_list, *args, **kwargs)
Given a list of boards, return :class:`basc_py4chan.Board` objects. Args: board_name_list (list): List of board names to get, eg: ['b', 'tg'] Returns: dict of :class:`basc_py4chan.Board`: Requested boards.
2.160537
2.862219
0.754847
# Use https based on how the Board class instances are to be instantiated https = kwargs.get('https', args[1] if len(args) > 1 else False) # Dummy URL generator, only used to generate the board list which doesn't # require a valid board name url_generator = Url(None, https) _fetch_boards_m...
def get_all_boards(*args, **kwargs)
Returns every board on 4chan. Returns: dict of :class:`basc_py4chan.Board`: All boards.
11.096249
12.817502
0.865711
# see if already cached cached_thread = self._thread_cache.get(thread_id) if cached_thread: if update_if_cached: cached_thread.update() return cached_thread res = self._requests_session.get( self._url.thread_api_url( ...
def get_thread(self, thread_id, update_if_cached=True, raise_404=False)
Get a thread from 4chan via 4chan API. Args: thread_id (int): Thread ID update_if_cached (bool): Whether the thread should be updated if it's already in our cache raise_404 (bool): Raise an Exception if thread has 404'd Returns: :class:`basc_py4chan.Thre...
2.705558
2.831816
0.955415
return self._requests_session.head( self._url.thread_api_url( thread_id=thread_id ) ).ok
def thread_exists(self, thread_id)
Check if a thread exists or has 404'd. Args: thread_id (int): Thread ID Returns: bool: Whether the given thread exists on this board.
6.845151
8.008565
0.854729
url = self._url.page_url(page) return self._request_threads(url)
def get_threads(self, page=1)
Returns all threads on a certain page. Gets a list of Thread objects for every thread on the given page. If a thread is already in our cache, the cached version is returned and thread.want_update is set to True on the specific thread object. Pages on 4chan are indexed from 1 onwards. ...
8.947889
12.364682
0.723665
json = self._get_json(self._url.thread_list()) return [thread['no'] for page in json for thread in page['threads']]
def get_all_thread_ids(self)
Return the ID of every thread on this board. Returns: list of ints: List of IDs of every thread on this board.
8.75599
9.751734
0.897891
if not expand: return self._request_threads(self._url.catalog()) thread_ids = self.get_all_thread_ids() threads = [self.get_thread(id, raise_404=False) for id in thread_ids] return filter(None, threads)
def get_all_threads(self, expand=False)
Return every thread on this board. If not expanded, result is same as get_threads run across all board pages, with last 3-5 replies included. Uses the catalog when not expanding, and uses the flat thread ID listing at /{board}/threads.json when expanding for more efficient resource usa...
4.618969
4.847803
0.952796
for thread in tuple(self._thread_cache.values()): if if_want_update: if not thread.want_update: continue thread.update()
def refresh_cache(self, if_want_update=False)
Update all threads currently stored in our cache.
5.020986
3.74686
1.340051
import numpy as np, os if ms is None: raise ValueError('ms') if plotdest is None: raise ValueError('plotdest') opac = helper.casans.plotweather(vis=ms, plotName=plotdest) opac = np.asarray(opac) with open(helper.temppath('opac.npy'), 'wb') as f: np.save(f, opac)
def in_casapy(helper, ms=None, plotdest=None)
This function is run inside the weirdo casapy IPython environment! A strange set of modules is available, and the `pwkit.environments.casa.scripting` system sets up a very particular environment to allow encapsulated scripting.
5.399302
5.795772
0.931593
# Ugh. I don't see any way out of special-casing the RPM-based # installations ... which only exist on NRAO computers, AFAICT. # Hardcoding 64-bitness, hopefully that won't come back to bite me. is_rpm_install = self._rootdir.startswith('/usr/lib64/casapy/release/') de...
def modify_environment(self, env)
Maintaining compatibility with different CASA versions is a pain.
3.740246
3.639458
1.027693
if node is None: cur_dir = os.path.dirname(os.path.realpath(__file__)) data_dir = os.path.join(cur_dir, "..", "data") dataset_path = os.path.join(data_dir, "datasets.json") with open(dataset_path, "r") as f: datasets = json.loads(f.read()) ...
def get_node(dataset, node)
.. todo:: Move to more appropriate place in module.
2.334221
2.318443
1.006805
with env.slurp (argv=['dmstat', '%s%s[cols energy]' % (evtpath, filter)], linebreak=True) as s: for etype, payload in s: if etype != 'stdout': continue if b'good:' not in payload: continue return int (payload.split ()[-1]) raise...
def count_events (env, evtpath, filter)
TODO: this can probably be replaced with simply reading the file ourselves!
13.738805
13.456587
1.020972
import numpy as np import pandas as pd from scipy.special import erfcinv, gammaln if env is None: from . import CiaoEnvironment env = CiaoEnvironment () srcarea = get_region_area (env, evtpath, srcreg) bkgarea = get_region_area (env, evtpath, bkgreg) srccounts = [coun...
def compute_bgband (evtpath, srcreg, bkgreg, ebins, env=None)
Compute background information for a source in one or more energy bands. evtpath Path to a CIAO events file srcreg String specifying the source region to consider; use 'region(path.reg)' if you have the region saved in a file. bkgreg String specifying the background region to consid...
2.448568
1.804246
1.357114
from ...io import Path import shutil, signal, tempfile if infile is None: raise ValueError('must specify infile') kwargs.update(dict( infile = infile, psfmethod = psfmethod, conf = conf, verbose = verbose, clobber = 'yes', outroot = 'sf', ...
def simple_srcflux(env, infile=None, psfmethod='arfcorr', conf=0.68, verbose=0, **kwargs)
Run the CIAO "srcflux" script and retrieve its results. *infile* The input events file; must be specified. The computation is done in a temporary directory, so this path — and all others passed in as arguments — **must be made absolute**. *psfmethod* = "arfcorr" The PSF modeling method ...
2.765931
2.878665
0.960838
if orig is None: orig = '' if not len(orig): return text return ''.join([text, pathsep, orig])
def prepend_path(orig, text, pathsep=os.pathsep)
Returns a $PATH-like environment variable with `text` prepended. `orig` is the original variable value, or None. `pathsep` is the character separating path elements, defaulting to `os.pathsep`. Example: newpath = cli.prepend_path(oldpath, '/mypackage/bin') See also `prepend_environ_path`.
4.113671
5.615147
0.732603
env[name] = prepend_path(env.get(name), text, pathsep=pathsep) return env
def prepend_environ_path(env, name, text, pathsep=os.pathsep)
Prepend `text` into a $PATH-like environment variable. `env` is a dictionary of environment variables and `name` is the variable name. `pathsep` is the character separating path elements, defaulting to `os.pathsep`. The variable will be created if it is not already in `env`. Returns `env`. Example:...
3.069571
8.153662
0.376465
fk10func = FK10Invoker(shlib_path) in_vals = make_in_vals_array() in_vals[IN_VAL_AREA] = 1.33e18 in_vals[IN_VAL_DEPTH] = 6e8 in_vals[IN_VAL_T0] = 2.1e7 # EPSILON (these markers are to aid counting indices) # KAPPA in_vals[IN_VAL_INTEG_METH] = 16 in_vals[IN_VAL_EMIN] = 0.016 ...
def do_figure9_calc_lowlevel(shlib_path, set_unused=True)
Reproduce the calculation used to produce Figure 9 of the Fleischman & Kuznetsov (2010) paper, using our low-level interfaces. Input parameters, etc., come from the file ``Flare071231a.pro`` that is distributed with the paper’s Supplementary Data archive. Invoke with something like:: from pwkit...
4.081259
4.182834
0.975716