INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return the digits to either side of a single non-digit character as a 2-tuple of integers >>> int_pair('90210-007') (90210, 7) >>> int_pair('04321.0123') (4321, 123)
def int_pair(s, default=(0, None)): """Return the digits to either side of a single non-digit character as a 2-tuple of integers >>> int_pair('90210-007') (90210, 7) >>> int_pair('04321.0123') (4321, 123) """ s = re.split(r'[^0-9]+', str(s).strip()) if len(s) and len(s[0]): if l...
>>> make_us_postal_code(1234) '01234' >>> make_us_postal_code(507.6009) '507' >>> make_us_postal_code(90210.0) '90210' >>> make_us_postal_code(39567.7226) '39567-7226' >>> make_us_postal_code(39567.7226) '39567-7226'
def make_us_postal_code(s, allowed_lengths=(), allowed_digits=()): """ >>> make_us_postal_code(1234) '01234' >>> make_us_postal_code(507.6009) '507' >>> make_us_postal_code(90210.0) '90210' >>> make_us_postal_code(39567.7226) '39567-7226' >>> make_us_postal_code(39567.7226) '...
r"""Coerce a string into a float >>> make_float('12,345') 12345.0 >>> make_float('12.345') 12.345 >>> make_float('1+2') 3.0 >>> make_float('+42.0') 42.0 >>> make_float('\r\n-42?\r\n') -42.0 >>> make_float('$42.42') 42.42 >>> make_float('B-52') -52.0 >>> make_...
def make_float(s, default='', ignore_commas=True): r"""Coerce a string into a float >>> make_float('12,345') 12345.0 >>> make_float('12.345') 12.345 >>> make_float('1+2') 3.0 >>> make_float('+42.0') 42.0 >>> make_float('\r\n-42?\r\n') -42.0 >>> make_float('$42.42') 4...
r"""Coerce a string into an integer (long ints will fail) TODO: - Ignore dashes and other punctuation within a long string of digits, like a telephone number, partnumber, datecode or serial number. - Use the Decimal type to allow infinite precision - Use regexes to be more robust >>> make_i...
def make_int(s, default='', ignore_commas=True): r"""Coerce a string into an integer (long ints will fail) TODO: - Ignore dashes and other punctuation within a long string of digits, like a telephone number, partnumber, datecode or serial number. - Use the Decimal type to allow infinite precisio...
Produce a string convertable with float(s), if possible, fixing some common scientific notations Deletes commas and allows addition. >>> normalize_scientific_notation(' -123 x 10^-45 ') '-123e-45' >>> normalize_scientific_notation(' -1+1,234 x 10^-5,678 ') '1233e-5678' >>> normalize_scientific_...
def normalize_scientific_notation(s, ignore_commas=True, verbosity=1): """Produce a string convertable with float(s), if possible, fixing some common scientific notations Deletes commas and allows addition. >>> normalize_scientific_notation(' -123 x 10^-45 ') '-123e-45' >>> normalize_scientific_not...
Coerce a string or nested list of strings into a flat list of strings.
def normalize_names(names): """Coerce a string or nested list of strings into a flat list of strings.""" if isinstance(names, basestring): names = names.split(',') names = listify(names) return [str(name).strip() for name in names]
Count the occurrence of a category of valid characters within an iterable of serial/model no, etc
def string_stats(strs, valid_chars='012346789', left_pad='0', right_pad='', strip=True): """ Count the occurrence of a category of valid characters within an iterable of serial/model no, etc """ if left_pad is None: left_pad = ''.join(c for c in rex.ASCII_CHARACTERS if c not in valid_chars) if right...
r"""Make a string compatible with typical serial number requirements # Default configuration strips internal and external whitespaces and retains only the last 10 characters >>> normalize_serial_number('1C 234567890 ') '0234567890' >>> normalize_serial_number('1C 234567890 ', ...
def normalize_serial_number(sn, max_length=None, left_fill='0', right_fill=str(), blank=str(), valid_chars=' -0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', invalid_chars=None, strip_whitesp...
r"""Just like str.split(), except that a variety (list) of seperators is allowed. >>> multisplit(r'1-2?3,;.4+-', string.punctuation) ['1', '2', '3', '', '', '4', '', ''] >>> multisplit(r'1-2?3,;.4+-', string.punctuation, blank=False) ['1', '2', '3', '4'] >>> multisplit(r'1C 234567890', '\x00\x01\x0...
def multisplit(s, seps=list(string.punctuation) + list(string.whitespace), blank=True): r"""Just like str.split(), except that a variety (list) of seperators is allowed. >>> multisplit(r'1-2?3,;.4+-', string.punctuation) ['1', '2', '3', '', '', '4', '', ''] >>> multisplit(r'1-2?3,;.4+-', string.punctua...
Simple, clumsy, slow HTML tag stripper
def strip_HTML(s): """Simple, clumsy, slow HTML tag stripper""" result = '' total = 0 for c in s: if c == '<': total = 1 elif c == '>': total = 0 result += ' ' elif total == 0: result += c return result
r"""Segment words (tokens), returning a list of all tokens Does not return any separating whitespace or punctuation marks. Attempts to return external apostrophes at the end of words. Comparable to `nltk.word_toeknize`. Arguments: splitter_regex (str or re): compiled or uncompiled regular expres...
def get_words(s, splitter_regex=rex.word_sep_except_external_appostrophe, preprocessor=strip_HTML, postprocessor=strip_edge_punc, min_len=None, max_len=None, blacklist=None, whitelist=None, lower=False, filter_fun=None, str_type=str): r"""Segment words (tokens), returning a...
Use the pypi tabulate package instead!
def tabulate(lol, headers, eol='\n'): """Use the pypi tabulate package instead!""" yield '| %s |' % ' | '.join(headers) + eol yield '| %s:|' % ':| '.join(['-' * len(w) for w in headers]) + eol for row in lol: yield '| %s |' % ' | '.join(str(c) for c in row) + eol
FIXME: this is unpythonic and does things you don't expect! FIXME: rename to "integer_from_category" Returns an integer representative of a categorical object (string, dict, etc) >>> intify('1.2345e10') 12345000000 >>> intify([12]), intify('[99]'), intify('(12,)') (91, 91, 40) >>> intify(...
def intify(obj, str_fun=str, use_ord=True, use_hash=True, use_len=True): """FIXME: this is unpythonic and does things you don't expect! FIXME: rename to "integer_from_category" Returns an integer representative of a categorical object (string, dict, etc) >>> intify('1.2345e10') 12345000000 >>...
Return an N-length list, with elements values, extrapolating as necessary. >>> listify("don't split into characters") ["don't split into characters"] >>> listify("len = 3", 3) ['len = 3', 'len = 3', 'len = 3'] >>> listify("But split on a delimeter, if requested.", delim=',') ['But split on a de...
def listify(values, N=1, delim=None): """Return an N-length list, with elements values, extrapolating as necessary. >>> listify("don't split into characters") ["don't split into characters"] >>> listify("len = 3", 3) ['len = 3', 'len = 3', 'len = 3'] >>> listify("But split on a delimeter, if re...
Return the desired element in a list ignoring the rest. >>> unlistify([1,2,3]) 1 >>> unlistify([1,[4, 5, 6],3], get=1) [4, 5, 6] >>> unlistify([1,[4, 5, 6],3], depth=2, get=1) 5 >>> unlistify([1,(4, 5, 6),3], depth=2, get=1) (4, 5, 6) >>> unlistify([1,2,(4, 5, 6)], depth=2, get=2) ...
def unlistify(n, depth=1, typ=list, get=None): """Return the desired element in a list ignoring the rest. >>> unlistify([1,2,3]) 1 >>> unlistify([1,[4, 5, 6],3], get=1) [4, 5, 6] >>> unlistify([1,[4, 5, 6],3], depth=2, get=1) 5 >>> unlistify([1,(4, 5, 6),3], depth=2, get=1) (4, 5, 6...
r"""Strip whitespace from all dictionary keys, to the depth indicated >>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}) == {'a': ' a', 'b\t c': {'d e ': 'd e '}} True >>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}, depth=100) == {'a': ' a', 'b\t c': {'d e': 'd e '}} True
def strip_keys(d, nones=False, depth=0): r"""Strip whitespace from all dictionary keys, to the depth indicated >>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}) == {'a': ' a', 'b\t c': {'d e ': 'd e '}} True >>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}, depth=100) == {'a': ' a...
Dictionary of sequences from CSV file
def get_table_from_csv(filename='ssg_report_aarons_returns.csv', delimiter=',', dos=False): """Dictionary of sequences from CSV file""" table = [] with open(filename, 'rb') as f: reader = csv.reader(f, dialect='excel', delimiter=delimiter) for row in reader: table += [row] if...
Attempt to shorten a phrase by deleting words at the end of the phrase >>> shorten('Hello World!') 'Hello World' >>> shorten("Hello World! I'll talk your ear off!", 15) 'Hello World'
def shorten(s, max_len=16): """Attempt to shorten a phrase by deleting words at the end of the phrase >>> shorten('Hello World!') 'Hello World' >>> shorten("Hello World! I'll talk your ear off!", 15) 'Hello World' """ short = s words = [abbreviate(word) for word in get_words(s)] for...
r"""Return string at most `max_len` characters or sequence elments appended with the `ellipsis` characters >>> truncate(OrderedDict(zip(list('ABCDEFGH'), range(8))), 1) "{'A': 0..." >>> truncate(list(range(5)), 3) '[0, 1, 2...' >>> truncate(np.arange(5), 3) '[0, 1, 2...' >>> truncate('Too v...
def truncate(s, max_len=20, ellipsis='...'): r"""Return string at most `max_len` characters or sequence elments appended with the `ellipsis` characters >>> truncate(OrderedDict(zip(list('ABCDEFGH'), range(8))), 1) "{'A': 0..." >>> truncate(list(range(5)), 3) '[0, 1, 2...' >>> truncate(np.arange...
Return a generator of all the unique substrings (k-mer or q-gram strings) within a sequence/string Not effiicent for large k and long strings. Doesn't form substrings that are shorter than k, only exactly k-mers Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing. ...
def generate_kmers(seq, k=4): """Return a generator of all the unique substrings (k-mer or q-gram strings) within a sequence/string Not effiicent for large k and long strings. Doesn't form substrings that are shorter than k, only exactly k-mers Used for algorithms like UniqTag for genome unique identi...
Return a sequence of all the unique substrings (k-mer or q-gram) within a short (<128 symbol) string Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing. jellyfish is a C implementation of k-mer counting If seq is a string generate a sequence of k-mer string If se...
def kmer_counter(seq, k=4): """Return a sequence of all the unique substrings (k-mer or q-gram) within a short (<128 symbol) string Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing. jellyfish is a C implementation of k-mer counting If seq is a string generate a...
Return the set of unique k-length substrings within a the sequence/string `seq` Implements formula: C_k(s) = C(s) ∩ Σ^k from http://biorxiv.org/content/early/2014/08/01/007583 >>> sorted(kmer_set('AGATAGATAGACACAGAAATGGGACCACAC')) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS ['AAAT', 'AATG', 'ACAC...
def kmer_set(seq, k=4): """Return the set of unique k-length substrings within a the sequence/string `seq` Implements formula: C_k(s) = C(s) ∩ Σ^k from http://biorxiv.org/content/early/2014/08/01/007583 >>> sorted(kmer_set('AGATAGATAGACACAGAAATGGGACCACAC')) # doctest: +NORMALIZE_WHITESPACE, +ELLI...
Return a dict of objects and thier counts (like a Counter), but only count > 1
def count_duplicates(items): """Return a dict of objects and thier counts (like a Counter), but only count > 1""" c = Counter(items) return dict((k, v) for (k, v) in viewitems(c) if v > 1)
Produce a slug (short URI-friendly string) from an iterable Mapping (dict, OrderedDict) >>> slug_from_dict(OrderedDict([('a', 1), ('b', 'beta'), (' ', 'alpha')])) '1-beta-alpha'
def slug_from_dict(d, max_len=128, delim='-'): """Produce a slug (short URI-friendly string) from an iterable Mapping (dict, OrderedDict) >>> slug_from_dict(OrderedDict([('a', 1), ('b', 'beta'), (' ', 'alpha')])) '1-beta-alpha' """ return slug_from_iter(list(d.values()), max_len=max_len, delim=deli...
Produce a slug (short URI-friendly string) from an iterable (list, tuple, dict) >>> slug_from_iter(['.a.', '=b=', '--alpha--']) 'a-b-alpha'
def slug_from_iter(it, max_len=128, delim='-'): """Produce a slug (short URI-friendly string) from an iterable (list, tuple, dict) >>> slug_from_iter(['.a.', '=b=', '--alpha--']) 'a-b-alpha' """ nonnull_values = [str(v) for v in it if v or ((isinstance(v, (int, float, Decimal)) and str(v)))] r...
Return a list of all possible meanings of a phrase containing slashes TODO: - Code is not in standard Sedgewick recursion form - Simplify by removing one of the recursive calls? - Simplify by using a list comprehension? # doctest: +NORMALIZE_WHITESPACE >>> slash_product("The challe...
def slash_product(string_or_seq, slash='/', space=' '): """Return a list of all possible meanings of a phrase containing slashes TODO: - Code is not in standard Sedgewick recursion form - Simplify by removing one of the recursive calls? - Simplify by using a list comprehension? # d...
Create a header a new image
def create_header(coord, radius, proj='ZEA', npix=30): """ Create a header a new image """ gal = coord.name == 'galactic' values = [ ["NAXIS", 2, ], ["NAXIS1", npix, ], ["NAXIS2", npix, ], ["CTYPE1", 'GLON-%s'%proj if gal else 'RA---%...
Make an empty sky region at location of skydir skydir : skymaps.SkyDir object size : size of region (deg.) kwargs : arguments passed to create_header
def create_header_data(coord, radius=10., **kwargs): """ Make an empty sky region at location of skydir skydir : skymaps.SkyDir object size : size of region (deg.) kwargs : arguments passed to create_header """ header = create_header(coord, radius=radius, **kwargs) data = np.zeros( (header...
Plot sky region defined by header and data header : FITS header data : Data array
def plot_skyreg(header, data, **kwargs): """ Plot sky region defined by header and data header : FITS header data : Data array """ kwargs.setdefault('cmap','binary') fig = plt.figure() ax = pywcsgrid2.subplot(111, header=header) ax.set_ticklabel_type("dms") im = ax.imshow(data, ori...
https://github.com/astropy/astropy/issues/3093
def estimate_angle(coord, angle, new_frame, offset=1e-7): """ https://github.com/astropy/astropy/issues/3093 """ delta = delta_coord(coord, angle, offset) new_coord = coord.transform_to(new_frame) new_delta = delta.transform_to(new_frame) return new_coord.position_angle(new_delta).deg
Split string `text` into word tokens using the Penn Treebank rules
def word_tokenize(text): """ Split string `text` into word tokens using the Penn Treebank rules """ for (regexp, replacement) in RULES1: text = sub(regexp, replacement, text) # add extra space to make things easier text = " " + text + " " for (regexp, replacement) in RULES2: ...
This assumes the value has been preprocessed into a dictionary of the form: {'type': <geometry_type>, 'geometry': <raw_geometry>}
def to_python(self, value): """ This assumes the value has been preprocessed into a dictionary of the form: {'type': <geometry_type>, 'geometry': <raw_geometry>} """ if not value or isinstance(value, BaseGeometry): return value geometry_type = value['type'] ...
get_postcodedata - fetch information for 'postcode'. Parameters ---------- postcode : string The full (dutch) postcode nr : int The housenumber addition : string (optional) the extension to a housenumber params : dict (optional) ...
def get_postcodedata(self, postcode, nr, addition="", **params): """get_postcodedata - fetch information for 'postcode'. Parameters ---------- postcode : string The full (dutch) postcode nr : int The housenumber addition : string (optional) ...
get_signalcheck - perform a signal check. Parameters ---------- sar : dict signal-api-request specified as a dictionary of parameters. All of these parameters are optional. For details check https://api.postcode.nl/documentation/signal-api-example. ...
def get_signalcheck(self, sar, **params): """get_signalcheck - perform a signal check. Parameters ---------- sar : dict signal-api-request specified as a dictionary of parameters. All of these parameters are optional. For details check https://api.po...
request - Returns dict of response from postcode.nl API. This method is called only by the EndpointMixin methods.
def __request(self, endpoint, method='GET', params=None, convJSON=False): """request - Returns dict of response from postcode.nl API. This method is called only by the EndpointMixin methods. """ url = '%s/%s' % (self.api_url, endpoint) method = method.lower() params = p...
Tool for simple MC validation studies -- specifically to create multiple realizations of a satellite given an CompositeIsochrone object, Kernel object, stellar mass (M_sol) for normalization, and distance_modulus.
def validateSatellite(config, isochrone, kernel, stellar_mass, distance_modulus, trials=1, debug=False, seed=0): """ Tool for simple MC validation studies -- specifically to create multiple realizations of a satellite given an CompositeIsochrone object, Kernel object, stellar mass (M_sol) for normalization,...
Plot membership probabilities and MC source ids together.
def validateMembership(likelihood, p, mc_source_id=1): """ Plot membership probabilities and MC source ids together. """ cut_mc_source_id = (likelihood.catalog.mc_source_id == mc_source_id) # Spatial projector = ugali.utils.projector.Projector(likelihood.kernel.lon, likelihood.kernel.lat) ...
Fit a line to the x, y data supplied and plot it along with teh raw samples >>> age = [25, 26, 33, 29, 27, 21, 26, 35, 21, 37, 21, 38, 18, 19, 36, 30, 29, 24, 24, 36, 36, 27, ... 33, 23, 21, 26, 27, 27, 24, 26, 25, 24, 22, 25, 40, 39, 19, 31, 33, 30, 33, 27, 40, 32, ... 31, 35, 26, 34, 27, 34...
def regression_and_plot(x, y=None): """ Fit a line to the x, y data supplied and plot it along with teh raw samples >>> age = [25, 26, 33, 29, 27, 21, 26, 35, 21, 37, 21, 38, 18, 19, 36, 30, 29, 24, 24, 36, 36, 27, ... 33, 23, 21, 26, 27, 27, 24, 26, 25, 24, 22, 25, 40, 39, 19, 31, 33, 30, 33, 2...
Plot a 2-D linear regression (y = slope * x + offset) overlayed over the raw data samples
def regressionplot(x, y, poly=None): """ Plot a 2-D linear regression (y = slope * x + offset) overlayed over the raw data samples """ if not isinstance(x[0], (float, int, np.float64, np.float32)): x = [row[0] for row in x] y_regression = poly[0] * np.array(x) + poly[-1] try: plt...
Scatter plot with colored markers depending on the discrete values in a "category" column FIXME: empty plots that dont go away, Plot and/save scatter matrix in groups of num_columns topics
def scatmat(df, category=None, colors='rgob', num_plots=4, num_topics=100, num_columns=4, show=False, block=False, data_path=DATA_PATH, save=False, verbose=1): """Scatter plot with colored markers depending on the discrete values in a "category" column FIXME: empty plots that dont go aw...
3-D Point cloud for plotting things like mesh models of horses ;)
def point_cloud(df, columns=[0, 1, 2]): """3-D Point cloud for plotting things like mesh models of horses ;)""" df = df if isinstance(df, pd.DataFrame) else pd.DataFrame(df) if not all(c in df.columns for c in columns): columns = list(df.columns)[:3] fig = plt.figure() ax = fig.add_subplot(...
Convert a sequence of bools (True/False) into a list of the start and stop of the True "sections" or spans
def mask2spans(mask, index=None): """Convert a sequence of bools (True/False) into a list of the start and stop of the True "sections" or spans""" index = list(range(len(mask))) if index is None else index mask = pd.Series(mask) mask = mask.astype(int).fillna(0).diff().fillna(0) starts = list(index...
Display the last image drawn
def show(self, block=False): """ Display the last image drawn """ try: plt.show(block=block) except ValueError: plt.show()
save colormap to file
def save(self, filename): """ save colormap to file""" plt.savefig(filename, fig=self.fig, facecolor='black', edgecolor='black')
https://github.com/numpy/numpy/issues/4701
def asscalar(a): """ https://github.com/numpy/numpy/issues/4701 """ # Do we want to check that the value is numeric? #if isinstance(value, (int, long, float)): return value try: return np.asscalar(a) except AttributeError as e: return np.asscalar(np.asarray(a))
Get the named parameter. Parameters ---------- name : string The parameter name. Returns ------- param : The parameter object.
def getp(self, name): """ Get the named parameter. Parameters ---------- name : string The parameter name. Returns ------- param : The parameter object. """ name = self._mapping.get(name,name) return self...
Set the value (and bounds) of the named parameter. Parameters ---------- name : string The parameter name. value: The value of the parameter bounds: None The bounds on the parameter Returns ------- None
def setp(self, name, value=None, bounds=None, free=None, errors=None): """ Set the value (and bounds) of the named parameter. Parameters ---------- name : string The parameter name. value: The value of the parameter bounds: None ...
Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.).
def set_attributes(self, **kwargs): """ Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.). """ kwargs = dict(kwargs) for name,value in kwargs.items(): ...
http://stackoverflow.com/a/14001707/4075339 http://stackoverflow.com/a/21912744/4075339
def representer(dumper, data): """ http://stackoverflow.com/a/14001707/4075339 http://stackoverflow.com/a/21912744/4075339 """ tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG return dumper.represent_mapping(tag,list(data.todict().items()),flow_style=True)
Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluation. Inputs are a Config object (or file name), an Isochrone object, an array of distance moduli at which to evaluate the signal color probability, and an array of magnitude uncertainties which set the bin ed...
def writeColorLUT2(config, outfile=None, isochrone=None, distance_modulus_array=None, delta_mag=None, mag_err_array=None, mass_steps=10000, plot=False): """ Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluati...
Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluation. Inputs are a Config object (or file name), an Isochrone object, an array of distance moduli at which to evaluate the signal color probability, and an array of magnitude uncertainties which set the bin ed...
def writeColorLUT(config, outfile=None, isochrone=None, distance_modulus_array=None, delta_mag=None, mag_err_array=None, mass_steps=1000000, plot=False): """ Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluat...
Take in a color look-up table and return the signal color evaluated for each object. Consider making the argument a Catalog object rather than magnitudes and uncertainties.
def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2): """ Take in a color look-up table and return the signal color evaluated for each object. Consider making the argument a Catalog object rather than magnitudes and uncertainties. """ reader = pyfits.open(infile) dist...
Based on django.util.functional.memoize. Automatically memoizes instace methods for the lifespan of an object. Only works with methods taking non-keword arguments. Note that the args to the function must be usable as dictionary keys. Also, the first argument MUST be self. This decorator will not work for functi...
def auto_memoize(func): """ Based on django.util.functional.memoize. Automatically memoizes instace methods for the lifespan of an object. Only works with methods taking non-keword arguments. Note that the args to the function must be usable as dictionary keys. Also, the first argument MUST be self. Thi...
For a sorted list li, returns the closest item to value
def best_fit(li, value): """For a sorted list li, returns the closest item to value""" index = min(bisect_left(li, value), len(li) - 1) if index in (0, len(li)): return index if li[index] - value < value - li[index-1]: return index else: return index-1
Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails
def proj4_to_epsg(projection): """Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails""" def make_definition(value): return {x.strip().lower() for x in value.split('+') if x} # Use the EPSG in the definition if available match = EPSG_RE.search(pro...
Converts a well-known text string to a pyproj.Proj object
def wkt_to_proj4(wkt): """Converts a well-known text string to a pyproj.Proj object""" srs = osgeo.osr.SpatialReference() srs.ImportFromWkt(wkt) return pyproj.Proj(str(srs.ExportToProj4()))
Converts a pyproj.Proj object to a well-known text string
def proj4_to_wkt(projection): """Converts a pyproj.Proj object to a well-known text string""" srs = osgeo.osr.SpatialReference() srs.ImportFromProj4(projection.srs) return srs.ExportToWkt()
Projects a shapely geometry object from the source to the target projection.
def project_geometry(geometry, source, target): """Projects a shapely geometry object from the source to the target projection.""" project = partial( pyproj.transform, source, target ) return transform(project, geometry)
Load this config from an existing config Parameters: ----------- config : filename, config object, or dict to load Returns: -------- params : configuration parameters
def _load(self, config): """ Load this config from an existing config Parameters: ----------- config : filename, config object, or dict to load Returns: -------- params : configuration parameters """ if isstring(config): self.filenam...
Enforce some structure to the config file
def _validate(self): """ Enforce some structure to the config file """ # This could be done with a default config # Check that specific keys exist sections = odict([ ('catalog',['dirname','basename', 'lon_field','lat_field','objid_field', ...
Join dirnames and filenames from config.
def _formatFilepaths(self): """ Join dirnames and filenames from config. """ likedir=self['output']['likedir'] self.likefile = join(likedir,self['output']['likefile']) self.mergefile = join(likedir,self['output']['mergefile']) self.roifile = join(likedir,self['...
Write a copy of this config object. Parameters: ----------- outfile : output filename Returns: -------- None
def write(self, filename): """ Write a copy of this config object. Parameters: ----------- outfile : output filename Returns: -------- None """ ext = os.path.splitext(filename)[1] writer = open(filename, 'w') if ex...
Create a masked records array of all filenames for the given set of pixels and store the existence of those files in the mask values. Examples: f = getFilenames([1,2,3]) # All possible catalog files f['catalog'].data # All existing catalog files f['catalog'][~f.m...
def _createFilenames(self,pixels=None): """ Create a masked records array of all filenames for the given set of pixels and store the existence of those files in the mask values. Examples: f = getFilenames([1,2,3]) # All possible catalog files f['catalog'].data ...
Create a masked records array of all filenames for the given set of pixels and store the existence of those files in the mask values. Parameters: ----------- None Returns: -------- recarray : pixels and mask value
def _createFilenames(self): """ Create a masked records array of all filenames for the given set of pixels and store the existence of those files in the mask values. Parameters: ----------- None Returns: -------- recarray : pixels and mask value ...
Return the requested filenames. Parameters: ----------- pixels : requeseted pixels Returns: -------- filenames : recarray
def getFilenames(self,pixels=None): """ Return the requested filenames. Parameters: ----------- pixels : requeseted pixels Returns: -------- filenames : recarray """ logger.debug("Getting filenames...") if pixels is None: ...
Return the indices of the super-pixels which contain each of the sub-pixels.
def superpixel(subpix, nside_subpix, nside_superpix): """ Return the indices of the super-pixels which contain each of the sub-pixels. """ if nside_subpix==nside_superpix: return subpix theta, phi = hp.pix2ang(nside_subpix, subpix) return hp.ang2pix(nside_superpix, theta, phi)
Return the indices of sub-pixels (resolution nside_subpix) within the super-pixel with (resolution nside_superpix). ADW: It would be better to convert to next and do this explicitly
def subpixel(superpix, nside_superpix, nside_subpix): """ Return the indices of sub-pixels (resolution nside_subpix) within the super-pixel with (resolution nside_superpix). ADW: It would be better to convert to next and do this explicitly """ if nside_superpix==nside_subpix: return superpi...
Return the indices of the super-pixels which contain each of the sub-pixels (nside_in > nside_out). Parameters: ----------- ipix : index of the input subpixels nside_in : nside of the input subpix nside_out : nside of the desired superpixels Returns: -------- ipix_out : supe...
def d_grade_ipix(ipix, nside_in, nside_out, nest=False): """ Return the indices of the super-pixels which contain each of the sub-pixels (nside_in > nside_out). Parameters: ----------- ipix : index of the input subpixels nside_in : nside of the input subpix nside_out : nside of th...
Return the indices of sub-pixels (resolution nside_subpix) within the super-pixel(s) (resolution nside_superpix). Parameters: ----------- ipix : index of the input superpixel(s) nside_in : nside of the input superpixel nside_out : nside of the desired subpixels Returns: -----...
def u_grade_ipix(ipix, nside_in, nside_out, nest=False): """ Return the indices of sub-pixels (resolution nside_subpix) within the super-pixel(s) (resolution nside_superpix). Parameters: ----------- ipix : index of the input superpixel(s) nside_in : nside of the input superpixel ...
Upgrade or degrade resolution of a pixel list. Parameters: ----------- ipix:array-like the input pixel(s) nside_in:int the nside of the input pixel(s) nside_out:int the desired nside of the output pixel(s) order:str pixel ordering of input and output ("RING" or "NESTED") ...
def ud_grade_ipix(ipix, nside_in, nside_out, nest=False): """ Upgrade or degrade resolution of a pixel list. Parameters: ----------- ipix:array-like the input pixel(s) nside_in:int the nside of the input pixel(s) nside_out:int the desired nside of the output pixel(s) ord...
Return (lon, lat) in degrees instead of (theta, phi) in radians
def pix2ang(nside, pix, nest=False): """ Return (lon, lat) in degrees instead of (theta, phi) in radians """ theta, phi = hp.pix2ang(nside, pix, nest=nest) lon = phi2lon(phi) lat = theta2lat(theta) return lon, lat
Input (lon, lat) in degrees instead of (theta, phi) in radians
def ang2pix(nside, lon, lat, nest=False): """ Input (lon, lat) in degrees instead of (theta, phi) in radians """ theta = np.radians(90. - lat) phi = np.radians(lon) return healpy.ang2pix(nside, theta, phi, nest=nest)
Input (lon, lat) in degrees instead of (theta, phi) in radians. Returns HEALPix map at the desired resolution
def healpixMap(nside, lon, lat, fill_value=0., nest=False): """ Input (lon, lat) in degrees instead of (theta, phi) in radians. Returns HEALPix map at the desired resolution """ lon_median, lat_median = np.median(lon), np.median(lat) max_angsep = np.max(ugali.utils.projector.angsep(lon, lat, l...
Find the indices of a set of pixels into another set of pixels. !!! ASSUMES SORTED PIXELS !!! Parameters: ----------- pix : set of search pixels pixels : set of reference pixels Returns: -------- index : index into the reference pixels
def index_pix_in_pixels(pix,pixels,sort=False,outside=-1): """ Find the indices of a set of pixels into another set of pixels. !!! ASSUMES SORTED PIXELS !!! Parameters: ----------- pix : set of search pixels pixels : set of reference pixels Returns: -------- index : index ...
Find the indices of a set of angles into a set of pixels Parameters: ----------- pix : set of search pixels pixels : set of reference pixels Returns: -------- index : index into the reference pixels
def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1): """ Find the indices of a set of angles into a set of pixels Parameters: ----------- pix : set of search pixels pixels : set of reference pixels Returns: -------- index : index into the reference pixels ...
Wrap `query_disc` to use lon, lat, and radius in degrees.
def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False): """ Wrap `query_disc` to use lon, lat, and radius in degrees. """ vec = ang2vec(lon,lat) return query_disc(nside,vec,radius,inclusive,fact,nest)
Mimic the healpy header keywords.
def header_odict(nside,nest=False,coord=None, partial=True): """Mimic the healpy header keywords.""" hdr = odict([]) hdr['PIXTYPE']=odict([('name','PIXTYPE'), ('value','HEALPIX'), ('comment','HEALPIX pixelisation')]) ordering = 'NEST' if nest else 'RI...
Partial HEALPix maps are used to efficiently store maps of the sky by only writing out the pixels that contain data. Three-dimensional data can be saved by supplying a distance modulus array which is stored in a separate extension. Parameters: ----------- filename : output file name data ...
def write_partial_map(filename, data, nside, coord=None, nest=False, header=None,dtype=None,**kwargs): """ Partial HEALPix maps are used to efficiently store maps of the sky by only writing out the pixels that contain data. Three-dimensional data can be saved by supplying a distan...
Read a partial HEALPix file(s) and return pixels and values/map. Can handle 3D healpix maps (pix, value, zdim). Returned array has shape (dimz,npix). Parameters: ----------- filenames : list of input filenames column : column of interest fullsky : partial or fullsky map ...
def read_partial_map(filenames, column, fullsky=True, **kwargs): """ Read a partial HEALPix file(s) and return pixels and values/map. Can handle 3D healpix maps (pix, value, zdim). Returned array has shape (dimz,npix). Parameters: ----------- filenames : list of input filenames colu...
Merge header information from likelihood files. Parameters: ----------- filenames : input filenames oufile : the merged file to write Returns: -------- data : the data being written
def merge_likelihood_headers(filenames, outfile): """ Merge header information from likelihood files. Parameters: ----------- filenames : input filenames oufile : the merged file to write Returns: -------- data : the data being written """ filenames = np.atleas...
Read a healpix map from a fits file. Partial-sky files, if properly identified, are expanded to full size and filled with UNSEEN. Uses fitsio to mirror much (but not all) of the functionality of healpy.read_map Parameters: ----------- filename : str the fits file name nest : bool, o...
def read_map(filename, nest=False, hdu=None, h=False, verbose=True): """Read a healpix map from a fits file. Partial-sky files, if properly identified, are expanded to full size and filled with UNSEEN. Uses fitsio to mirror much (but not all) of the functionality of healpy.read_map Parameters: ...
Converts a number to float or int as appropriate
def _convert_number(self, number): """Converts a number to float or int as appropriate""" number = float(number) return int(number) if number.is_integer() else float(number)
Write the results output file
def do_results(args): """ Write the results output file """ config,name,label,coord = args filenames = make_filenames(config,label) srcfile = filenames['srcfile'] samples = filenames['samfile'] if not exists(srcfile): logger.warning("Couldn't find %s; skipping..."%srcfile) retu...
Write the membership output file
def do_membership(args): """ Write the membership output file """ config,name,label,coord = args filenames = make_filenames(config,label) srcfile = filenames['srcfile'] memfile = filenames['memfile'] logger.info("Writing %s..."%memfile) from ugali.analysis.loglike import write_membership ...
Create plots of mcmc output
def do_plot(args): """ Create plots of mcmc output """ import ugali.utils.plotting import pylab as plt config,name,label,coord = args filenames = make_filenames(config,label) srcfile = filenames['srcfile'] samfile = filenames['samfile'] memfile = filenames['memfile'] if not exists(...
Return our initialized dictionary arguments.
def parse(self, *args): """ Return our initialized dictionary arguments. """ if isinstance(self.dictionary, dict): return self.dictionary raise self.subparserException("Argument passed to Dictionary SubParser is not a dict: %s" % type(self.dictionary))
Caches variants_dict and replace_dict in a single database hit.
def _caches_dicts(self): """ Caches variants_dict and replace_dict in a single database hit. """ qs = (self.get_query_set() if django.VERSION < (1, 6) else self.get_queryset()) variants_dict = self._get_variants_dict(qs) cache.set(VARIANTS_DICT_CACHE_KEY, ...
Returns (path, address) based on consecutive optional arguments, [path] [address].
def resolve(path_or_address=None, address=None, *ignored): """ Returns (path, address) based on consecutive optional arguments, [path] [address]. """ if path_or_address is None or address is not None: return path_or_address, address path = None if split_address(path_or_address)[1] i...
Returns (host, port) with an integer port from the specified address string. (None, None) is returned if the address is invalid.
def split_address(address): """ Returns (host, port) with an integer port from the specified address string. (None, None) is returned if the address is invalid. """ invalid = None, None if not address and address != 0: return invalid components = str(address).split(':') if len(...
Translate a botocore.exceptions.ClientError into a dynamo3 error
def translate_exception(exc, kwargs): """ Translate a botocore.exceptions.ClientError into a dynamo3 error """ error = exc.response['Error'] error.setdefault('Message', '') err_class = EXC.get(error['Code'], DynamoDBError) return err_class(exc.response['ResponseMetadata']['HTTPStatusCode'], ...
Raise this exception with the original traceback
def re_raise(self): """ Raise this exception with the original traceback """ if self.exc_info is not None: six.reraise(type(self), self, self.exc_info[2]) else: raise self
r""" Yield text one line at a time from from a single file path, files in a directory, or a text string >>> list(generate_lines('Hello crazy\r\nMS/Apple world\rof EOLS.\n')) ['Hello crazy\r\n', 'MS/Apple world\r', 'of EOLS.\n']
def generate_lines(text, ext=['.txt', '.md', '.rst', '.asciidoc', '.asc']): r""" Yield text one line at a time from from a single file path, files in a directory, or a text string >>> list(generate_lines('Hello crazy\r\nMS/Apple world\rof EOLS.\n')) ['Hello crazy\r\n', 'MS/Apple world\r', 'of EOLS.\n'] ...
Split text into segments (sections, paragraphs) using regular expressions to trigger breaks.start
def segment_text(text=os.path.join(DATA_PATH, 'goodreads-omniscient-books.txt'), start=None, stop=r'^Rate\ this', ignore=r'^[\d]'): """ Split text into segments (sections, paragraphs) using regular expressions to trigger breaks.start """ start = start if hasattr(start, 'match') else re.comp...
Return a list of n-tuples, one for each possible sequence of n items in the token_list Arguments: join (bool or str): if str, then join ngrom tuples on it before returning True is equivalent to join=' ' default = True See: http://stackoverflow.com/a/30609050/623735 >>> list_ngrams...
def list_ngrams(token_list, n=1, join=' '): """Return a list of n-tuples, one for each possible sequence of n items in the token_list Arguments: join (bool or str): if str, then join ngrom tuples on it before returning True is equivalent to join=' ' default = True See: http://stack...
Return a list of n-tuples, one for each possible sequence of n items in the token_list Arguments: join (bool or str): if str, then join ngrom tuples on it before returning True is equivalent to join=' ' default = True >>> list_ngram_range('goodbye cruel world'.split(), 0, 2, join=False...
def list_ngram_range(token_list, *args, **kwargs): """Return a list of n-tuples, one for each possible sequence of n items in the token_list Arguments: join (bool or str): if str, then join ngrom tuples on it before returning True is equivalent to join=' ' default = True >>> list_n...
Generate sentences from a sequence of characters (text) Wrapped text (newlines at column 80, for instance) will break this, breaking up sentences. Wrapper and preprocessor for Kyle Gorman's "DetectorMorse" module Arguments: preprocess (bool): whether to assume common sentence delimitters in markdown...
def generate_sentences(text='', train_path=None, case_sensitive=True, ext=['.md', '.txt', '.asc', '.asciidoc'], normalize_ordinals=1, normalize_newlines=1, normalize_sentence_boundaries=1, epochs=20, classifier=nlup.BinaryAveragedPerceptron, re_eol=r'...
Add a timestamp and date to the data
def add(self, now, num): """ Add a timestamp and date to the data """ if num == 0: return self.points.append((now, num))
Get the summation of all non-expired points
def value(self): """ Get the summation of all non-expired points """ now = time.time() cutoff = now - self.window while self.points and self.points[0][0] < cutoff: self.points.pop(0) return sum([p[1] for p in self.points])
Getter for a consumed capacity storage dict
def get_consumed(self, key): """ Getter for a consumed capacity storage dict """ if key not in self._consumed: self._consumed[key] = { 'read': DecayingCapacityStore(), 'write': DecayingCapacityStore(), } return self._consumed[key]
Hook that runs in response to a 'returned capacity' event
def on_capacity(self, connection, command, query_kwargs, response, capacity): """ Hook that runs in response to a 'returned capacity' event """ now = time.time() args = (connection, command, query_kwargs, response, capacity) # Check total against the total_cap ...