repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
scivision/gridaurora
gridaurora/__init__.py
chapman_profile
python
def chapman_profile(Z0: float, zKM: np.ndarray, H: float): return np.exp(.5*(1-(zKM-Z0)/H - np.exp((Z0-zKM)/H)))
Z0: altitude [km] of intensity peak zKM: altitude grid [km] H: scale height [km] example: pz = chapman_profile(110,np.arange(90,200,1),20)
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/__init__.py#L64-L73
null
from datetime import datetime, date from dateutil.parser import parse import numpy as np import logging from typing import Union def toyearmon(time: datetime) -> int: # %% date handle if isinstance(time, (tuple, list, np.ndarray)): logging.warning(f'taking only first time {time[0]}, would you like mul...
scivision/gridaurora
gridaurora/calcemissions.py
calcemissions
python
def calcemissions(rates: xarray.DataArray, sim) -> Tuple[xarray.DataArray, np.ndarray, np.ndarray]: if not sim.reacreq: return 0., 0., 0. ver = None lamb = None br = None # %% METASTABLE if 'metastable' in sim.reacreq: ver, lamb, br = getMetastable(rates, ver, lamb, br, sim.reaction...
Franck-Condon factor http://chemistry.illinoisstate.edu/standard/che460/handouts/460-Feb28lec-S13.pdf http://assign3.chem.usyd.edu.au/spectroscopy/index.php
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L20-L59
[ "def sortelimlambda(lamb, ver, br):\n assert lamb.ndim == 1\n assert lamb.size == ver.shape[-1]\n# %% eliminate unused wavelengths and Einstein coeff\n mask = np.isfinite(lamb)\n ver = ver[..., mask]\n lamb = lamb[mask]\n br = br[:, mask]\n# %% sort by lambda\n lambSortInd = lamb.argsort() # l...
#!/usr/bin/env python from pathlib import Path import numpy as np import h5py from typing import Tuple import xarray """ inputs: spec: excitation rates, 3-D , dimensions time x altitude x reaction output: ver: a pandas DataFrame, wavelength x altitude br: flux-tube integrated intensity, dimension lamb See Eqn 9 of A...
scivision/gridaurora
gridaurora/calcemissions.py
getMetastable
python
def getMetastable(rates, ver: np.ndarray, lamb, br, reactfn: Path): with h5py.File(reactfn, 'r') as f: A = f['/metastable/A'][:] lambnew = f['/metastable/lambda'].value.ravel(order='F') # some are not 1-D! vnew = np.concatenate((A[:2] * rates.loc[..., 'no1s'].values[:, None], ...
concatenate along the reaction dimension, axis=-1
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L62-L76
[ "def catvl(z, ver, vnew, lamb, lambnew, br):\n \"\"\"\n trapz integrates over altitude axis, axis = -2\n concatenate over reaction dimension, axis = -1\n\n br: column integrated brightness\n lamb: wavelength [nm]\n ver: volume emission rate [photons / cm^-3 s^-3 ...]\n \"\"\"\n if ver is no...
#!/usr/bin/env python from pathlib import Path import numpy as np import h5py from typing import Tuple import xarray """ inputs: spec: excitation rates, 3-D , dimensions time x altitude x reaction output: ver: a pandas DataFrame, wavelength x altitude br: flux-tube integrated intensity, dimension lamb See Eqn 9 of A...
scivision/gridaurora
gridaurora/calcemissions.py
getAtomic
python
def getAtomic(rates, ver, lamb, br, reactfn): with h5py.File(reactfn, 'r') as f: lambnew = f['/atomic/lambda'].value.ravel(order='F') # some are not 1-D! vnew = np.concatenate((rates.loc[..., 'po3p3p'].values[..., None], rates.loc[..., 'po3p5p'].values[..., None]), axis=-1) ...
prompt atomic emissions (nm) 844.6 777.4
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L79-L89
[ "def catvl(z, ver, vnew, lamb, lambnew, br):\n \"\"\"\n trapz integrates over altitude axis, axis = -2\n concatenate over reaction dimension, axis = -1\n\n br: column integrated brightness\n lamb: wavelength [nm]\n ver: volume emission rate [photons / cm^-3 s^-3 ...]\n \"\"\"\n if ver is no...
#!/usr/bin/env python from pathlib import Path import numpy as np import h5py from typing import Tuple import xarray """ inputs: spec: excitation rates, 3-D , dimensions time x altitude x reaction output: ver: a pandas DataFrame, wavelength x altitude br: flux-tube integrated intensity, dimension lamb See Eqn 9 of A...
scivision/gridaurora
gridaurora/calcemissions.py
getN21NG
python
def getN21NG(rates, ver, lamb, br, reactfn): with h5py.File(str(reactfn), 'r', libver='latest') as f: A = f['/N2+1NG/A'].value lambdaA = f['/N2+1NG/lambda'].value.ravel(order='F') franckcondon = f['/N2+1NG/fc'].value return doBandTrapz(A, lambdaA, franckcondon, rates.loc[..., 'p1ng'], l...
excitation Franck-Condon factors (derived from Vallance Jones, 1974)
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L92-L101
[ "def doBandTrapz(Aein, lambnew, fc, kin, lamb, ver, z, br):\n \"\"\"\n ver dimensions: wavelength, altitude, time\n\n A and lambda dimensions:\n axis 0 is upper state vib. level (nu')\n axis 1 is bottom state vib level (nu'')\n there is a Franck-Condon parameter (variable fc) for each upper state...
#!/usr/bin/env python from pathlib import Path import numpy as np import h5py from typing import Tuple import xarray """ inputs: spec: excitation rates, 3-D , dimensions time x altitude x reaction output: ver: a pandas DataFrame, wavelength x altitude br: flux-tube integrated intensity, dimension lamb See Eqn 9 of A...
scivision/gridaurora
gridaurora/calcemissions.py
getN21PG
python
def getN21PG(rates, ver, lamb, br, reactfn): with h5py.File(str(reactfn), 'r', libver='latest') as fid: A = fid['/N2_1PG/A'].value lambnew = fid['/N2_1PG/lambda'].value.ravel(order='F') franckcondon = fid['/N2_1PG/fc'].value tau1PG = 1 / np.nansum(A, axis=1) consfac = franckcondon...
solve for base concentration confac=[1.66;1.56;1.31;1.07;.77;.5;.33;.17;.08;.04;.02;.004;.001]; %Cartwright, 1973b, stop at nuprime==12 Gattinger and Vallance Jones 1974 confac=array([1.66,1.86,1.57,1.07,.76,.45,.25,.14,.07,.03,.01,.004,.001])
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L125-L148
[ "def catvl(z, ver, vnew, lamb, lambnew, br):\n \"\"\"\n trapz integrates over altitude axis, axis = -2\n concatenate over reaction dimension, axis = -1\n\n br: column integrated brightness\n lamb: wavelength [nm]\n ver: volume emission rate [photons / cm^-3 s^-3 ...]\n \"\"\"\n if ver is no...
#!/usr/bin/env python from pathlib import Path import numpy as np import h5py from typing import Tuple import xarray """ inputs: spec: excitation rates, 3-D , dimensions time x altitude x reaction output: ver: a pandas DataFrame, wavelength x altitude br: flux-tube integrated intensity, dimension lamb See Eqn 9 of A...
scivision/gridaurora
gridaurora/calcemissions.py
doBandTrapz
python
def doBandTrapz(Aein, lambnew, fc, kin, lamb, ver, z, br): tau = 1/np.nansum(Aein, axis=1) scalevec = (Aein * tau[:, None] * fc[:, None]).ravel(order='F') vnew = scalevec[None, None, :]*kin.values[..., None] return catvl(z, ver, vnew, lamb, lambnew, br)
ver dimensions: wavelength, altitude, time A and lambda dimensions: axis 0 is upper state vib. level (nu') axis 1 is bottom state vib level (nu'') there is a Franck-Condon parameter (variable fc) for each upper state nu'
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L151-L166
[ "def catvl(z, ver, vnew, lamb, lambnew, br):\n \"\"\"\n trapz integrates over altitude axis, axis = -2\n concatenate over reaction dimension, axis = -1\n\n br: column integrated brightness\n lamb: wavelength [nm]\n ver: volume emission rate [photons / cm^-3 s^-3 ...]\n \"\"\"\n if ver is no...
#!/usr/bin/env python from pathlib import Path import numpy as np import h5py from typing import Tuple import xarray """ inputs: spec: excitation rates, 3-D , dimensions time x altitude x reaction output: ver: a pandas DataFrame, wavelength x altitude br: flux-tube integrated intensity, dimension lamb See Eqn 9 of A...
scivision/gridaurora
gridaurora/calcemissions.py
catvl
python
def catvl(z, ver, vnew, lamb, lambnew, br): if ver is not None: br = np.concatenate((br, np.trapz(vnew, z, axis=-2)), axis=-1) # must come first! ver = np.concatenate((ver, vnew), axis=-1) lamb = np.concatenate((lamb, lambnew)) else: ver = vnew.copy(order='F') lamb = lam...
trapz integrates over altitude axis, axis = -2 concatenate over reaction dimension, axis = -1 br: column integrated brightness lamb: wavelength [nm] ver: volume emission rate [photons / cm^-3 s^-3 ...]
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L169-L187
null
#!/usr/bin/env python from pathlib import Path import numpy as np import h5py from typing import Tuple import xarray """ inputs: spec: excitation rates, 3-D , dimensions time x altitude x reaction output: ver: a pandas DataFrame, wavelength x altitude br: flux-tube integrated intensity, dimension lamb See Eqn 9 of A...
scivision/gridaurora
gridaurora/solarangle.py
solarzenithangle
python
def solarzenithangle(time: datetime, glat: float, glon: float, alt_m: float) -> tuple: time = totime(time) obs = EarthLocation(lat=glat*u.deg, lon=glon*u.deg, height=alt_m*u.m) times = Time(time, scale='ut1') sun = get_sun(times) sunobs = sun.transform_to(AltAz(obstime=times, location=obs)) re...
Input: t: scalar or array of datetime
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/solarangle.py#L8-L21
[ "def totime(time: Union[str, datetime, np.datetime64]) -> np.ndarray:\n time = np.atleast_1d(time)\n\n if isinstance(time[0], (datetime, np.datetime64)):\n pass\n elif isinstance(time[0], str):\n time = np.atleast_1d(list(map(parse, time)))\n\n return time.squeeze()[()]\n" ]
from datetime import datetime import astropy.units as u from astropy.coordinates import get_sun, EarthLocation, AltAz from astropy.time import Time from . import totime
scivision/gridaurora
gridaurora/eFluxGen.py
maxwellian
python
def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]: E0 = np.atleast_1d(E0) Q0 = np.atleast_1d(Q0) assert E0.ndim == Q0.ndim == 1 assert (Q0.size == 1 or Q0.size == E0.size) Phi = Q0/(2*pi*E0**3) * E[:, None] * np.exp(-E[:, None]/E0) Q = np.trapz(Phi, E, a...
input: ------ E: 1-D vector of energy bins [eV] E0: characteristic energy (scalar or vector) [eV] Q0: flux coefficient (scalar or vector) (to yield overall flux Q) output: ------- Phi: differential number flux Q: total flux Tanaka 2006 Eqn. 1 http://odin.gi.alaska.edu/lumm/Pape...
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/eFluxGen.py#L14-L39
null
""" Michael Hirsch based on Strickland 1993 """ import logging from pathlib import Path import numpy as np import h5py from typing import Tuple pi = np.pi def fluxgen(E, E0, Q0, Wbc, bl, bm, bh, Bm, Bhf, verbose: int = 0) -> tuple: Wb = Wbc*E0 isimE0 = abs(E - E0).argmin() base = gaussflux(E, Wb, E...
scivision/gridaurora
gridaurora/eFluxGen.py
hitail
python
def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray, Bhf: np.ndarray, bh: float, verbose: int = 0): Bh = np.empty_like(E0) for iE0 in np.arange(E0.size): Bh[iE0] = Bhf[iE0]*diffnumflux[isimE0[iE0], iE0] # 4100. # bh = 4 #2.9 het = B...
strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/eFluxGen.py#L90-L103
null
""" Michael Hirsch based on Strickland 1993 """ import logging from pathlib import Path import numpy as np import h5py from typing import Tuple pi = np.pi def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]: """ input: ------ E: 1-D vector of energy bins [eV] ...
scivision/gridaurora
gridaurora/plots.py
plotOptMod
python
def plotOptMod(verNObg3gray, VERgray): if VERgray is None and verNObg3gray is None: return fg = figure() ax2 = fg.gca() # summed (as camera would see) if VERgray is not None: z = VERgray.alt_km Ek = VERgray.energy_ev.values # ax1.semilogx(VERgray, z, marker='',label='f...
called from either readTranscar.py or hist-feasibility/plotsnew.py
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/plots.py#L260-L331
null
import logging from datetime import datetime from pathlib import Path import h5py import xarray from numpy.ma import masked_invalid # for pcolormesh, which doesn't like NaN from matplotlib.pyplot import figure, draw, close from matplotlib.colors import LogNorm from matplotlib.ticker import MultipleLocator from matplot...
scivision/gridaurora
gridaurora/opticalmod.py
opticalModel
python
def opticalModel(sim, ver: xarray.DataArray, obsAlt_km: float, zenithang: float): assert isinstance(ver, xarray.DataArray) # %% get system optical transmission T optT = getSystemT(ver.wavelength_nm, sim.bg3fn, sim.windowfn, sim.qefn, obsAlt_km, zenithang) # %% first multiply VER by T, THEN sum overall wavelengt...
ver: Nalt x Nwavelength
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/opticalmod.py#L7-L25
[ "def getSystemT(newLambda, bg3fn: Path, windfn: Path, qefn: Path,\n obsalt_km, zenang_deg, verbose: bool = False) -> xarray.Dataset:\n\n bg3fn = Path(bg3fn).expanduser()\n windfn = Path(windfn).expanduser()\n qefn = Path(qefn).expanduser()\n\n newLambda = np.asarray(newLambda)\n# %% atmosp...
#!/usr/bin/env python import logging import xarray from .filterload import getSystemT
scivision/gridaurora
MakeIonoEigenprofile.py
main
python
def main(): p = ArgumentParser(description='Makes unit flux eV^-1 as input to GLOW or Transcar to create ionospheric eigenprofiles') p.add_argument('-i', '--inputgridfn', help='original Zettergren input flux grid to base off of', default='zettflux.csv') p.add_argument('-o', '--outfn', help='hdf5 file to wri...
three output eigenprofiles 1) ver (optical emissions) 4-D array: time x energy x altitude x wavelength 2) prates (production) 4-D array: time x energy x altitude x reaction 3) lrates (loss) 4-D array: time x energy x altitude x reaction
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/MakeIonoEigenprofile.py#L35-L112
[ "def ploteigver(EKpcolor, zKM, eigenprofile,\n vlim=(None,)*6, sim=None, tInd=None, makeplot=None, prefix=None, progms=None):\n try:\n fg = figure()\n ax = fg.gca()\n # pcolormesh canNOT handle nan at all\n pcm = ax.pcolormesh(EKpcolor, zKM, masked_invalid(eigenprofile),...
#!/usr/bin/env python """ Computes Eigenprofiles of Ionospheric response to flux tube input via the following steps: 1. Generate unit input differential number flux vs. energy 2. Compute ionospheric energy deposition and hence production/loss rates for the modeled kinetic chemistries (12 in total) unverified for prope...
scivision/gridaurora
gridaurora/ztanh.py
setupz
python
def setupz(Np: int, zmin: float, gridmin: float, gridmax: float) -> np.ndarray: dz = _ztanh(Np, gridmin, gridmax) return np.insert(np.cumsum(dz)+zmin, 0, zmin)[:-1]
np: number of grid points zmin: minimum STEP SIZE at minimum grid altitude [km] gridmin: minimum altitude of grid [km] gridmax: maximum altitude of grid [km]
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/ztanh.py#L9-L19
[ "def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray:\n \"\"\"\n typically call via setupz instead\n \"\"\"\n x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote\n return np.tanh(x0)*gridmax+gridmin\n" ]
#!/usr/bin/env python """ inspired by Matt Zettergren Michael Hirsch """ import numpy as np def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray: """ typically call via setupz instead """ x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote ...
scivision/gridaurora
gridaurora/ztanh.py
_ztanh
python
def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray: x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote return np.tanh(x0)*gridmax+gridmin
typically call via setupz instead
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/ztanh.py#L22-L27
null
#!/usr/bin/env python """ inspired by Matt Zettergren Michael Hirsch """ import numpy as np def setupz(Np: int, zmin: float, gridmin: float, gridmax: float) -> np.ndarray: """ np: number of grid points zmin: minimum STEP SIZE at minimum grid altitude [km] gridmin: minimum altitude of grid [km] gri...
jacebrowning/comparable
comparable/tools.py
match_similar
python
def match_similar(base, items): finds = list(find_similar(base, items)) if finds: return max(finds, key=base.similarity) # TODO: make O(n) return None
Get the most similar matching item from a list of items. @param base: base item to locate best match @param items: list of items for comparison @return: most similar matching item or None
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/tools.py#L40-L52
[ "def find_similar(base, items):\n \"\"\"Get an iterator of items similar to the base.\n\n @param base: base item to locate best match\n @param items: list of items for comparison\n @return: generator of similar items\n\n \"\"\"\n return (item for item in items if base.similarity(item))\n" ]
"""Functions to utilize lists of Comparable objects.""" def find_equal(base, items): """Get an iterator of items equal to the base. @param base: base item to find equality @param items: list of items for comparison @return: generator of equal items """ return (item for item in items if base....
jacebrowning/comparable
comparable/tools.py
duplicates
python
def duplicates(base, items): for item in items: if item.similarity(base) and not item.equality(base): yield item
Get an iterator of items similar but not equal to the base. @param base: base item to perform comparison against @param items: list of items to compare to the base @return: generator of items sorted by similarity to the base
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/tools.py#L55-L65
null
"""Functions to utilize lists of Comparable objects.""" def find_equal(base, items): """Get an iterator of items equal to the base. @param base: base item to find equality @param items: list of items for comparison @return: generator of equal items """ return (item for item in items if base....
jacebrowning/comparable
comparable/tools.py
sort
python
def sort(base, items): return sorted(items, key=base.similarity, reverse=True)
Get a sorted list of items ranked in descending similarity. @param base: base item to perform comparison against @param items: list of items to compare to the base @return: list of items sorted by similarity to the base
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/tools.py#L68-L76
null
"""Functions to utilize lists of Comparable objects.""" def find_equal(base, items): """Get an iterator of items equal to the base. @param base: base item to find equality @param items: list of items for comparison @return: generator of equal items """ return (item for item in items if base....
jacebrowning/comparable
comparable/simple.py
Number.similarity
python
def similarity(self, other): numerator, denominator = sorted((self.value, other.value)) try: ratio = float(numerator) / denominator except ZeroDivisionError: ratio = 0.0 if numerator else 1.0 similarity = self.Similarity(ratio) return similarity
Get similarity as a ratio of the two numbers.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/simple.py#L44-L52
[ "def Similarity(self, value=None): # pylint: disable=C0103\n \"\"\"Constructor for new default Similarities.\"\"\"\n if value is None:\n value = 0.0\n return Similarity(value, threshold=self.threshold)\n" ]
class Number(_Simple): """Comparable positive number.""" threshold = 0.999 # 99.9% similar def __init__(self, value): super().__init__(value) if value < 0: raise ValueError("Number objects can only be positive") def equality(self, other): """Get equality using fl...
jacebrowning/comparable
comparable/simple.py
Text.similarity
python
def similarity(self, other): ratio = SequenceMatcher(a=self.value, b=other.value).ratio() similarity = self.Similarity(ratio) return similarity
Get similarity as a ratio of the two texts.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/simple.py#L65-L69
[ "def Similarity(self, value=None): # pylint: disable=C0103\n \"\"\"Constructor for new default Similarities.\"\"\"\n if value is None:\n value = 0.0\n return Similarity(value, threshold=self.threshold)\n" ]
class Text(_Simple): """Comparable generic text.""" threshold = 0.83 # "Hello, world!" ~ "hello world" def equality(self, other): """Get equality using string comparison.""" return str(self) == str(other)
jacebrowning/comparable
comparable/simple.py
TextEnum.similarity
python
def similarity(self, other): ratio = 1.0 if (str(self).lower() == str(other).lower()) else 0.0 similarity = self.Similarity(ratio) return similarity
Get similarity as a discrete ratio (1.0 or 0.0).
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/simple.py#L78-L82
[ "def Similarity(self, value=None): # pylint: disable=C0103\n \"\"\"Constructor for new default Similarities.\"\"\"\n if value is None:\n value = 0.0\n return Similarity(value, threshold=self.threshold)\n" ]
class TextEnum(Text): """Comparable case-insensitive textual enumeration.""" threshold = 1.0 # enumerations must match
jacebrowning/comparable
comparable/simple.py
TextTitle._strip
python
def _strip(text): text = text.strip() text = text.replace(' ', ' ') # remove duplicate spaces text = text.lower() for joiner in TextTitle.JOINERS: text = text.replace(joiner, 'and') for article in TextTitle.ARTICLES: if text.startswith(article + ' '): ...
Strip articles/whitespace and remove case.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/simple.py#L100-L111
null
class TextTitle(Text): """Comparable case-insensitive textual titles.""" threshold = 0.93 # "The Cat and the Hat" ~ "cat an' the hat" ARTICLES = 'a', 'an', 'the' # stripped from the front JOINERS = '&', '+' # replaced with 'and' def __init__(self, value): super().__init__(value) ...
jacebrowning/comparable
comparable/simple.py
TextTitle.similarity
python
def similarity(self, other): logging.debug("comparing %r and %r...", self.stripped, other.stripped) ratio = SequenceMatcher(a=self.stripped, b=other.stripped).ratio() similarity = self.Similarity(ratio) return similarity
Get similarity as a ratio of the stripped text.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/simple.py#L113-L118
[ "def Similarity(self, value=None): # pylint: disable=C0103\n \"\"\"Constructor for new default Similarities.\"\"\"\n if value is None:\n value = 0.0\n return Similarity(value, threshold=self.threshold)\n" ]
class TextTitle(Text): """Comparable case-insensitive textual titles.""" threshold = 0.93 # "The Cat and the Hat" ~ "cat an' the hat" ARTICLES = 'a', 'an', 'the' # stripped from the front JOINERS = '&', '+' # replaced with 'and' def __init__(self, value): super().__init__(value) ...
jacebrowning/comparable
comparable/base.py
equal
python
def equal(obj1, obj2): Comparable.log(obj1, obj2, '==') equality = obj1.equality(obj2) Comparable.log(obj1, obj2, '==', result=equality) return equality
Calculate equality between two (Comparable) objects.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/base.py#L127-L132
[ "def equality(self, other):\n \"\"\"Compare two objects for equality.\n\n @param self: first object to compare\n @param other: second object to compare\n\n @return: boolean result of comparison\n\n \"\"\"\n # Compare specified attributes for equality\n cname = self.__class__.__name__\n for a...
"""Abstract base class and similarity functions.""" import logging from collections import OrderedDict from abc import ABCMeta, abstractmethod, abstractproperty # pylint: disable=W0611 class _Base(object): # pylint: disable=R0903 """Shared base class.""" def _repr(self, *args, **kwargs): """Retur...
jacebrowning/comparable
comparable/base.py
similar
python
def similar(obj1, obj2): Comparable.log(obj1, obj2, '%') similarity = obj1.similarity(obj2) Comparable.log(obj1, obj2, '%', result=similarity) return similarity
Calculate similarity between two (Comparable) objects.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/base.py#L135-L140
[ "def similarity(self, other):\n \"\"\"Compare two objects for similarity.\n\n @param self: first object to compare\n @param other: second object to compare\n\n @return: L{Similarity} result of comparison\n\n \"\"\"\n sim = self.Similarity()\n total = 0.0\n\n # Calculate similarity ratio for ...
"""Abstract base class and similarity functions.""" import logging from collections import OrderedDict from abc import ABCMeta, abstractmethod, abstractproperty # pylint: disable=W0611 class _Base(object): # pylint: disable=R0903 """Shared base class.""" def _repr(self, *args, **kwargs): """Retur...
jacebrowning/comparable
comparable/base.py
_Base._repr
python
def _repr(self, *args, **kwargs): # Remove unnecessary empty keywords arguments and sort the arguments kwargs = {k: v for k, v in kwargs.items() if v is not None} kwargs = OrderedDict(sorted(kwargs.items())) # Build the __repr__ string pieces args_repr = ', '.join(repr(arg) for ...
Return a __repr__ string from the arguments provided to __init__. @param args: list of arguments to __init__ @param kwargs: dictionary of keyword arguments to __init__ @return: __repr__ string
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/base.py#L12-L31
null
class _Base(object): # pylint: disable=R0903 """Shared base class."""
jacebrowning/comparable
comparable/base.py
Comparable.equality
python
def equality(self, other): # Compare specified attributes for equality cname = self.__class__.__name__ for aname in self.attributes: try: attr1 = getattr(self, aname) attr2 = getattr(other, aname) except AttributeError as error: ...
Compare two objects for equality. @param self: first object to compare @param other: second object to compare @return: boolean result of comparison
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/base.py#L179-L203
[ "def log(obj1, obj2, sym, cname=None, aname=None, result=None): # pylint: disable=R0913\n \"\"\"Log the objects being compared and the result.\n\n When no result object is specified, subsequence calls will have an\n increased indentation level. The indentation level is decreased\n once a result object ...
class Comparable(_Base, metaclass=ABCMeta): """Abstract Base Class for objects that are comparable. Subclasses directly comparable must override the 'equality' and 'similarity' methods to return a bool and 'Similarity' object, respectively. Subclasses comparable by attributes must override the ...
jacebrowning/comparable
comparable/base.py
Comparable.similarity
python
def similarity(self, other): sim = self.Similarity() total = 0.0 # Calculate similarity ratio for each attribute cname = self.__class__.__name__ for aname, weight in self.attributes.items(): attr1 = getattr(self, aname, None) attr2 = getattr(other, aname...
Compare two objects for similarity. @param self: first object to compare @param other: second object to compare @return: L{Similarity} result of comparison
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/base.py#L206-L253
[ "def Similarity(self, value=None): # pylint: disable=C0103\n \"\"\"Constructor for new default Similarities.\"\"\"\n if value is None:\n value = 0.0\n return Similarity(value, threshold=self.threshold)\n", "def log(obj1, obj2, sym, cname=None, aname=None, result=None): # pylint: disable=R0913\n ...
class Comparable(_Base, metaclass=ABCMeta): """Abstract Base Class for objects that are comparable. Subclasses directly comparable must override the 'equality' and 'similarity' methods to return a bool and 'Similarity' object, respectively. Subclasses comparable by attributes must override the ...
jacebrowning/comparable
comparable/base.py
Comparable.Similarity
python
def Similarity(self, value=None): # pylint: disable=C0103 if value is None: value = 0.0 return Similarity(value, threshold=self.threshold)
Constructor for new default Similarities.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/base.py#L255-L259
null
class Comparable(_Base, metaclass=ABCMeta): """Abstract Base Class for objects that are comparable. Subclasses directly comparable must override the 'equality' and 'similarity' methods to return a bool and 'Similarity' object, respectively. Subclasses comparable by attributes must override the ...
jacebrowning/comparable
comparable/base.py
Comparable.log
python
def log(obj1, obj2, sym, cname=None, aname=None, result=None): # pylint: disable=R0913 fmt = "{o1} {sym} {o2} : {r}" if cname or aname: assert cname and aname # both must be specified fmt = "{c}.{a}: " + fmt if result is None: result = '...' fmt...
Log the objects being compared and the result. When no result object is specified, subsequence calls will have an increased indentation level. The indentation level is decreased once a result object is provided. @param obj1: first object @param obj2: second object @para...
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/base.py#L262-L292
[ "def more(cls):\n \"\"\"Increase the indent level.\"\"\"\n cls.level += 1\n", "def less(cls):\n \"\"\"Decrease the indent level.\"\"\"\n cls.level = max(cls.level - 1, 0)\n", "def indent(cls, fmt):\n \"\"\"Get a new format string with indentation.\"\"\"\n return '| ' * cls.level + fmt\n" ]
class Comparable(_Base, metaclass=ABCMeta): """Abstract Base Class for objects that are comparable. Subclasses directly comparable must override the 'equality' and 'similarity' methods to return a bool and 'Similarity' object, respectively. Subclasses comparable by attributes must override the ...
jacebrowning/comparable
comparable/compound.py
Group.equality
python
def equality(self, other): if not len(self) == len(other): return False return super().equality(other)
Calculate equality based on equality of all group items.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/compound.py#L42-L46
[ "def equality(self, other):\n \"\"\"A compound comparable's equality is based on attributes.\"\"\"\n return super().equality(other)\n" ]
class Group(CompoundComparable): # pylint: disable=W0223 """Comparable list of Comparable items.""" attributes = None # created dynamically def __init__(self, items): self.items = items names = ("item{0}".format(n + 1) for n in range(len(items))) self.attributes = {name: 1 for n...
jacebrowning/comparable
comparable/compound.py
Group.similarity
python
def similarity(self, other): # Select the longer list as the basis for comparison if len(self.items) > len(other.items): first, second = self, other else: first, second = other, self items = list(first.items) # backup items list length = len(items) ...
Calculate similarity based on best matching permutation of items.
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/compound.py#L48-L75
[ "def Similarity(self, value=None): # pylint: disable=C0103\n \"\"\"Constructor for new default Similarities.\"\"\"\n if value is None:\n value = 0.0\n return Similarity(value, threshold=self.threshold)\n", "def log(obj1, obj2, sym, cname=None, aname=None, result=None): # pylint: disable=R0913\n ...
class Group(CompoundComparable): # pylint: disable=W0223 """Comparable list of Comparable items.""" attributes = None # created dynamically def __init__(self, items): self.items = items names = ("item{0}".format(n + 1) for n in range(len(items))) self.attributes = {name: 1 for n...
timothydmorton/simpledist
simpledist/distributions.py
double_lorgauss
python
def double_lorgauss(x,p): mu,sig1,sig2,gam1,gam2,G1,G2 = p gam1 = float(gam1) gam2 = float(gam2) G1 = abs(G1) G2 = abs(G2) sig1 = abs(sig1) sig2 = abs(sig2) gam1 = abs(gam1) gab2 = abs(gam2) L2 = (gam1/(gam1 + gam2)) * ((gam2*np.pi*G1)/(sig1*np.sqrt(2*np.pi)) - ...
Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian. Parameters ---------- x : float or array-like Value(s) at which to evaluate distribution p : array-like Input parameters: mu (mode of distribution), s...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L615-L664
null
from __future__ import absolute_import, division, print_function __author__ = 'Timothy D. Morton <tim.morton@gmail.com>' """ Defines objects useful for describing probability distributions. """ import numpy as np import matplotlib.pyplot as plt import logging from scipy.interpolate import UnivariateSpline as interpol...
timothydmorton/simpledist
simpledist/distributions.py
fit_double_lorgauss
python
def fit_double_lorgauss(bins,h,Ntry=5): try: from lmfit import minimize, Parameters, Parameter, report_fit except ImportError: raise ImportError('you need lmfit to use this function.') #make sure histogram is normalized h /= np.trapz(h,bins) #zero-pad the ends of the distri...
Uses lmfit to fit a "Double LorGauss" distribution to a provided histogram. Uses a grid of starting guesses to try to avoid local minima. Parameters ---------- bins, h : array-like Bins and heights of a histogram, as returned by, e.g., `np.histogram`. Ntry : int, optional Spacing ...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L666-L754
[ "def double_lorgauss(x,p):\n \"\"\"Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian.\n\n Parameters\n ----------\n x : float or array-like\n Value(s) at which to evaluate distribution\n\n p : array-like\n Input parameters: mu (...
from __future__ import absolute_import, division, print_function __author__ = 'Timothy D. Morton <tim.morton@gmail.com>' """ Defines objects useful for describing probability distributions. """ import numpy as np import matplotlib.pyplot as plt import logging from scipy.interpolate import UnivariateSpline as interpol...
timothydmorton/simpledist
simpledist/distributions.py
doublegauss
python
def doublegauss(x,p): mu,sig1,sig2 = p x = np.atleast_1d(x) A = 1./(np.sqrt(2*np.pi)*(sig1+sig2)/2.) ylo = A*np.exp(-(x-mu)**2/(2*sig1**2)) yhi = A*np.exp(-(x-mu)**2/(2*sig2**2)) y = x*0 wlo = np.where(x < mu) whi = np.where(x >= mu) y[wlo] = ylo[wlo] y[whi] = yhi[whi] if np....
Evaluates normalized two-sided Gaussian distribution Parameters ---------- x : float or array-like Value(s) at which to evaluate distribution p : array-like Parameters of distribution: (mu: mode of distribution, sig1: LH width, ...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L792-L824
null
from __future__ import absolute_import, division, print_function __author__ = 'Timothy D. Morton <tim.morton@gmail.com>' """ Defines objects useful for describing probability distributions. """ import numpy as np import matplotlib.pyplot as plt import logging from scipy.interpolate import UnivariateSpline as interpol...
timothydmorton/simpledist
simpledist/distributions.py
doublegauss_cdf
python
def doublegauss_cdf(x,p): x = np.atleast_1d(x) mu,sig1,sig2 = p sig1 = np.absolute(sig1) sig2 = np.absolute(sig2) ylo = float(sig1)/(sig1 + sig2)*(1 + erf((x-mu)/np.sqrt(2*sig1**2))) yhi = float(sig1)/(sig1 + sig2) + float(sig2)/(sig1+sig2)*(erf((x-mu)/np.sqrt(2*sig2**2))) lo = x < mu hi...
Cumulative distribution function for two-sided Gaussian Parameters ---------- x : float Input values at which to calculate CDF. p : array-like Parameters of distribution: (mu: mode of distribution, sig1: LH width, ...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L826-L847
null
from __future__ import absolute_import, division, print_function __author__ = 'Timothy D. Morton <tim.morton@gmail.com>' """ Defines objects useful for describing probability distributions. """ import numpy as np import matplotlib.pyplot as plt import logging from scipy.interpolate import UnivariateSpline as interpol...
timothydmorton/simpledist
simpledist/distributions.py
fit_doublegauss_samples
python
def fit_doublegauss_samples(samples,**kwargs): sorted_samples = np.sort(samples) N = len(samples) med = sorted_samples[N/2] siglo = med - sorted_samples[int(0.16*N)] sighi = sorted_samples[int(0.84*N)] - med return fit_doublegauss(med,siglo,sighi,median=True,**kwargs)
Fits a two-sided Gaussian to a set of samples. Calculates 0.16, 0.5, and 0.84 quantiles and passes these to `fit_doublegauss` for fitting. Parameters ---------- samples : array-like Samples to which to fit the Gaussian. kwargs Keyword arguments passed to `fit_doublegauss`.
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L849-L868
[ "def fit_doublegauss(med,siglo,sighi,interval=0.683,p0=None,median=False,return_distribution=True):\n \"\"\"Fits a two-sided Gaussian distribution to match a given confidence interval.\n\n The center of the distribution may be either the median or the mode.\n\n Parameters\n ----------\n med : float\n...
from __future__ import absolute_import, division, print_function __author__ = 'Timothy D. Morton <tim.morton@gmail.com>' """ Defines objects useful for describing probability distributions. """ import numpy as np import matplotlib.pyplot as plt import logging from scipy.interpolate import UnivariateSpline as interpol...
timothydmorton/simpledist
simpledist/distributions.py
fit_doublegauss
python
def fit_doublegauss(med,siglo,sighi,interval=0.683,p0=None,median=False,return_distribution=True): if median: q1 = 0.5 - (interval/2) q2 = 0.5 + (interval/2) targetvals = np.array([med-siglo,med,med+sighi]) qvals = np.array([q1,0.5,q2]) def objfn(pars): logging.de...
Fits a two-sided Gaussian distribution to match a given confidence interval. The center of the distribution may be either the median or the mode. Parameters ---------- med : float The center of the distribution to which to fit. Default this will be the mode unless the `median` keyword...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L871-L937
null
from __future__ import absolute_import, division, print_function __author__ = 'Timothy D. Morton <tim.morton@gmail.com>' """ Defines objects useful for describing probability distributions. """ import numpy as np import matplotlib.pyplot as plt import logging from scipy.interpolate import UnivariateSpline as interpol...
timothydmorton/simpledist
simpledist/distributions.py
Distribution.pctile
python
def pctile(self,pct,res=1000): grid = np.linspace(self.minval,self.maxval,res) return grid[np.argmin(np.absolute(pct-self.cdf(grid)))]
Returns the desired percentile of the distribution. Will only work if properly normalized. Designed to mimic the `ppf` method of the `scipy.stats` random variate objects. Works by gridding the CDF at a given resolution and matching the nearest point. NB, this is of course not as preci...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L136-L158
[ "def cdf(x):\n x = np.atleast_1d(x)\n y = np.atleast_1d(cdf_fn(x))\n y[np.where(x < self.minval)] = 0\n y[np.where(x > self.maxval)] = 1\n return y\n" ]
class Distribution(object): """Base class to describe probability distribution. Has some minimal functional overlap with scipy.stats random variates (e.g. `ppf`, `rvs`) Parameters ---------- pdf : callable The probability density function to be used. Does not have to be normal...
timothydmorton/simpledist
simpledist/distributions.py
Distribution.save_hdf
python
def save_hdf(self,filename,path='',res=1000,logspace=False): if logspace: vals = np.logspace(np.log10(self.minval), np.log10(self.maxval), res) else: vals = np.linspace(self.minval,self.maxval,res) d = {'vals':...
Saves distribution to an HDF5 file. Saves a pandas `dataframe` object containing tabulated pdf and cdf values at a specfied resolution. After saving to a particular path, a distribution may be regenerated using the `Distribution_FromH5` subclass. Parameters ---------- ...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L162-L206
[ "def cdf(x):\n x = np.atleast_1d(x)\n y = np.atleast_1d(cdf_fn(x))\n y[np.where(x < self.minval)] = 0\n y[np.where(x > self.maxval)] = 1\n return y\n" ]
class Distribution(object): """Base class to describe probability distribution. Has some minimal functional overlap with scipy.stats random variates (e.g. `ppf`, `rvs`) Parameters ---------- pdf : callable The probability density function to be used. Does not have to be normal...
timothydmorton/simpledist
simpledist/distributions.py
Distribution.plot
python
def plot(self,minval=None,maxval=None,fig=None,log=False, npts=500,**kwargs): if minval is None: minval = self.minval if maxval is None: maxval = self.maxval if maxval==np.inf or minval==-np.inf: raise ValueError('must have finite upper and lower ...
Plots distribution. Parameters ---------- minval : float,optional minimum value to plot. Required if minval of Distribution is `-np.inf`. maxval : float, optional maximum value to plot. Required if maxval of Distribution is `np.inf`. ...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L244-L294
null
class Distribution(object): """Base class to describe probability distribution. Has some minimal functional overlap with scipy.stats random variates (e.g. `ppf`, `rvs`) Parameters ---------- pdf : callable The probability density function to be used. Does not have to be normal...
timothydmorton/simpledist
simpledist/distributions.py
Distribution.resample
python
def resample(self,N,minval=None,maxval=None,log=False,res=1e4): N = int(N) if minval is None: if hasattr(self,'minval_cdf'): minval = self.minval_cdf else: minval = self.minval if maxval is None: if hasattr(self,'maxval_cdf'): ...
Returns random samples generated according to the distribution Mirrors basic functionality of `rvs` method for `scipy.stats` random variates. Implemented by mapping uniform numbers onto the inverse CDF using a closest-matching grid approach. Parameters ---------- N : i...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L296-L357
[ "def cdf(x):\n x = np.atleast_1d(x)\n y = np.atleast_1d(cdf_fn(x))\n y[np.where(x < self.minval)] = 0\n y[np.where(x > self.maxval)] = 1\n return y\n" ]
class Distribution(object): """Base class to describe probability distribution. Has some minimal functional overlap with scipy.stats random variates (e.g. `ppf`, `rvs`) Parameters ---------- pdf : callable The probability density function to be used. Does not have to be normal...
timothydmorton/simpledist
simpledist/distributions.py
Hist_Distribution.plothist
python
def plothist(self,fig=None,**kwargs): setfig(fig) plt.hist(self.samples,bins=self.bins,**kwargs)
Plots a histogram of samples using provided bins. Parameters ---------- fig : None or int Parameter passed to `setfig`. kwargs Keyword arguments passed to `plt.hist`.
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L548-L560
null
class Hist_Distribution(Distribution): """Generates a distribution from a histogram of provided samples. Uses `np.histogram` to create a histogram using the bins keyword, then interpolates this histogram to create the pdf to pass to the `Distribution` constructor. Parameters ---------- sam...
timothydmorton/simpledist
simpledist/distributions.py
Hist_Distribution.resample
python
def resample(self,N): inds = rand.randint(len(self.samples),size=N) return self.samples[inds]
Returns a bootstrap resampling of provided samples. Parameters ---------- N : int Number of samples.
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L562-L571
null
class Hist_Distribution(Distribution): """Generates a distribution from a histogram of provided samples. Uses `np.histogram` to create a histogram using the bins keyword, then interpolates this histogram to create the pdf to pass to the `Distribution` constructor. Parameters ---------- sam...
timothydmorton/simpledist
simpledist/distributions.py
Box_Distribution.resample
python
def resample(self,N): return rand.random(size=N)*(self.maxval - self.minval) + self.minval
Returns a random sampling.
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L606-L609
null
class Box_Distribution(Distribution): """Simple distribution uniform between provided lower and upper limits. Parameters ---------- lo,hi : float Lower/upper limits of the distribution. kwargs Keyword arguments passed to `Distribution` constructor. """ def __init__(self,lo...
timothydmorton/simpledist
simpledist/distributions.py
DoubleGauss_Distribution.resample
python
def resample(self,N,**kwargs): lovals = self.mu - np.absolute(rand.normal(size=N)*self.siglo) hivals = self.mu + np.absolute(rand.normal(size=N)*self.sighi) u = rand.random(size=N) hi = (u < float(self.sighi)/(self.sighi + self.siglo)) lo = (u >= float(self.sighi)/(self.sighi + ...
Random resampling of the doublegauss distribution
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L982-L995
null
class DoubleGauss_Distribution(Distribution): """A Distribution oject representing a two-sided Gaussian distribution This can be used to represent a slightly asymmetric distribution, and consists of two half-Normal distributions patched together at the mode, and normalized appropriately. The pdf and c...
timothydmorton/simpledist
simpledist/kde.py
deriv
python
def deriv(f,c,dx=0.0001): return (f(c+dx)-f(c-dx))/(2*dx)
deriv(f,c,dx) --> float Returns f'(x), computed as a symmetric difference quotient.
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/kde.py#L224-L230
null
from __future__ import absolute_import, division, print_function import numpy as np from scipy.stats import gaussian_kde import numpy.random as rand from scipy.integrate import quad class KDE(object): """An implementation of a kernel density estimator allowing for adaptive kernels. If the `adaptive` keyword i...
timothydmorton/simpledist
simpledist/kde.py
newton
python
def newton(f,c,tol=0.0001,restrict=None): #print(c) if restrict: lo,hi = restrict if c < lo or c > hi: print(c) c = random*(hi-lo)+lo if fuzzyequals(f(c),0,tol): return c else: try: return newton(f,c-f(c)/deriv(f,c,tol),tol,restrict) ...
newton(f,c) --> float Returns the x closest to c such that f(x) = 0
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/kde.py#L235-L254
[ "def newton(f,c,tol=0.0001,restrict=None):\n \"\"\"\n newton(f,c) --> float\n\n Returns the x closest to c such that f(x) = 0\n \"\"\"\n #print(c)\n if restrict:\n lo,hi = restrict\n if c < lo or c > hi:\n print(c)\n c = random*(hi-lo)+lo\n\n if fuzzyequals(f...
from __future__ import absolute_import, division, print_function import numpy as np from scipy.stats import gaussian_kde import numpy.random as rand from scipy.integrate import quad class KDE(object): """An implementation of a kernel density estimator allowing for adaptive kernels. If the `adaptive` keyword i...
timothydmorton/simpledist
simpledist/kde.py
KDE.integrate_box
python
def integrate_box(self,low,high,forcequad=False,**kwargs): if not self.adaptive and not forcequad: return self.gauss_kde.integrate_box_1d(low,high)*self.norm return quad(self.evaluate,low,high,**kwargs)[0]
Integrates over a box. Optionally force quad integration, even for non-adaptive. If adaptive mode is not being used, this will just call the `scipy.stats.gaussian_kde` method `integrate_box_1d`. Else, by default, it will call `scipy.integrate.quad`. If the `forcequad` flag is turned o...
train
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/kde.py#L131-L156
null
class KDE(object): """An implementation of a kernel density estimator allowing for adaptive kernels. If the `adaptive` keyword is set to `False`, then this will essentially be just a wrapper for the `scipy.stats.gaussian_kde` class. If adaptive, though, it allows for different kernels and different ke...
ttm/socialLegacy
social/twiter.py
Twitter.searchTag
python
def searchTag(self,HTAG="#arenaNETmundial"): search = t.search(q=HTAG,count=100,result_type="recent") ss=search[:] search = t.search(q=HTAG,count=150,max_id=ss[-1]['id']-1,result_type="recent") #search = t.search(q=HTAG,count=150,since_id=ss[-1]['id'],result_type="recent") while ...
Set Twitter search or stream criteria for the selection of tweets
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/twiter.py#L24-L32
null
class Twitter: """Simplified Twitter interface for Stability observance # function to set authentication: __init__() # function to set hashtag and other tweets selection criteria: searchTag() # function to search tweets: searchTag() # function to stream tweets: void """ def __init__(self,ap...
ttm/socialLegacy
social/utils.py
makeRetweetNetwork
python
def makeRetweetNetwork(tweets): G=x.DiGraph() G_=x.DiGraph() for tweet in tweets: text=tweet["text"] us=tweet["user"]["screen_name"] if text.startswith("RT @"): prev_us=text.split(":")[0].split("@")[1] #print(us,prev_us,text) if G.has_edge(prev_us,...
Receives tweets, returns directed retweet networks. Without and with isolated nodes.
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/utils.py#L2-L23
null
import networkx as x def makeRetweetNetwork(tweets): """Receives tweets, returns directed retweet networks. Without and with isolated nodes. """ G=x.DiGraph() G_=x.DiGraph() for tweet in tweets: text=tweet["text"] us=tweet["user"]["screen_name"] if text.startswith("RT @"...
ttm/socialLegacy
social/utils.py
GDFgraph.makeNetwork
python
def makeNetwork(self): if "weight" in self.data_friendships.keys(): self.G=G=x.DiGraph() else: self.G=G=x.Graph() F=self.data_friends for friendn in range(self.n_friends): if "posts" in F.keys(): G.add_node(F["name"][friendn], ...
Makes graph object from .gdf loaded data
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/utils.py#L57-L85
null
class GDFgraph: """Read GDF graph into networkX""" def __init__(self,filename="../data/RenatoFabbri06022014.gdf"): with open(filename,"r") as f: self.data=f.read() self.lines=self.data.split("\n") columns=self.lines[0].split(">")[1].split(",") column_names=[i.split(" ...
ttm/socialLegacy
social/fb/gml2rdf.py
triplifyGML
python
def triplifyGML(dpath="../data/fb/",fname="foo.gdf",fnamei="foo_interaction.gdf", fpath="./fb/",scriptpath=None,uid=None,sid=None,fb_link=None,ego=True,umbrella_dir=None): c("iniciado tripgml") if sum(c.isdigit() for c in fname)==4: year=re.findall(r".*(\d\d\d\d).gml",fname)[0][0] B.date...
Produce a linked data publication tree from a standard GML file. INPUTS: ====== => the data directory path => the file name (fname) of the friendship network => the file name (fnamei) of the interaction network => the final path (fpath) for the tree of files to be created => a path to the s...
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fb/gml2rdf.py#L4-L67
[ "def rdfFriendshipNetwork(fnet):\n tg=P.rdf.makeBasicGraph([[\"po\",\"fb\"],[P.rdf.ns.per,P.rdf.ns.fb]],\"Facebook friendship network from {} . Ego: {}\".format(B.name,B.ego))\n #if sum([(\"user\" in i) for i in fnet[\"individuals\"][\"label\"]])==len(fnet[\"individuals\"][\"label\"]):\n # # nomes falso...
import percolation as P, social as S, rdflib as r, builtins as B, re, datetime, os, shutil c=P.utils.check def trans(tkey): if tkey=="name": return "numericID" if tkey=="label": return "name" return tkey def rdfInteractionNetwork(fnet): tg=P.rdf.makeBasicGraph([["po","fb"],[P.rdf.ns...
ttm/socialLegacy
social/fb/fb.py
triplifyGML
python
def triplifyGML(fname="foo.gml",fpath="./fb/",scriptpath=None,uid=None,sid=None,extra_info=None): # aname=fname.split("/")[-1].split(".")[0] aname=fname.split("/")[-1].split(".")[0] if "RonaldCosta" in fname: aname=fname.split("/")[-1].split(".")[0] name,day,month,year=re.findall(".*/([a-zA-...
Produce a linked data publication tree from a standard GML file. INPUTS: => the file name (fname, with path) where the gdf file of the friendship network is. => the final path (fpath) for the tree of files to be created. => a path to the script that is calling this function (scriptpath). ...
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fb/fb.py#L11-L167
null
import time, os, pickle, shutil, datetime, re import networkx as x, rdflib as r from splinter import Browser from bs4 import BeautifulSoup import percolation as P c=P.utils.check this_dir = os.path.split(__file__)[0] NS=P.rdf.ns a=NS.rdf.type def triplifyGML(fname="foo.gml",fpath="./fb/",scriptpath=None,uid=None,sid=N...
ttm/socialLegacy
social/fb/fb.py
triplifyGDFInteraction
python
def triplifyGDFInteraction(fname="foo.gdf",fpath="./fb/",scriptpath=None,uid=None,sid=None,dlink=None): #aname=fname.split("/")[-1].split(".")[0]+"_fb" aname=fname.split("/")[-1].split(".")[0] if re.findall("[a-zA-Z]*_[0-9]",fname): name,year,month,day,hour,minute=re.findall(".*/([a-zA-Z]*).*(\d\d\d...
Produce a linked data publication tree from GDF files of a Facebook interaction network. INPUTS: => the file name (fname, with path) where the gdf file of the friendship network is. => the final path (fpath) for the tree of files to be created. => a path to the script that is calling this fun...
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fb/fb.py#L170-L326
[ "def readGDF(filename=\"../data/RenatoFabbri06022014.gdf\"):\n \"\"\"Made to work with my own network. Check file to ease adaptation\"\"\"\n with open(filename,\"r\") as f:\n data=f.read()\n lines=data.split(\"\\n\")\n columns=lines[0].split(\">\")[1].split(\",\")\n column_names=[i.split(\" \"...
import time, os, pickle, shutil, datetime, re import networkx as x, rdflib as r from splinter import Browser from bs4 import BeautifulSoup import percolation as P c=P.utils.check this_dir = os.path.split(__file__)[0] NS=P.rdf.ns a=NS.rdf.type def triplifyGML(fname="foo.gml",fpath="./fb/",scriptpath=None,uid=None,sid=N...
ttm/socialLegacy
social/fb/fb.py
ScrapyBrowser.getFriends
python
def getFriends(self,user_id="astronauta.mecanico",write=True): while user_id not in self.browser.url: self.browser.visit("http://www.facebook.com/{}/friends".format(user_id), wait_time=3) #self.go("http://www.facebook.com/{}/friends".format(user_id)) T=time.time() while 1: ...
Returns user_ids (that you have access) of the friends of your friend with user_ids
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fb/fb.py#L611-L655
null
class ScrapyBrowser: """Opens a browser for user to login to facebook. Such browser pulls data as requested by user.""" def __init__(self,user_email=None, user_password=None,basedir="~/.social/"): self._BASE_DIR=basedir.replace("~",os.path.expanduser("~")) if not os.path.isdir(self._BASE_DI...
ttm/socialLegacy
social/fb/read.py
readGDF
python
def readGDF(filename="../data/RenatoFabbri06022014.gdf"): with open(filename,"r") as f: data=f.read() lines=data.split("\n") columns=lines[0].split(">")[1].split(",") column_names=[i.split(" ")[0] for i in columns] data_friends={cn:[] for cn in column_names} for line in lines[1:]: ...
Made to work with gdf files from my own network and friends and groups
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fb/read.py#L164-L192
null
import networkx as x, percolation as P, re c=P.utils.check def readGML2(filename="../data/RenatoFabbri06022014.gml"): with open(filename,"r") as f: data=f.read() lines=data.split("\n") nodes=[] # list of dicts, each a node edges=[] # list of tuples state="receive" for line in lines: ...
ttm/socialLegacy
social/tw.py
Twitter.searchTag
python
def searchTag(self,HTAG="#python"): self.t = Twython(app_key =self.app_key , app_secret =self.app_secret , oauth_token =self.oauth_token , oauth_token_secret =self.oauth_token_secret) ...
Set Twitter search or stream criteria for the selection of tweets
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/tw.py#L293-L307
null
class Twitter: """Simplified Twitter interface for Stability observance # function to set authentication: __init__() # function to set hashtag and other tweets selection criteria: searchTag() # function to search tweets: searchTag() # function to stream tweets: void """ TWITTER_API_KEY ...
ttm/socialLegacy
social/fsong.py
FSong.makePartitions
python
def makePartitions(self): class NetworkMeasures: pass self.nm=nm=NetworkMeasures() nm.degrees=self.network.degree() nm.nodes_= sorted(self.network.nodes(), key=lambda x : nm.degrees[x]) nm.degrees_=[nm.degrees[i] for i in nm.nodes_] nm.edges= self.network....
Make partitions with gmane help.
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L29-L41
null
class FSong: """Create song from undirected (friendship) network """ def __init__(self, network,basedir="fsong/",clean=False,render_images=False,render_images2=False,make_video=False): os.system("mkdir {}".format(basedir)) if clean: os.system("rm {}*".format(basedir)) sel...
ttm/socialLegacy
social/fsong.py
FSong.makeImages
python
def makeImages(self): # make layout self.makeLayout() self.setAgraph() # make function that accepts a mode, a sector # and nodes and edges True and False self.plotGraph() self.plotGraph("reversed",filename="tgraphR.png") agents=n.concatenate(self.np.sector...
Make spiral images in sectors and steps. Plain, reversed, sectorialized, negative sectorialized outline, outline reversed, lonely only nodes, only edges, both
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L42-L63
[ "def plotGraph(self,mode=\"plain\",nodes=None,filename=\"tgraph.png\"):\n \"\"\"Plot graph with nodes (iterable) into filename\n \"\"\"\n if nodes==None:\n nodes=self.nodes\n else:\n nodes=[i for i in self.nodes if i in nodes]\n for node in self.nodes:\n n_=self.A.get_node(node)\...
class FSong: """Create song from undirected (friendship) network """ def __init__(self, network,basedir="fsong/",clean=False,render_images=False,render_images2=False,make_video=False): os.system("mkdir {}".format(basedir)) if clean: os.system("rm {}*".format(basedir)) sel...
ttm/socialLegacy
social/fsong.py
FSong.plotGraph
python
def plotGraph(self,mode="plain",nodes=None,filename="tgraph.png"): if nodes==None: nodes=self.nodes else: nodes=[i for i in self.nodes if i in nodes] for node in self.nodes: n_=self.A.get_node(node) if mode=="plain": nmode=1 ...
Plot graph with nodes (iterable) into filename
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L72-L109
null
class FSong: """Create song from undirected (friendship) network """ def __init__(self, network,basedir="fsong/",clean=False,render_images=False,render_images2=False,make_video=False): os.system("mkdir {}".format(basedir)) if clean: os.system("rm {}*".format(basedir)) sel...
ttm/socialLegacy
social/fsong.py
FSong.makeSong
python
def makeSong(self): self.makeVisualSong() self.makeAudibleSong() if self.make_video: self.makeAnimation()
Render abstract animation
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L127-L133
[ "def makeVisualSong(self):\n \"\"\"Return a sequence of images and durations.\n \"\"\"\n self.files=os.listdir(self.basedir)\n self.stairs=[i for i in self.files if (\"stair\" in i) and (\"R\" in i)]\n self.sectors=[i for i in self.files if \"sector\" in i]\n self.stairs.sort()\n self.sectors.s...
class FSong: """Create song from undirected (friendship) network """ def __init__(self, network,basedir="fsong/",clean=False,render_images=False,render_images2=False,make_video=False): os.system("mkdir {}".format(basedir)) if clean: os.system("rm {}*".format(basedir)) sel...
ttm/socialLegacy
social/fsong.py
FSong.makeVisualSong
python
def makeVisualSong(self): self.files=os.listdir(self.basedir) self.stairs=[i for i in self.files if ("stair" in i) and ("R" in i)] self.sectors=[i for i in self.files if "sector" in i] self.stairs.sort() self.sectors.sort() filenames=[self.basedir+i for i in self.sectors[...
Return a sequence of images and durations.
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L134-L188
null
class FSong: """Create song from undirected (friendship) network """ def __init__(self, network,basedir="fsong/",clean=False,render_images=False,render_images2=False,make_video=False): os.system("mkdir {}".format(basedir)) if clean: os.system("rm {}*".format(basedir)) sel...
ttm/socialLegacy
social/fsong.py
FSong.makeAudibleSong
python
def makeAudibleSong(self): sound0=n.hstack((sy.render(220,d=1.5), sy.render(220*(2**(7/12)),d=2.5), sy.render(220*(2**(-5/12)),d=.5), sy.render(220*(2**(0/12)),d=1.5), )) sound1=n.hstack((sy.render(220*(2**(0...
Use mass to render wav soundtrack.
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L194-L239
null
class FSong: """Create song from undirected (friendship) network """ def __init__(self, network,basedir="fsong/",clean=False,render_images=False,render_images2=False,make_video=False): os.system("mkdir {}".format(basedir)) if clean: os.system("rm {}*".format(basedir)) sel...
ttm/socialLegacy
social/fsong.py
FSong.makeAnimation
python
def makeAnimation(self): aclip=mpy.AudioFileClip("sound.wav") self.iS=self.iS.set_audio(aclip) self.iS.write_videofile("mixedVideo.webm",15,audio=True) print("wrote "+"mixedVideo.webm")
Use pymovie to render (visual+audio)+text overlays.
train
https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/fsong.py#L240-L246
null
class FSong: """Create song from undirected (friendship) network """ def __init__(self, network,basedir="fsong/",clean=False,render_images=False,render_images2=False,make_video=False): os.system("mkdir {}".format(basedir)) if clean: os.system("rm {}*".format(basedir)) sel...
harlowja/failure
failure/finders.py
match_modules
python
def match_modules(allowed_modules): cleaned_allowed_modules = [ utils.mod_to_mod_name(tmp_mod) for tmp_mod in allowed_modules ] cleaned_split_allowed_modules = [ tmp_mod.split(".") for tmp_mod in cleaned_allowed_modules ] cleaned_allowed_modules = [] del cleaned_a...
Creates a matcher that matches a list/set/tuple of allowed modules.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/finders.py#L44-L73
null
# -*- coding: utf-8 -*- # Copyright (C) 2016 GoDaddy Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
harlowja/failure
failure/finders.py
match_classes
python
def match_classes(allowed_classes): cleaned_allowed_classes = [ utils.cls_to_cls_name(tmp_cls) for tmp_cls in allowed_classes ] def matcher(cause): cause_cls = None cause_type_name = cause.exception_type_names[0] try: cause_cls_idx = cleaned_allowed_class...
Creates a matcher that matches a list/tuple of allowed classes.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/finders.py#L76-L97
null
# -*- coding: utf-8 -*- # Copyright (C) 2016 GoDaddy Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
harlowja/failure
failure/finders.py
combine_or
python
def combine_or(matcher, *more_matchers): def matcher(cause): for sub_matcher in itertools.chain([matcher], more_matchers): cause_cls = sub_matcher(cause) if cause_cls is not None: return cause_cls return None return matcher
Combines more than one matcher together (first that matches wins).
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/finders.py#L100-L110
null
# -*- coding: utf-8 -*- # Copyright (C) 2016 GoDaddy Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
harlowja/failure
failure/failure.py
WrappedFailure.check
python
def check(self, *exc_classes): if not exc_classes: return None for cause in self: result = cause.check(*exc_classes) if result is not None: return result return None
Check if any of exception classes caused the failure/s. :param exc_classes: exception types/exception type names to search for. If any of the contained failures were caused by an exception of a given type, the corresponding argument that matched is returned. If ...
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L77-L93
null
class WrappedFailure(utils.StrMixin, Exception): """Wraps one or several failure objects. When exception/s cannot be re-raised (for example, because the value and traceback are lost in serialization) or there are several exceptions active at the same time (due to more than one thread raising exceptions...
harlowja/failure
failure/failure.py
Failure.from_exc_info
python
def from_exc_info(cls, exc_info=None, retain_exc_info=True, cause=None, find_cause=True): if exc_info is None: exc_info = sys.exc_info() if not any(exc_info): raise NoActiveException("No exception currently" ...
Creates a failure object from a ``sys.exc_info()`` tuple.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L241-L291
[ "def extract_roots(exc_type):\n return to_tuple(\n reflection.get_all_class_names(exc_type, up_to=BaseException,\n truncate_builtins=False))\n", "def _extract_cause(cls, exc_val):\n \"\"\"Helper routine to extract nested cause (if any).\"\"\"\n # See: https://...
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.from_exception
python
def from_exception(cls, exception, retain_exc_info=True, cause=None, find_cause=True): exc_info = ( type(exception), exception, getattr(exception, '__traceback__', None) ) return cls.from_exc_info(exc_info=exc_info, ...
Creates a failure object from a exception instance.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L294-L304
[ "def from_exc_info(cls, exc_info=None,\n retain_exc_info=True,\n cause=None, find_cause=True):\n \"\"\"Creates a failure object from a ``sys.exc_info()`` tuple.\"\"\"\n if exc_info is None:\n exc_info = sys.exc_info()\n if not any(exc_info):\n raise N...
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.validate
python
def validate(cls, data): try: jsonschema.validate( data, cls.SCHEMA, # See: https://github.com/Julian/jsonschema/issues/148 types={'array': (list, tuple)}) except jsonschema.ValidationError as e: raise InvalidFormat("Failure data no...
Validate input data matches expected failure ``dict`` format.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L307-L338
null
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.matches
python
def matches(self, other): if not isinstance(other, Failure): return False if self.exc_info is None or other.exc_info is None: return self._matches(other) else: return self == other
Checks if another object is equivalent to this object. :returns: checks if another object is equivalent to this object :rtype: boolean
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L351-L362
[ "def _matches(self, other):\n if self is other:\n return True\n return (self.exception_type_names == other.exception_type_names and\n self.exception_args == other.exception_args and\n self.exception_kwargs == other.exception_kwargs and\n self.exception_str == other.exce...
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.reraise_if_any
python
def reraise_if_any(failures, cause_cls_finder=None): if not isinstance(failures, (list, tuple)): # Convert generators/other into a list... failures = list(failures) if len(failures) == 1: failures[0].reraise(cause_cls_finder=cause_cls_finder) elif len(failures...
Re-raise exceptions if argument is not empty. If argument is empty list/tuple/iterator, this method returns None. If argument is converted into a list with a single ``Failure`` object in it, that failure is reraised. Else, a :class:`~.WrappedFailure` exception is raised with the failure...
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L436-L451
null
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.reraise
python
def reraise(self, cause_cls_finder=None): if self._exc_info: six.reraise(*self._exc_info) else: # Attempt to regenerate the full chain (and then raise # from the root); without a traceback, oh well... root = None parent = None for c...
Re-raise captured exception (possibly trying to recreate).
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L453-L482
[ "def iter_causes(self):\n \"\"\"Iterate over all causes.\"\"\"\n curr = self._cause\n while curr is not None:\n yield curr\n curr = curr._cause\n" ]
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.check
python
def check(self, *exc_classes): for cls in exc_classes: cls_name = utils.cls_to_cls_name(cls) if cls_name in self._exc_type_names: return cls return None
Check if any of ``exc_classes`` caused the failure. Arguments of this method can be exception types or type names (strings **fully qualified**). If captured exception is an instance of exception of given type, the corresponding argument is returned, otherwise ``None`` is returned.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L484-L496
[ "def cls_to_cls_name(cls):\n if isinstance(cls, type):\n cls_name = reflection.get_class_name(cls, truncate_builtins=False)\n else:\n cls_name = str(cls)\n return cls_name\n" ]
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.pformat
python
def pformat(self, traceback=False): buf = six.StringIO() if not self._exc_type_names: buf.write('Failure: %s' % (self._exception_str)) else: buf.write('Failure: %s: %s' % (self._exc_type_names[0], self._exception_str)) if...
Pretty formats the failure object into a string.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L513-L532
null
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.iter_causes
python
def iter_causes(self): curr = self._cause while curr is not None: yield curr curr = curr._cause
Iterate over all causes.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L534-L539
null
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure._extract_cause
python
def _extract_cause(cls, exc_val): # See: https://www.python.org/dev/peps/pep-3134/ for why/what # these are... # # '__cause__' attribute for explicitly chained exceptions # '__context__' attribute for implicitly chained exceptions # '__traceback__' attribute for the trace...
Helper routine to extract nested cause (if any).
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L584-L620
null
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.from_dict
python
def from_dict(cls, data): data = dict(data) cause = data.get('cause') if cause is not None: data['cause'] = cls.from_dict(cause) return cls(**data)
Converts this from a dictionary to a object.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L623-L629
[ "def from_dict(cls, data):\n \"\"\"Converts this from a dictionary to a object.\"\"\"\n data = dict(data)\n cause = data.get('cause')\n if cause is not None:\n data['cause'] = cls.from_dict(cause)\n return cls(**data)\n" ]
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.to_dict
python
def to_dict(self, include_args=True, include_kwargs=True): data = { 'exception_str': self.exception_str, 'traceback_str': self.traceback_str, 'exc_type_names': self.exception_type_names, 'exc_args': self.exception_args if include_args else tuple(), 'ex...
Converts this object to a dictionary. :param include_args: boolean indicating whether to include the exception args in the output. :param include_kwargs: boolean indicating whether to include the exception kwargs in the output.
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L631-L650
null
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
harlowja/failure
failure/failure.py
Failure.copy
python
def copy(self, deep=False): cause = self._cause if cause is not None: cause = cause.copy(deep=deep) exc_info = utils.copy_exc_info(self.exc_info, deep=deep) exc_args = self.exception_args exc_kwargs = self.exception_kwargs if deep: exc_args = copy....
Copies this object (shallow or deep). :param deep: boolean indicating whether to do a deep copy (or a shallow copy).
train
https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L652-L684
[ "def copy_exc_info(exc_info, deep=False):\n if exc_info is None:\n return None\n exc_type, exc_value, exc_tb = exc_info\n # NOTE(imelnikov): there is no need to copy the exception type, and\n # a shallow copy of the value is fine and we can't copy the traceback since\n # it contains reference ...
class Failure(utils.StrMixin): """An immutable object that represents failure. Failure objects encapsulate exception information so that they can be re-used later to re-raise, inspect, examine, log, print, serialize, deserialize... For those who are curious, here are a few reasons why the original...
ambitioninc/django-entity-event
entity_event/context_loader.py
get_context_hints_per_source
python
def get_context_hints_per_source(context_renderers): # Merge the context render hints for each source as there can be multiple context hints for # sources depending on the render target. Merging them together involves combining select # and prefetch related hints for each context renderer context_hints_...
Given a list of context renderers, return a dictionary of context hints per source.
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_loader.py#L21-L42
null
""" A module for loading contexts using context hints. """ from collections import defaultdict import six from django.conf import settings from django.db.models import Q try: # Django 1.9 from django.apps import apps get_model = apps.get_model except ImportError: # pragma: no cover # Django < 1.9 ...
ambitioninc/django-entity-event
entity_event/context_loader.py
get_querysets_for_context_hints
python
def get_querysets_for_context_hints(context_hints_per_source): model_select_relateds = defaultdict(set) model_prefetch_relateds = defaultdict(set) model_querysets = {} for context_hints in context_hints_per_source.values(): for hints in context_hints.values(): model = get_model(hints...
Given a list of context hint dictionaries, return a dictionary of querysets for efficient context loading. The return value is structured as follows: { model: queryset, ... }
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_loader.py#L45-L74
null
""" A module for loading contexts using context hints. """ from collections import defaultdict import six from django.conf import settings from django.db.models import Q try: # Django 1.9 from django.apps import apps get_model = apps.get_model except ImportError: # pragma: no cover # Django < 1.9 ...
ambitioninc/django-entity-event
entity_event/context_loader.py
dict_find
python
def dict_find(d, which_key): # If the starting point is a list, iterate recursively over all values if isinstance(d, (list, tuple)): for i in d: for result in dict_find(i, which_key): yield result # Else, iterate over all key values of the dictionary elif isinstance(...
Finds key values in a nested dictionary. Returns a tuple of the dictionary in which the key was found along with the value
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_loader.py#L77-L94
[ "def dict_find(d, which_key):\n \"\"\"\n Finds key values in a nested dictionary. Returns a tuple of the dictionary in which\n the key was found along with the value\n \"\"\"\n # If the starting point is a list, iterate recursively over all values\n if isinstance(d, (list, tuple)):\n for i ...
""" A module for loading contexts using context hints. """ from collections import defaultdict import six from django.conf import settings from django.db.models import Q try: # Django 1.9 from django.apps import apps get_model = apps.get_model except ImportError: # pragma: no cover # Django < 1.9 ...
ambitioninc/django-entity-event
entity_event/context_loader.py
get_model_ids_to_fetch
python
def get_model_ids_to_fetch(events, context_hints_per_source): number_types = (complex, float) + six.integer_types model_ids_to_fetch = defaultdict(set) for event in events: context_hints = context_hints_per_source.get(event.source, {}) for context_key, hints in context_hints.items(): ...
Obtains the ids of all models that need to be fetched. Returns a dictionary of models that point to sets of ids that need to be fetched. Return output is as follows: { model: [id1, id2, ...], ... }
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_loader.py#L97-L119
[ "def dict_find(d, which_key):\n \"\"\"\n Finds key values in a nested dictionary. Returns a tuple of the dictionary in which\n the key was found along with the value\n \"\"\"\n # If the starting point is a list, iterate recursively over all values\n if isinstance(d, (list, tuple)):\n for i ...
""" A module for loading contexts using context hints. """ from collections import defaultdict import six from django.conf import settings from django.db.models import Q try: # Django 1.9 from django.apps import apps get_model = apps.get_model except ImportError: # pragma: no cover # Django < 1.9 ...
ambitioninc/django-entity-event
entity_event/context_loader.py
fetch_model_data
python
def fetch_model_data(model_querysets, model_ids_to_fetch): return { model: id_dict(model_querysets[model].filter(id__in=ids_to_fetch)) for model, ids_to_fetch in model_ids_to_fetch.items() }
Given a dictionary of models to querysets and model IDs to models, fetch the IDs for every model and return the objects in the following structure. { model: { id: obj, ... }, ... }
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_loader.py#L122-L138
null
""" A module for loading contexts using context hints. """ from collections import defaultdict import six from django.conf import settings from django.db.models import Q try: # Django 1.9 from django.apps import apps get_model = apps.get_model except ImportError: # pragma: no cover # Django < 1.9 ...
ambitioninc/django-entity-event
entity_event/context_loader.py
load_fetched_objects_into_contexts
python
def load_fetched_objects_into_contexts(events, model_data, context_hints_per_source): for event in events: context_hints = context_hints_per_source.get(event.source, {}) for context_key, hints in context_hints.items(): model = get_model(hints['app_name'], hints['model_name']) ...
Given the fetched model data and the context hints for each source, go through each event and populate the contexts with the loaded information.
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_loader.py#L141-L155
[ "def dict_find(d, which_key):\n \"\"\"\n Finds key values in a nested dictionary. Returns a tuple of the dictionary in which\n the key was found along with the value\n \"\"\"\n # If the starting point is a list, iterate recursively over all values\n if isinstance(d, (list, tuple)):\n for i ...
""" A module for loading contexts using context hints. """ from collections import defaultdict import six from django.conf import settings from django.db.models import Q try: # Django 1.9 from django.apps import apps get_model = apps.get_model except ImportError: # pragma: no cover # Django < 1.9 ...
ambitioninc/django-entity-event
entity_event/context_loader.py
load_renderers_into_events
python
def load_renderers_into_events(events, mediums, context_renderers, default_rendering_style): # Make a mapping of source groups and rendering styles to context renderers. Do # the same for sources and rendering styles to context renderers source_group_style_to_renderer = { (cr.source_group_id, cr.ren...
Given the events and the context renderers, load the renderers into the event objects so that they may be able to call the 'render' method later on.
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_loader.py#L158-L191
null
""" A module for loading contexts using context hints. """ from collections import defaultdict import six from django.conf import settings from django.db.models import Q try: # Django 1.9 from django.apps import apps get_model = apps.get_model except ImportError: # pragma: no cover # Django < 1.9 ...
ambitioninc/django-entity-event
entity_event/context_loader.py
load_contexts_and_renderers
python
def load_contexts_and_renderers(events, mediums): sources = {event.source for event in events} rendering_styles = {medium.rendering_style for medium in mediums if medium.rendering_style} # Fetch the default rendering style and add it to the set of rendering styles default_rendering_style = get_default_...
Given a list of events and mediums, load the context model data into the contexts of the events.
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_loader.py#L202-L226
[ "def get_context_hints_per_source(context_renderers):\n \"\"\"\n Given a list of context renderers, return a dictionary of context hints per source.\n \"\"\"\n # Merge the context render hints for each source as there can be multiple context hints for\n # sources depending on the render target. Mergi...
""" A module for loading contexts using context hints. """ from collections import defaultdict import six from django.conf import settings from django.db.models import Q try: # Django 1.9 from django.apps import apps get_model = apps.get_model except ImportError: # pragma: no cover # Django < 1.9 ...
ambitioninc/django-entity-event
entity_event/models.py
_unseen_event_ids
python
def _unseen_event_ids(medium): query = ''' SELECT event.id FROM entity_event_event AS event LEFT OUTER JOIN (SELECT * FROM entity_event_eventseen AS seen WHERE seen.medium_id=%s) AS eventseen ON event.id = eventseen.event_id WHERE eve...
Return all events that have not been seen on this medium.
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L1191-L1206
null
from collections import defaultdict from datetime import datetime from operator import or_ from six.moves import reduce from cached_property import cached_property from django.contrib.postgres.fields import JSONField from django.core.serializers.json import DjangoJSONEncoder from django.db import models, transaction f...
ambitioninc/django-entity-event
entity_event/models.py
EventQuerySet.mark_seen
python
def mark_seen(self, medium): EventSeen.objects.bulk_create([ EventSeen(event=event, medium=medium) for event in self ])
Creates EventSeen objects for the provided medium for every event in the queryset. Creating these EventSeen objects ensures they will not be returned when passing ``seen=False`` to any of the medium event retrieval functions, ``events``, ``entity_events``, or ``events_targets``.
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L866-L878
null
class EventQuerySet(QuerySet): """ A custom QuerySet for Events. """ def cache_related(self): """ Cache any related objects that we may use :return: """ return self.select_related( 'source' ).prefetch_related( 'source__group' ...
ambitioninc/django-entity-event
entity_event/models.py
EventManager.create_event
python
def create_event(self, actors=None, ignore_duplicates=False, **kwargs): kwargs['actors'] = actors kwargs['ignore_duplicates'] = ignore_duplicates events = self.create_events([kwargs]) if events: return events[0] return None
Create events with actors. This method can be used in place of ``Event.objects.create`` to create events, and the appropriate actors. It takes all the same keywords as ``Event.objects.create`` for the event creation, but additionally takes a list of actors, and can be told to no...
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L926-L988
[ "def create_events(self, kwargs_list):\n \"\"\"\n Create events in bulk to save on queries. Each element in the kwargs list should be a dict with the same set\n of arguments you would normally pass to create_event\n :param kwargs_list: list of kwargs dicts\n :return: list of Event\n \"\"\"\n # ...
class EventManager(models.Manager): """ A custom Manager for Events. """ def get_queryset(self): """ Return the EventQuerySet. """ return EventQuerySet(self.model) def cache_related(self): """ Return a queryset with prefetched values :return: ...
ambitioninc/django-entity-event
entity_event/models.py
EventManager.create_events
python
def create_events(self, kwargs_list): # Build map of uuid to event info uuid_map = { kwargs.get('uuid', ''): { 'actors': kwargs.pop('actors', []), 'ignore_duplicates': kwargs.pop('ignore_duplicates', False), 'event_kwargs': kwargs ...
Create events in bulk to save on queries. Each element in the kwargs list should be a dict with the same set of arguments you would normally pass to create_event :param kwargs_list: list of kwargs dicts :return: list of Event
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/models.py#L990-L1036
null
class EventManager(models.Manager): """ A custom Manager for Events. """ def get_queryset(self): """ Return the EventQuerySet. """ return EventQuerySet(self.model) def cache_related(self): """ Return a queryset with prefetched values :return: ...
ambitioninc/django-entity-event
entity_event/context_serializer.py
DefaultContextSerializer.serialize_value
python
def serialize_value(self, value): # Create a list of serialize methods to run the value through serialize_methods = [ self.serialize_model, self.serialize_json_string, self.serialize_list, self.serialize_dict ] # Run all of our serialize m...
Given a value, ensure that it is serialized properly :param value: :return:
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_serializer.py#L29-L48
null
class DefaultContextSerializer(object): """ Default class for serializing context data """ def __init__(self, context): super(DefaultContextSerializer, self).__init__() self.context = context @property def data(self): """ Data property that will return the seria...
ambitioninc/django-entity-event
entity_event/context_serializer.py
DefaultContextSerializer.serialize_model
python
def serialize_model(self, value): # Check if the context value is a model if not isinstance(value, models.Model): return value # Serialize the model serialized_model = model_to_dict(value) # Check the model for cached foreign keys for model_field, model_val...
Serializes a model and all of its prefetched foreign keys :param value: :return:
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_serializer.py#L50-L79
[ "def serialize_value(self, value):\n \"\"\"\n Given a value, ensure that it is serialized properly\n :param value:\n :return:\n \"\"\"\n # Create a list of serialize methods to run the value through\n serialize_methods = [\n self.serialize_model,\n self.serialize_json_string,\n ...
class DefaultContextSerializer(object): """ Default class for serializing context data """ def __init__(self, context): super(DefaultContextSerializer, self).__init__() self.context = context @property def data(self): """ Data property that will return the seria...
ambitioninc/django-entity-event
entity_event/context_serializer.py
DefaultContextSerializer.serialize_json_string
python
def serialize_json_string(self, value): # Check if the value might be a json string if not isinstance(value, six.string_types): return value # Make sure it starts with a brace if not value.startswith('{') or value.startswith('['): return value # Try to ...
Tries to load an encoded json string back into an object :param json_string: :return:
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_serializer.py#L81-L100
null
class DefaultContextSerializer(object): """ Default class for serializing context data """ def __init__(self, context): super(DefaultContextSerializer, self).__init__() self.context = context @property def data(self): """ Data property that will return the seria...
ambitioninc/django-entity-event
entity_event/context_serializer.py
DefaultContextSerializer.serialize_list
python
def serialize_list(self, value): # Check if this is a list or a tuple if not isinstance(value, (list, tuple)): return value # Loop over all the values and serialize the values return [ self.serialize_value(list_value) for list_value in value ...
Ensure that all values of a list or tuple are serialized :return:
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_serializer.py#L102-L116
null
class DefaultContextSerializer(object): """ Default class for serializing context data """ def __init__(self, context): super(DefaultContextSerializer, self).__init__() self.context = context @property def data(self): """ Data property that will return the seria...
ambitioninc/django-entity-event
entity_event/context_serializer.py
DefaultContextSerializer.serialize_dict
python
def serialize_dict(self, value): # Check if this is a dict if not isinstance(value, dict): return value # Loop over all the values and serialize them return { dict_key: self.serialize_value(dict_value) for dict_key, dict_value in value.items() ...
Ensure that all values of a dictionary are properly serialized :param value: :return:
train
https://github.com/ambitioninc/django-entity-event/blob/70f50df133e42a7bf38d0f07fccc6d2890e5fd12/entity_event/context_serializer.py#L118-L133
null
class DefaultContextSerializer(object): """ Default class for serializing context data """ def __init__(self, context): super(DefaultContextSerializer, self).__init__() self.context = context @property def data(self): """ Data property that will return the seria...