INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
DEPRECATED: ADW 2017-09-20 Compute the stellar luminosity (L_Sol; average per star). Uses "sample" to generate mass sample and pdf. The range of integration only covers the input isochrone data (no extrapolation used), but this seems like a sub-percent effect if the isochrone g...
def stellar_luminosity2(self, steps=10000): """ DEPRECATED: ADW 2017-09-20 Compute the stellar luminosity (L_Sol; average per star). Uses "sample" to generate mass sample and pdf. The range of integration only covers the input isochrone data (no extrapolation used), but...
Calculate the absolute visual magnitude (Mv) from the richness by transforming the isochrone in the SDSS system and using the g,r -> V transform equations from Jester 2005 [astro-ph/0506022]. Parameters: ----------- richness : isochrone normalization parameter s...
def absolute_magnitude(self, richness=1, steps=1e4): """ Calculate the absolute visual magnitude (Mv) from the richness by transforming the isochrone in the SDSS system and using the g,r -> V transform equations from Jester 2005 [astro-ph/0506022]. Parameters: -...
Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits should depend on the survey maglim? Parameters: ----------- richness : Isochrone nomalization factor steps : N...
def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None): """ Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits ...
Simulate a set of stellar magnitudes (no uncertainty) for a satellite of a given stellar mass and distance. Parameters: ----------- stellar_mass : the total stellar mass of the system (Msun) distance_modulus : distance modulus of the system (if None takes from isochrone) ...
def simulate(self, stellar_mass, distance_modulus=None, **kwargs): """ Simulate a set of stellar magnitudes (no uncertainty) for a satellite of a given stellar mass and distance. Parameters: ----------- stellar_mass : the total stellar mass of the system (Msun) d...
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatalogToObservable space. However, for technical reasons it ...
def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the sam...
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatalogToObservable space. However, for technical reasons it ...
def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same...
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. Incorporates simplistic photometric errors. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatalogToObservable sp...
def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. Incorporates simplistic photometric errors. ADW: Careful, this function is fragile...
Return a 2D histogram the isochrone in mag-mag space. Parameters: ----------- distance_modulus : distance modulus to calculate histogram at delta_mag : magnitude bin size mass_steps : number of steps to sample isochrone at Returns: -------- bins_mag_1 : ...
def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000): """ Return a 2D histogram the isochrone in mag-mag space. Parameters: ----------- distance_modulus : distance modulus to calculate histogram at delta_mag : magnitude bin size mass_steps : num...
Ok, now here comes the beauty of having the signal MMD.
def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000): """ Ok, now here comes the beauty of having the signal MMD. """ logger.info('Running MMD pdf') roi = mask.roi mmd = self.signalMMD(mask,distance_modulus,delta_mag=delta_mag,ma...
Compute isochrone probability for each catalog object. ADW: This is a memory intensive function, so try as much as possible to keep array types at `float32` or smaller (maybe using add.at would be good?) ADW: Still a little speed to be gained here (broadcasting) ADW: Units? [ma...
def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2, distance_modulus=None, delta_mag=0.03, steps=10000): """ Compute isochrone probability for each catalog object. ADW: This is a memory intensive function, so try as much as possible to keep array types at `float32` or smalle...
Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : The magnitude of the test points in the first band mag_2 : The m...
def raw_separation(self,mag_1,mag_2,steps=10000): """ Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : T...
Calculate the separation between a specific point and the isochrone in magnitude-magnitude space. Uses an interpolation ADW: Could speed this up... Parameters: ----------- mag_1 : The magnitude of the test points in the first band mag_2 : The magnitude of the test point...
def separation(self, mag_1, mag_2): """ Calculate the separation between a specific point and the isochrone in magnitude-magnitude space. Uses an interpolation ADW: Could speed this up... Parameters: ----------- mag_1 : The magnitude of the test points in the f...
Check valid parameter range and download isochrones from: http://stev.oapd.inaf.it/cgi-bin/cmd
def download(self,age=None,metallicity=None,outdir=None,force=False): """ Check valid parameter range and download isochrones from: http://stev.oapd.inaf.it/cgi-bin/cmd """ try: from urllib.error import URLError except ImportError: from urllib2 imp...
Get the router's URLs, ready to be installed in `urlpatterns` (directly or via `include`). :param root_view_name: The optional url name for an API root view. This may be useful for projects that do not explicitly know where the router is mounted; th...
def get_urls( self, root_view_name=None, optional_trailing_slash=False, decorate=(), name_template='{name}', ): """ Get the router's URLs, ready to be installed in `urlpatterns` (directly or via `include`). :param root_view_name: The optional url name...
Get the handler function for a given operation. To remain Pythonic, both the original and the snake_cased version of the operation ID are supported. This could be overridden in a subclass. :param operation_id: Operation ID. :return: Handler function :rtype: function
def get_handler(self, operation_id): """ Get the handler function for a given operation. To remain Pythonic, both the original and the snake_cased version of the operation ID are supported. This could be overridden in a subclass. :param operation_id: Operation ID. ...
Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-prefixed functions and methods are imported. :para...
def add_handlers(self, namespace): """ Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-pref...
Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context.
def get_context(self, arr, expr, context): """ Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context. """ expression_names = [x for x in self.get_expr...
Raise a server error indicating a request timeout to the given URL.
def timeout_error(url, timeout): """Raise a server error indicating a request timeout to the given URL.""" msg = 'Request timed out: {} timeout: {}s'.format(url, timeout) log.warning(msg) return ServerError(msg)
Creates and returns a masked view of the input array.
def execute(self, array_in, expression, **kwargs): """Creates and returns a masked view of the input array.""" context = self.get_context(array_in, expression, kwargs) context.update(kwargs) return ma.masked_where(self.evaluate_expression(expression, context), array_in)
Return partial sums of the Gregory series converging to atan(1) == pi/4. Yield 1 - 1/3 + 1/5 - 1/7 + ... computed with the given type.
def Gregory(type=float): """Return partial sums of the Gregory series converging to atan(1) == pi/4. Yield 1 - 1/3 + 1/5 - 1/7 + ... computed with the given type. """ return seq(type(1), step=2) >> map(lambda x: 1/x) >> alt_sign >> fold(operator.add)
Accelerate the convergence of the a series using Aitken's delta-squared process (SCIP calls it Euler).
def Aitken(s): """Accelerate the convergence of the a series using Aitken's delta-squared process (SCIP calls it Euler). """ def accel(): s0, s1, s2 = s >> item[:3] while 1: yield s2 - (s2 - s1)**2 / (s0 - 2*s1 + s2) s0, s1, s2 = s1, s2, next(s) return accel()
Upload an array to a personal database using SOAP POST protocol. http://skyserver.sdss3.org/casjobs/services/jobs.asmx?op=UploadData
def upload(self, array, fields=None, table="MyDB", configfile=None): """ Upload an array to a personal database using SOAP POST protocol. http://skyserver.sdss3.org/casjobs/services/jobs.asmx?op=UploadData """ wsid='' password='' if configfile is None: ...
Download the survey footprint for HEALpix pixels.
def footprint(self,nside): """ Download the survey footprint for HEALpix pixels. """ import healpy import ugali.utils.projector if nside > 2**9: raise Exception("Overflow error: nside must be <=2**9") pix = np.arange(healpy.nside2npix(nside),dtype='int') f...
Plot a basic histogram.
def histogram(title, title_x, title_y, x, bins_x): """ Plot a basic histogram. """ plt.figure() plt.hist(x, bins_x) plt.xlabel(title_x) plt.ylabel(title_y) plt.title(title)
Create a two-dimension histogram plot or binned map. If using the outputs of np.histogram2d, remember to transpose the histogram. INPUTS
def twoDimensionalHistogram(title, title_x, title_y, z, bins_x, bins_y, lim_x=None, lim_y=None, vmin=None, vmax=None): """ Create a two-dimension histogram plot or binned map. If using the outputs of np.histogram2d, remembe...
Create a two-dimensional scatter plot. INPUTS
def twoDimensionalScatter(title, title_x, title_y, x, y, lim_x = None, lim_y = None, color = 'b', size = 20, alpha=None): """ Create a two-dimensional scatter plot. INPUTS """ plt.figure() plt.scatter(x, y, c=color, ...
Inputs: lon (deg), lat (deg), radius (deg)
def zoomedHealpixMap(title, map, lon, lat, radius, xsize=1000, **kwargs): """ Inputs: lon (deg), lat (deg), radius (deg) """ reso = 60. * 2. * radius / xsize # Deg to arcmin hp.gnomview(map=map, rot=[lon, lat, 0], title=title, xsize=xsize, reso=reso, degree=False, **kwargs)
Create a scatter plot on HEALPix projected axes. Inputs: lon (deg), lat (deg)
def projScatter(lon, lat, **kwargs): """ Create a scatter plot on HEALPix projected axes. Inputs: lon (deg), lat (deg) """ hp.projscatter(lon, lat, lonlat=True, **kwargs)
Inputs: field
def sparseHealpixFiles(title, infiles, field='MAGLIM',**kwargs): """ Inputs: field """ #map = ugali.utils.skymap.readSparseHealpixMaps(infiles,field) map = ugali.utils.skymap.read_partial_map(infiles,field) ax = hp.mollview(map=map, title=title, **kwargs) return ax, m...
Draw local projection of healpix map.
def drawHealpixMap(hpxmap, lon, lat, size=1.0, xsize=501, coord='GC', **kwargs): """ Draw local projection of healpix map. """ ax = plt.gca() x = np.linspace(-size,size,xsize) y = np.linspace(-size,size,xsize) xx, yy = np.meshgrid(x,y) coord = coord.upper() if coord == ...
Download Sloan Digital Sky Survey images http://skyserver.sdss3.org/dr9/en/tools/chart/chart.asp radius (degrees) opts: (G) Grid, (L) Label, P (PhotoObj), S (SpecObj), O (Outline), (B) Bounding Box, (F) Fields, (M) Mask, (Q) Plates, (I) Invert
def getSDSSImage(ra,dec,radius=1.0,xsize=800,opt='GML',**kwargs): """ Download Sloan Digital Sky Survey images http://skyserver.sdss3.org/dr9/en/tools/chart/chart.asp radius (degrees) opts: (G) Grid, (L) Label, P (PhotoObj), S (SpecObj), O (Outline), (B) Bounding Box, (F) Fields, (M) Mas...
Download Digitized Sky Survey images https://archive.stsci.edu/cgi-bin/dss_form https://archive.stsci.edu/cgi-bin/dss_search Image is in celestial orientation (RA increases to the right) https://archive.stsci.edu/dss/script_usage.html ra (r) - right ascension dec (d) - declination equ...
def getDSSImage(ra,dec,radius=1.0,xsize=800,**kwargs): """ Download Digitized Sky Survey images https://archive.stsci.edu/cgi-bin/dss_form https://archive.stsci.edu/cgi-bin/dss_search Image is in celestial orientation (RA increases to the right) https://archive.stsci.edu/dss/script_usage.h...
Draw horizontal and vertical slices through histogram
def draw_slices(hist, func=np.sum, **kwargs): """ Draw horizontal and vertical slices through histogram """ from mpl_toolkits.axes_grid1 import make_axes_locatable kwargs.setdefault('ls','-') ax = plt.gca() data = hist # Slices vslice = func(data,axis=0) hslice = func(data,axis=1) ...
Plot a catalog of coordinates on a full-sky map.
def plotSkymapCatalog(lon,lat,**kwargs): """ Plot a catalog of coordinates on a full-sky map. """ fig = plt.figure() ax = plt.subplot(111,projection=projection) drawSkymapCatalog(ax,lon,lat,**kwargs)
Create closed path.
def makePath(x_path, y_path, epsilon=1.e-10): """ Create closed path. """ x_path_closed = np.concatenate([x_path, x_path[::-1]]) y_path_closed = np.concatenate([y_path, epsilon + y_path[::-1]]) path = matplotlib.path.Path(list(zip(x_path_closed, y_path_closed))) return path
Cut to identify objects within isochrone cookie-cutter. ADW: This should be moved into the isochrone class.
def cutIsochronePath(g, r, g_err, r_err, isochrone, radius=0.1, return_all=False): """ Cut to identify objects within isochrone cookie-cutter. ADW: This should be moved into the isochrone class. """ import scipy.interpolate from ugali.isochrone import CompositeIsochrone if isinstance(isoch...
Draw the maglim from the mask.
def drawMask(self,ax=None, mask=None, mtype='maglim'): """ Draw the maglim from the mask. """ if not ax: ax = plt.gca() if mask is None: mask = ugali.analysis.loglike.createMask(self.config,roi=self.roi) mask_map = hp.UNSEEN*np.ones(hp.nside2npix(self.nside)) if mtyp...
Parse configuration options out of an .ini configuration file. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration options populated thus far. Outputs: A dictionary of new configu...
def parse(self, configManager, config): """ Parse configuration options out of an .ini configuration file. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration options popul...
Create a chapter that contains a random number of paragraphs
def write_chapter(self): """ Create a chapter that contains a random number of paragraphs """ self.paragraphs = [] self.paragraphs.append('\n') for x in range(randint(0, 50)): p = Paragraph(self.model) self.paragraphs.append(p.get_p...
Create CSS file.
def buildcss(app, buildpath, imagefile): """Create CSS file.""" # set default values div = 'body' repeat = 'repeat-y' position = 'center' attachment = 'scroll' if app.config.sphinxmark_div != 'default': div = app.config.sphinxmark_div if app.config.sphinxmark_repeat is False: ...
Create PNG image from string.
def createimage(app, srcdir, buildpath): """Create PNG image from string.""" text = app.config.sphinxmark_text # draw transparent background width = app.config.sphinxmark_text_width height = app.config.sphinxmark_text_spacing img = Image.new('RGBA', (width, height), (255, 255, 255, 0)) d = ...
Get image file.
def getimage(app): """Get image file.""" # append source directory to TEMPLATE_PATH so template is found srcdir = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_PATH.append(srcdir) staticbase = '_static' buildpath = os.path.join(app.outdir, staticbase) try: os.makedirs(buildpath...
Add watermark.
def watermark(app, env): """Add watermark.""" if app.config.sphinxmark_enable is True: LOG.info('adding watermark...', nonl=True) buildpath, imagefile = getimage(app) cssname = buildcss(app, buildpath, imagefile) app.add_css_file(cssname) LOG.info(' done')
Configure setup for Sphinx extension. :param app: Sphinx application context.
def setup(app): """ Configure setup for Sphinx extension. :param app: Sphinx application context. """ app.add_config_value('sphinxmark_enable', False, 'html') app.add_config_value('sphinxmark_div', 'default', 'html') app.add_config_value('sphinxmark_border', None, 'html') app.add_config...
Get a Django function view calling the given method (and pre/post-processors) :param method_name: The method on the class :return: View function
def get_view(cls, method_name): """ Get a Django function view calling the given method (and pre/post-processors) :param method_name: The method on the class :return: View function """ method = getattr(cls, method_name) @wraps(method) def view(request, *...
Uses Stirling's approximation for the log-gamma function suitable for large arguments.
def gammalnStirling(z): """ Uses Stirling's approximation for the log-gamma function suitable for large arguments. """ return (0.5 * (np.log(2. * np.pi) - np.log(z))) \ + (z * (np.log(z + (1. / ((12. * z) - (1. / (10. * z))))) - 1.))
Given n tests and k successes, return efficiency and confidence interval.
def confidenceInterval(n, k, alpha = 0.68, errorbar=False): """ Given n tests and k successes, return efficiency and confidence interval. """ try: e = float(k) / float(n) except ZeroDivisionError: return np.nan, [np.nan, np.nan] bins = 1000001 dx = 1. / bins efficiency ...
Given n tests and k successes, return efficiency and confidence interval.
def binomialInterval(n, k, alpha = 0.68): """ Given n tests and k successes, return efficiency and confidence interval. """ e = float(k)/n delta_e = 1/float(n) * np.sqrt(e * (1 - e) * float(n)) * alpha/0.68 return e, [e - delta_e, e + delta_e]
Wrapping the isochrone and kernel simulate functions.
def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs): """ Wrapping the isochrone and kernel simulate functions. """ mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus) lon, lat = kernel.simulate(len(mag_1)) return mag_1, mag_2, lon, lat
An a priori detectability proxy.
def detectability(self,**kwargs): """ An a priori detectability proxy. """ distance_modulus = kwargs.get('distance_modulus') distance = mod2dist(distance_modulus) stellar_mass = kwargs.get('stellar_mass') extension = kwargs.get('extension') # Normalized t...
Bundle it.
def _create_catalog(self,catalog=None): """ Bundle it. """ if catalog is None: catalog = ugali.analysis.loglike.createCatalog(self.config,self.roi) cut = self.mask.restrictCatalogToObservableSpace(catalog) self.catalog = catalog.applyCut(cut)
Realistic photometric errors estimated from catalog objects and mask. Extend below the magnitude threshold with a flat extrapolation.
def _photometricErrors(self, n_per_bin=100, plot=False): """ Realistic photometric errors estimated from catalog objects and mask. Extend below the magnitude threshold with a flat extrapolation. """ self.catalog.spatialBin(self.roi) if len(self.catalog.mag_1) < n_per_bi...
Subpixels for random position generation.
def _setup_subpix(self,nside=2**16): """ Subpixels for random position generation. """ # Only setup once... if hasattr(self,'subpix'): return # Simulate over full ROI self.roi_radius = self.config['coords']['roi_radius'] # Setup background spatial stuff...
The purpose here is to create a more finely binned background CMD to sample from.
def _setup_cmd(self,mode='cloud-in-cells'): """ The purpose here is to create a more finely binned background CMD to sample from. """ # Only setup once... if hasattr(self,'bkg_lambda'): return logger.info("Setup color...") # In the limit theta->0: 2*pi*(1...
Quick uniform background generation.
def toy_background(self,mc_source_id=2,seed=None): """ Quick uniform background generation. """ logger.info("Running toy background simulation...") size = 20000 nstar = np.random.poisson(size) #np.random.seed(0) logger.info("Simulating %i background stars...
Create a simulation of the background stellar population. Because some stars have been clipped to generate the CMD, this function tends to slightly underestimate (~1%) the background as compared to the true catalog. The simulation of background object colors relies on the data-...
def background(self,mc_source_id=2,seed=None): """ Create a simulation of the background stellar population. Because some stars have been clipped to generate the CMD, this function tends to slightly underestimate (~1%) the background as compared to the true catalog. The...
Create a simulated satellite. Returns a catalog object.
def satellite(self,stellar_mass,distance_modulus,mc_source_id=1,seed=None,**kwargs): """ Create a simulated satellite. Returns a catalog object. """ if seed is not None: np.random.seed(seed) isochrone = kwargs.pop('isochrone',self.isochrone) kernel = kwargs.pop('kerne...
Create a catalog fits file object based on input data. ADW: This should be combined with the write_membership function of loglike.
def makeHDU(self, mag_1, mag_err_1, mag_2, mag_err_2, lon, lat, mc_source_id): """ Create a catalog fits file object based on input data. ADW: This should be combined with the write_membership function of loglike. """ if self.config['catalog']['coordsys'].lower() == 'cel...
Ensure all column name strings are valid python variable/attribute names >>> df = pd.DataFrame(np.zeros((2, 3)), columns=['WAT??', "Don't do th!s, way too long. ya-think????", 'ok-this123.456']) >>> df.columns = clean_columns(df.columns, max_len=12) >>> df.head() wat dont_do_ths_ okthis123456 ...
def clean_columns(columns, valid_regex=r'\w', lower=True, max_len=32): """ Ensure all column name strings are valid python variable/attribute names >>> df = pd.DataFrame(np.zeros((2, 3)), columns=['WAT??', "Don't do th!s, way too long. ya-think????", 'ok-this123.456']) >>> df.columns = clean_columns(df.co...
Force frozenset() command to freeze the order and contents of mutables and iterables like lists, dicts, generators Useful for memoization and constructing dicts or hashtables where keys must be immutable. FIXME: Rename function because "hashable" is misleading. A better name might be `force_immutab...
def force_hashable(obj, recursive=True): """Force frozenset() command to freeze the order and contents of mutables and iterables like lists, dicts, generators Useful for memoization and constructing dicts or hashtables where keys must be immutable. FIXME: Rename function because "hashable" is misleading. ...
Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True
def inverted_dict(d): """Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True """ return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
Return a dict where the keys are all the values listed in the values of the original dict >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1} True
def inverted_dict_of_lists(d): """Return a dict where the keys are all the values listed in the values of the original dict >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1} True """ new_dict = {} for (old_key, old_value_list) in viewitems(dict(d)): for n...
Sort a list of strings according to the provided sorted list of string prefixes TODO: - Provide an option to use `.startswith()` rather than a fixed prefix length (will be much slower) Arguments: sort_order_first (bool): Whether strings in sort_order should always preceed "unknown" strings ...
def sort_strings(strings, sort_order=None, reverse=False, case_sensitive=False, sort_order_first=True): """Sort a list of strings according to the provided sorted list of string prefixes TODO: - Provide an option to use `.startswith()` rather than a fixed prefix length (will be much slower) Argume...
r"""Normalize field values by stripping whitespace from strings, localizing datetimes to a timezone, etc >>> (sorted(clean_field_dict({'_state': object(), 'x': 1, 'y': "\t Wash Me! \n" }).items()) == ... [('x', 1), ('y', 'Wash Me!')]) True
def clean_field_dict(field_dict, cleaner=str.strip, time_zone=None): r"""Normalize field values by stripping whitespace from strings, localizing datetimes to a timezone, etc >>> (sorted(clean_field_dict({'_state': object(), 'x': 1, 'y': "\t Wash Me! \n" }).items()) == ... [('x', 1), ('y', 'Wash Me!')]) ...
Find spelling variations of similar words within a list of tokens to reduce token set size Lexically sorted in reverse order (unless `reverse=False`), before running through fuzzy-wuzzy which results in the longer of identical spellings to be prefered (e.g. "ones" prefered to "one") as the key token. Usual...
def reduce_vocab(tokens, similarity=.85, limit=20, sort_order=-1): """Find spelling variations of similar words within a list of tokens to reduce token set size Lexically sorted in reverse order (unless `reverse=False`), before running through fuzzy-wuzzy which results in the longer of identical spellings ...
Find spelling variations of similar words within a list of tokens to reduce token set size Sorted by length (longest first unless reverse=False) before running through fuzzy-wuzzy which results in longer key tokens. Arguments: tokens (list or set or tuple of str): token strings from which to elimina...
def reduce_vocab_by_len(tokens, similarity=.87, limit=20, reverse=True): """Find spelling variations of similar words within a list of tokens to reduce token set size Sorted by length (longest first unless reverse=False) before running through fuzzy-wuzzy which results in longer key tokens. Arguments:...
r"""Convert strings and datetime objects in the values of a dict into float/int/long, if possible Arguments: field_dict (dict): The dict to have any values (not keys) that are strings "quantified" precision (int): Number of digits of precision to enforce cleaner: A string cleaner to apply to all ...
def quantify_field_dict(field_dict, precision=None, date_precision=None, cleaner=str.strip): r"""Convert strings and datetime objects in the values of a dict into float/int/long, if possible Arguments: field_dict (dict): The dict to have any values (not keys) that are strings "quantified" precision...
Iterate through a sequence (or generator) in batches of length `batch_len` http://stackoverflow.com/a/761125/623735 >>> [batch for batch in generate_batches(range(7), 3)] [[0, 1, 2], [3, 4, 5], [6]]
def generate_batches(sequence, batch_len=1, allow_partial=True, ignore_errors=True, verbosity=1): """Iterate through a sequence (or generator) in batches of length `batch_len` http://stackoverflow.com/a/761125/623735 >>> [batch for batch in generate_batches(range(7), 3)] [[0, 1, 2], [3, 4, 5], [6]] ...
Iterate through a queryset in batches of length `batch_len` >>> [batch for batch in generate_tuple_batches(range(7), 3)] [(0, 1, 2), (3, 4, 5), (6,)]
def generate_tuple_batches(qs, batch_len=1): """Iterate through a queryset in batches of length `batch_len` >>> [batch for batch in generate_tuple_batches(range(7), 3)] [(0, 1, 2), (3, 4, 5), (6,)] """ num_items, batch = 0, [] for item in qs: if num_items >= batch_len: yield...
Iterate through a sequence (or generator) in batches of length `batch_len` See Also: pug.dj.db.generate_queryset_batches References: http://stackoverflow.com/a/761125/623735 Examples: >> [batch for batch in generate_slices(range(7), 3)] [(0, 1, 2), (3, 4, 5), (6,)] >> from...
def generate_slices(sliceable_set, batch_len=1, length=None, start_batch=0): """Iterate through a sequence (or generator) in batches of length `batch_len` See Also: pug.dj.db.generate_queryset_batches References: http://stackoverflow.com/a/761125/623735 Examples: >> [batch for batc...
Find the member of a set that means "count" or "frequency" or "probability" or "number of occurrences".
def find_count_label(d): """Find the member of a set that means "count" or "frequency" or "probability" or "number of occurrences". """ for name in COUNT_NAMES: if name in d: return name for name in COUNT_NAMES: if str(name).lower() in d: return name
>>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you') >>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you', default='Not Found') 'Not Found' >>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'other', default='Not...
def get_key_for_value(dict_obj, value, default=None): """ >>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you') >>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you', default='Not Found') 'Not Found' >>> get_key_for_value({0: 'what', '...
Similar to `list(set(seq))`, but maintains the order of `seq` while eliminating duplicates In general list(set(L)) will not have the same order as the original list. This is a list(set(L)) function that will preserve the order of L. Arguments: seq (iterable): list, tuple, or other iterable to be use...
def list_set(seq): """Similar to `list(set(seq))`, but maintains the order of `seq` while eliminating duplicates In general list(set(L)) will not have the same order as the original list. This is a list(set(L)) function that will preserve the order of L. Arguments: seq (iterable): list, tuple, o...
r"""Find the closest matching key in a dictionary (or element in a list) For a dict, optionally retrieve the associated value associated with the closest key Notes: `possible_keys` must have all string elements or keys! Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne(...
def fuzzy_get(possible_keys, approximate_key, default=None, similarity=0.6, tuple_joiner='|', key_and_value=False, dict_keys=None): r"""Find the closest matching key in a dictionary (or element in a list) For a dict, optionally retrieve the associated value associated with the closest key No...
Like fuzzy_get, but assume the obj is dict-like and return the value without the key Notes: Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()` but in the same order as get(self, key) method on dicts Arguments: obj (dict-like): object to run the get method on u...
def fuzzy_get_value(obj, approximate_key, default=None, **kwargs): """ Like fuzzy_get, but assume the obj is dict-like and return the value without the key Notes: Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()` but in the same order as get(self, key) method on dic...
Find the closest matching key and/or value in a dictionary (must have all string keys!)
def fuzzy_get_tuple(dict_obj, approximate_key, dict_keys=None, key_and_value=False, similarity=0.6, default=None): """Find the closest matching key and/or value in a dictionary (must have all string keys!)""" return fuzzy_get(dict(('|'.join(str(k2) for k2 in k), v) for (k, v) in viewitems(dict_obj)), ...
Return sequence (list) of dictionaries, transposed into a dictionary of sequences (lists) >>> sorted(sod_transposed([{'c': 1, 'cm': 'P'}, {'c': 1, 'ct': 2, 'cm': 6, 'cn': 'MUS'}, ... {'c': 1, 'cm': 'Q', 'cn': 'ROM'}], filler=0).items()) [('c', [1, 1, 1]), ('cm', ['P', 6, 'Q']), ('cn'...
def sod_transposed(seq_of_dicts, align=True, pad=True, filler=None): """Return sequence (list) of dictionaries, transposed into a dictionary of sequences (lists) >>> sorted(sod_transposed([{'c': 1, 'cm': 'P'}, {'c': 1, 'ct': 2, 'cm': 6, 'cn': 'MUS'}, ... {'c': 1, 'cm': 'Q', 'cn': 'RO...
r"""Join a sequence into a tuple or a concatenated string >>> joined_seq(range(3), ', ') '0, 1, 2' >>> joined_seq([1, 2, 3]) (1, 2, 3)
def joined_seq(seq, sep=None): r"""Join a sequence into a tuple or a concatenated string >>> joined_seq(range(3), ', ') '0, 1, 2' >>> joined_seq([1, 2, 3]) (1, 2, 3) """ joined_seq = tuple(seq) if isinstance(sep, basestring): joined_seq = sep.join(str(item) for item in joined_se...
Join (stringify and concatenate) keys (table fields) in a dict (table) of sequences (columns) >>> consolidate_stats(dict([('c', [1, 1, 1]), ('cm', ['P', 6, 'Q']), ('cn', [0, 'MUS', 'ROM']), ... ('ct', [0, 2, 0])]), stats_key='c') [{'P,0,0': 1}, {'6,MUS,2': 1}, {'Q,ROM,0': 1}] >>>...
def consolidate_stats(dict_of_seqs, stats_key=None, sep=','): """Join (stringify and concatenate) keys (table fields) in a dict (table) of sequences (columns) >>> consolidate_stats(dict([('c', [1, 1, 1]), ('cm', ['P', 6, 'Q']), ('cn', [0, 'MUS', 'ROM']), ... ('ct', [0, 2, 0])]), stat...
Produce dictionary of sequences from sequence of sequences, optionally with a header "row". >>> dos_from_table([['hello', 'world'], [1, 2], [3,4]]) == {'hello': [1, 3], 'world': [2, 4]} True
def dos_from_table(table, header=None): """Produce dictionary of sequences from sequence of sequences, optionally with a header "row". >>> dos_from_table([['hello', 'world'], [1, 2], [3,4]]) == {'hello': [1, 3], 'world': [2, 4]} True """ start_row = 0 if not table: return table if n...
Like `numpy.transposed`, but allows uneven row lengths Uneven lengths will affect the order of the elements in the rows of the transposed lists >>> transposed_lists([[1, 2], [3, 4, 5], [6]]) [[1, 3, 6], [2, 4], [5]] >>> transposed_lists(transposed_lists([[], [1, 2, 3], [4]])) [[1, 2, 3], [4]] ...
def transposed_lists(list_of_lists, default=None): """Like `numpy.transposed`, but allows uneven row lengths Uneven lengths will affect the order of the elements in the rows of the transposed lists >>> transposed_lists([[1, 2], [3, 4, 5], [6]]) [[1, 3, 6], [2, 4], [5]] >>> transposed_lists(transpo...
Like numpy.transposed, evens up row (list) lengths that aren't uniform, filling with None. Also, makes all elements a uniform type (default=type(matrix[0][0])), except for filler elements. TODO: add feature to delete None's at the end of rows so that transpose(transpose(LOL)) = LOL >>> transposed_mat...
def transposed_matrix(matrix, filler=None, row_type=list, matrix_type=list, value_type=None): """Like numpy.transposed, evens up row (list) lengths that aren't uniform, filling with None. Also, makes all elements a uniform type (default=type(matrix[0][0])), except for filler elements. TODO: add featur...
Compute an emprical histogram, PMF or CDF in a list of lists TESTME: compare results to hist_from_values_list and hist_from_float_values_list
def hist_from_counts(counts, normalize=False, cumulative=False, to_str=False, sep=',', min_bin=None, max_bin=None): """Compute an emprical histogram, PMF or CDF in a list of lists TESTME: compare results to hist_from_values_list and hist_from_float_values_list """ counters = [dict((i, c)for i, c in enu...
Compute an emprical histogram, PMF or CDF in a list of lists or a csv string Only works for discrete (integer) values (doesn't bin real values). `fillers`: list or tuple of values to ignore in computing the histogram >>> hist_from_values_list([1,1,2,1,1,1,2,3,2,4,4,5,7,7,9]) # doctest: +NORMALIZE_WHITESP...
def hist_from_values_list(values_list, fillers=(None,), normalize=False, cumulative=False, to_str=False, sep=',', min_bin=None, max_bin=None): """Compute an emprical histogram, PMF or CDF in a list of lists or a csv string Only works for discrete (integer) values (doesn't bin real val...
Similar to fuzzy_get, but allows non-string keys and a list of possible keys Searches attributes in addition to keys and indexes to find the closest match. See Also: `fuzzy_get`
def get_similar(obj, labels, default=None, min_similarity=0.5): """Similar to fuzzy_get, but allows non-string keys and a list of possible keys Searches attributes in addition to keys and indexes to find the closest match. See Also: `fuzzy_get` """ raise NotImplementedError( "Unfi...
Recursively merge (union or update) dict-like objects (Mapping) to the specified depth. >>> update_dict({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4}) == {'k1': {'k2': {'k3': 3}}, 'k4': 4} True >>> update_dict(OrderedDict([('k1', OrderedDict([('k2', 2)]))]), {'k1': {'k2': {'k3': 3}}, 'k4': 4}) ...
def update_dict(d, u=None, depth=-1, take_new=True, default_mapping_type=dict, prefer_update_type=False, copy=False): """ Recursively merge (union or update) dict-like objects (Mapping) to the specified depth. >>> update_dict({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4}) == {'k1': {'k2': {'k3': 3}...
Process a string to produce a valid python variable/class/type name Arguments: space (str): string to substitute for spaces ('' to delete all whitespace) camel (bool): whether to camel-case names, Django Model Name style (first letter capitalized) lower (bool): whether to lowercase all strings ...
def make_name(s, camel=None, lower=None, space='_', remove_prefix=None, language='python', string_type=str): """Process a string to produce a valid python variable/class/type name Arguments: space (str): string to substitute for spaces ('' to delete all whitespace) camel (bool): whether to camel-ca...
r"""Process string to remove any characters not allowed by the language specified (default: MSDOS) In addition, optionally replace spaces with the indicated "space" character (to make the path useful in a copy-paste without quoting). Uses the following regular expression to substitute spaces for invalid c...
def make_filename(s, space=None, language='msdos', strict=False, max_len=None, repeats=1024): r"""Process string to remove any characters not allowed by the language specified (default: MSDOS) In addition, optionally replace spaces with the indicated "space" character (to make the path useful in a copy-pas...
r"""Force the file or path str to end with the indicated extension Note: a dot (".") is assumed to delimit the extension >>> from __future__ import unicode_literals >>> update_file_ext('/home/hobs/extremofile', 'bac') '/home/hobs/extremofile.bac' >>> update_file_ext('/home/hobs/piano.file/', 'musi...
def update_file_ext(filename, ext='txt', sep='.'): r"""Force the file or path str to end with the indicated extension Note: a dot (".") is assumed to delimit the extension >>> from __future__ import unicode_literals >>> update_file_ext('/home/hobs/extremofile', 'bac') '/home/hobs/extremofile.bac' ...
Convert value to one of the desired_types specified (in order of preference) without raising an exception. If value is empty is a string and Falsey, then return the `empty` value specified. If value can't be converted to any of the desired_types requested, then return the `default` value specified. >>> tr...
def tryconvert(value, desired_types=SCALAR_TYPES, default=None, empty='', strip=True): """ Convert value to one of the desired_types specified (in order of preference) without raising an exception. If value is empty is a string and Falsey, then return the `empty` value specified. If value can't be conv...
Change encoding of text file
def transcode(infile, outfile=None, incoding="shift-jis", outcoding="utf-8"): """Change encoding of text file""" if not outfile: outfile = os.path.basename(infile) + '.utf8' with codecs.open(infile, "rb", incoding) as fpin: with codecs.open(outfile, "wb", outcoding) as fpout: fpo...
r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text so only the last element in a sequence is "stripped" >>> strip_br(' Title <BR> ') ' Title' >>> strip_br(list(ra...
def strip_br(s): r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text so only the last element in a sequence is "stripped" >>> strip_br(' Title <BR> ') ' Title' ...
r""" Read a csv file from a path or file pointer, returning a dict of lists, or list of lists (according to `format`) filename: a directory or list of file paths numbers: whether to attempt to convert strings in csv to numbers TODO: merge with `nlp.util.make_dataframe` function Handles un...
def read_csv(csv_file, ext='.csv', format=None, delete_empty_keys=False, fieldnames=[], rowlimit=100000000, numbers=False, normalize_names=True, unique_names=True, verbosity=0): r""" Read a csv file from a path or file pointer, returning a dict of lists, or list of lists (according to ...
Convert a dict to an object or namespace >>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} >>> obj = dict2obj(d) >>> obj.b.c 2 >>> obj.d ['hi', {'foo': 'bar'}] >>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]} >>> obj = dict2obj(d) >>> obj.d.hi.foo 'bar'
def dict2obj(d): """Convert a dict to an object or namespace >>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} >>> obj = dict2obj(d) >>> obj.b.c 2 >>> obj.d ['hi', {'foo': 'bar'}] >>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]} >>> obj = dict2obj(d) >>...
Coerce a provided array/sequence/generator into a pandas.Series object FIXME: Deal with CSR, COO, DOK and other sparse matrices like this: pd.Series(csr.toarray()[:,0]) or, if csr.shape[1] == 2 pd.Series(csr.toarray()[:,1], index=csr.toarray()[:,0]) >>> make_series(range(1, 4)) 0 1...
def make_series(x, *args, **kwargs): """Coerce a provided array/sequence/generator into a pandas.Series object FIXME: Deal with CSR, COO, DOK and other sparse matrices like this: pd.Series(csr.toarray()[:,0]) or, if csr.shape[1] == 2 pd.Series(csr.toarray()[:,1], index=csr.toarray()[:,0])...
r"""Encode all unicode/str objects in a dataframe in the encoding indicated (as a fun attribute) similar to to_ascii, but doesn't return a None, even when it fails. >>> encode(u'Is 2013 a year or a code point for "\u2013"?') b'Is 2013 a year or a code point for "\xe2\x80\x93"?' >>> print(u'Is 2013 a ye...
def encode(obj): r"""Encode all unicode/str objects in a dataframe in the encoding indicated (as a fun attribute) similar to to_ascii, but doesn't return a None, even when it fails. >>> encode(u'Is 2013 a year or a code point for "\u2013"?') b'Is 2013 a year or a code point for "\xe2\x80\x93"?' >>>...
Ensure all datetimes are valid Timestamp objects and dtype is np.datetime64[ns] >>> from datetime import timedelta >>> clean_series(pd.Series([datetime.datetime(1, 1, 1), 9, '1942', datetime.datetime(1970, 10, 23)])) 0 1677-09-22 00:12:44+00:00 1 9 2 ...
def clean_series(series, *args, **kwargs): """Ensure all datetimes are valid Timestamp objects and dtype is np.datetime64[ns] >>> from datetime import timedelta >>> clean_series(pd.Series([datetime.datetime(1, 1, 1), 9, '1942', datetime.datetime(1970, 10, 23)])) 0 1677-09-22 00:12:44+00:00 1 ...
Coerce a provided table (QuerySet, list of lists, list of Series) >>> dt = datetime.datetime >>> make_dataframe([[1,2,3],[4,5,6]]) 0 1 2 0 1 2 3 1 4 5 6 >>> make_dataframe([]) Empty DataFrame Columns: [] Index: [] >>> make_dataframe([OrderedDict([('a', 2), ('b', 3)]), ...
def make_dataframe(table, clean=True, verbose=False, **kwargs): """Coerce a provided table (QuerySet, list of lists, list of Series) >>> dt = datetime.datetime >>> make_dataframe([[1,2,3],[4,5,6]]) 0 1 2 0 1 2 3 1 4 5 6 >>> make_dataframe([]) Empty DataFrame Columns: [] ...
TODO: should probably assume a 2000 epoch for 2-digit dates >>> column_name_to_date('10-Apr') datetime.date(10, 4, 1) >>> column_name_to_date('10_2011') datetime.date(2011, 10, 1) >>> column_name_to_date('apr_10') datetime.date(10, 4, 1)
def column_name_to_date(name): """ TODO: should probably assume a 2000 epoch for 2-digit dates >>> column_name_to_date('10-Apr') datetime.date(10, 4, 1) >>> column_name_to_date('10_2011') datetime.date(2011, 10, 1) >>> column_name_to_date('apr_10') datetime.date(10, 4, 1) """ mo...
Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-). >>> first_digits('+123.456') 123
def first_digits(s, default=0): """Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-). >>> first_digits('+123.456') 123 """ s = re.split(r'[^0-9]+', str(s).strip().lstrip('+-' + charlist.whitespace)) if len(s) and len(s[0]): return int(s[0]) retur...