repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
bwohlberg/sporco
sporco/dictlrn/common.py
isxmap
def isxmap(xmethod, opt): """Return ``isxmap`` argument for ``.IterStatsConfig`` initialiser. """ if xmethod == 'admm': isx = {'XPrRsdl': 'PrimalRsdl', 'XDlRsdl': 'DualRsdl', 'XRho': 'Rho'} else: isx = {'X_F_Btrack': 'F_Btrack', 'X_Q_Btrack': 'Q_Btrack', 'X_ItBt': 'IterBTrack', 'X_L': 'L', 'X_Rsdl': 'Rsdl'} if not opt['AccurateDFid']: isx.update(evlmap(True)) return isx
python
def isxmap(xmethod, opt): """Return ``isxmap`` argument for ``.IterStatsConfig`` initialiser. """ if xmethod == 'admm': isx = {'XPrRsdl': 'PrimalRsdl', 'XDlRsdl': 'DualRsdl', 'XRho': 'Rho'} else: isx = {'X_F_Btrack': 'F_Btrack', 'X_Q_Btrack': 'Q_Btrack', 'X_ItBt': 'IterBTrack', 'X_L': 'L', 'X_Rsdl': 'Rsdl'} if not opt['AccurateDFid']: isx.update(evlmap(True)) return isx
[ "def", "isxmap", "(", "xmethod", ",", "opt", ")", ":", "if", "xmethod", "==", "'admm'", ":", "isx", "=", "{", "'XPrRsdl'", ":", "'PrimalRsdl'", ",", "'XDlRsdl'", ":", "'DualRsdl'", ",", "'XRho'", ":", "'Rho'", "}", "else", ":", "isx", "=", "{", "'X_F...
Return ``isxmap`` argument for ``.IterStatsConfig`` initialiser.
[ "Return", "isxmap", "argument", "for", ".", "IterStatsConfig", "initialiser", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/common.py#L32-L44
train
210,200
bwohlberg/sporco
sporco/dictlrn/common.py
isfld
def isfld(xmethod, dmethod, opt): """Return ``isfld`` argument for ``.IterStatsConfig`` initialiser. """ fld = ['Iter', 'ObjFun', 'DFid', 'RegL1', 'Cnstr'] if xmethod == 'admm': fld.extend(['XPrRsdl', 'XDlRsdl', 'XRho']) else: if opt['CBPDN', 'BackTrack', 'Enabled']: fld.extend(['X_F_Btrack', 'X_Q_Btrack', 'X_ItBt', 'X_L', 'X_Rsdl']) else: fld.extend(['X_L', 'X_Rsdl']) if dmethod != 'fista': fld.extend(['DPrRsdl', 'DDlRsdl', 'DRho']) else: if opt['CCMOD', 'BackTrack', 'Enabled']: fld.extend(['D_F_Btrack', 'D_Q_Btrack', 'D_ItBt', 'D_L', 'D_Rsdl']) else: fld.extend(['D_L', 'D_Rsdl']) fld.append('Time') return fld
python
def isfld(xmethod, dmethod, opt): """Return ``isfld`` argument for ``.IterStatsConfig`` initialiser. """ fld = ['Iter', 'ObjFun', 'DFid', 'RegL1', 'Cnstr'] if xmethod == 'admm': fld.extend(['XPrRsdl', 'XDlRsdl', 'XRho']) else: if opt['CBPDN', 'BackTrack', 'Enabled']: fld.extend(['X_F_Btrack', 'X_Q_Btrack', 'X_ItBt', 'X_L', 'X_Rsdl']) else: fld.extend(['X_L', 'X_Rsdl']) if dmethod != 'fista': fld.extend(['DPrRsdl', 'DDlRsdl', 'DRho']) else: if opt['CCMOD', 'BackTrack', 'Enabled']: fld.extend(['D_F_Btrack', 'D_Q_Btrack', 'D_ItBt', 'D_L', 'D_Rsdl']) else: fld.extend(['D_L', 'D_Rsdl']) fld.append('Time') return fld
[ "def", "isfld", "(", "xmethod", ",", "dmethod", ",", "opt", ")", ":", "fld", "=", "[", "'Iter'", ",", "'ObjFun'", ",", "'DFid'", ",", "'RegL1'", ",", "'Cnstr'", "]", "if", "xmethod", "==", "'admm'", ":", "fld", ".", "extend", "(", "[", "'XPrRsdl'", ...
Return ``isfld`` argument for ``.IterStatsConfig`` initialiser.
[ "Return", "isfld", "argument", "for", ".", "IterStatsConfig", "initialiser", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/common.py#L63-L85
train
210,201
bwohlberg/sporco
sporco/dictlrn/dictlrn.py
IterStatsConfig.iterstats
def iterstats(self, j, t, isx, isd, evl): """Construct IterationStats namedtuple from X step and D step IterationStats namedtuples. Parameters ---------- j : int Iteration number t : float Iteration time isx : namedtuple IterationStats namedtuple from X step object isd : namedtuple IterationStats namedtuple from D step object evl : dict Dict associating result labels with values computed by :meth:`DictLearn.evaluate` """ vlst = [] # Iterate over the fields of the IterationStats namedtuple # to be populated with values. If a field name occurs as a # key in the isxmap dictionary, use the corresponding key # value as a field name in the isx namedtuple for the X # step object and append the value of that field as the # next value in the IterationStats namedtuple under # construction. The isdmap dictionary is handled # correspondingly with respect to the isd namedtuple for # the D step object. There are also two reserved field # names, 'Iter' and 'Time', referring respectively to the # iteration number and run time of the dictionary learning # algorithm. for fnm in self.IterationStats._fields: if fnm in self.isxmap: vlst.append(getattr(isx, self.isxmap[fnm])) elif fnm in self.isdmap: vlst.append(getattr(isd, self.isdmap[fnm])) elif fnm in self.evlmap: vlst.append(evl[fnm]) elif fnm == 'Iter': vlst.append(j) elif fnm == 'Time': vlst.append(t) else: vlst.append(None) return self.IterationStats._make(vlst)
python
def iterstats(self, j, t, isx, isd, evl): """Construct IterationStats namedtuple from X step and D step IterationStats namedtuples. Parameters ---------- j : int Iteration number t : float Iteration time isx : namedtuple IterationStats namedtuple from X step object isd : namedtuple IterationStats namedtuple from D step object evl : dict Dict associating result labels with values computed by :meth:`DictLearn.evaluate` """ vlst = [] # Iterate over the fields of the IterationStats namedtuple # to be populated with values. If a field name occurs as a # key in the isxmap dictionary, use the corresponding key # value as a field name in the isx namedtuple for the X # step object and append the value of that field as the # next value in the IterationStats namedtuple under # construction. The isdmap dictionary is handled # correspondingly with respect to the isd namedtuple for # the D step object. There are also two reserved field # names, 'Iter' and 'Time', referring respectively to the # iteration number and run time of the dictionary learning # algorithm. for fnm in self.IterationStats._fields: if fnm in self.isxmap: vlst.append(getattr(isx, self.isxmap[fnm])) elif fnm in self.isdmap: vlst.append(getattr(isd, self.isdmap[fnm])) elif fnm in self.evlmap: vlst.append(evl[fnm]) elif fnm == 'Iter': vlst.append(j) elif fnm == 'Time': vlst.append(t) else: vlst.append(None) return self.IterationStats._make(vlst)
[ "def", "iterstats", "(", "self", ",", "j", ",", "t", ",", "isx", ",", "isd", ",", "evl", ")", ":", "vlst", "=", "[", "]", "# Iterate over the fields of the IterationStats namedtuple", "# to be populated with values. If a field name occurs as a", "# key in the isxmap dicti...
Construct IterationStats namedtuple from X step and D step IterationStats namedtuples. Parameters ---------- j : int Iteration number t : float Iteration time isx : namedtuple IterationStats namedtuple from X step object isd : namedtuple IterationStats namedtuple from D step object evl : dict Dict associating result labels with values computed by :meth:`DictLearn.evaluate`
[ "Construct", "IterationStats", "namedtuple", "from", "X", "step", "and", "D", "step", "IterationStats", "namedtuples", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/dictlrn.py#L84-L130
train
210,202
bwohlberg/sporco
sporco/dictlrn/dictlrn.py
IterStatsConfig.printiterstats
def printiterstats(self, itst): """Print iteration statistics. Parameters ---------- itst : namedtuple IterationStats namedtuple as returned by :meth:`iterstats` """ itdsp = tuple([getattr(itst, self.hdrmap[col]) for col in self.hdrtxt]) print(self.fmtstr % itdsp)
python
def printiterstats(self, itst): """Print iteration statistics. Parameters ---------- itst : namedtuple IterationStats namedtuple as returned by :meth:`iterstats` """ itdsp = tuple([getattr(itst, self.hdrmap[col]) for col in self.hdrtxt]) print(self.fmtstr % itdsp)
[ "def", "printiterstats", "(", "self", ",", "itst", ")", ":", "itdsp", "=", "tuple", "(", "[", "getattr", "(", "itst", ",", "self", ".", "hdrmap", "[", "col", "]", ")", "for", "col", "in", "self", ".", "hdrtxt", "]", ")", "print", "(", "self", "."...
Print iteration statistics. Parameters ---------- itst : namedtuple IterationStats namedtuple as returned by :meth:`iterstats`
[ "Print", "iteration", "statistics", "." ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/dictlrn.py#L149-L159
train
210,203
bwohlberg/sporco
sporco/prox/_nuclear.py
norm_nuclear
def norm_nuclear(X): r"""Compute the nuclear norm .. math:: \| X \|_* = \sum_i \sigma_i where :math:`\sigma_i` are the singular values of matrix :math:`X`. Parameters ---------- X : array_like Input array :math:`X` Returns ------- nncl : float Nuclear norm of `X` """ return np.sum(np.linalg.svd(sl.promote16(X), compute_uv=False))
python
def norm_nuclear(X): r"""Compute the nuclear norm .. math:: \| X \|_* = \sum_i \sigma_i where :math:`\sigma_i` are the singular values of matrix :math:`X`. Parameters ---------- X : array_like Input array :math:`X` Returns ------- nncl : float Nuclear norm of `X` """ return np.sum(np.linalg.svd(sl.promote16(X), compute_uv=False))
[ "def", "norm_nuclear", "(", "X", ")", ":", "return", "np", ".", "sum", "(", "np", ".", "linalg", ".", "svd", "(", "sl", ".", "promote16", "(", "X", ")", ",", "compute_uv", "=", "False", ")", ")" ]
r"""Compute the nuclear norm .. math:: \| X \|_* = \sum_i \sigma_i where :math:`\sigma_i` are the singular values of matrix :math:`X`. Parameters ---------- X : array_like Input array :math:`X` Returns ------- nncl : float Nuclear norm of `X`
[ "r", "Compute", "the", "nuclear", "norm" ]
8946a04331106f4e39904fbdf2dc7351900baa04
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/prox/_nuclear.py#L21-L41
train
210,204
danilobellini/audiolazy
audiolazy/_internals.py
deprecate
def deprecate(func): """ A deprecation warning emmiter as a decorator. """ @wraps(func) def wrapper(*args, **kwargs): warn("Deprecated, this will be removed in the future", DeprecationWarning) return func(*args, **kwargs) wrapper.__doc__ = "Deprecated.\n" + (wrapper.__doc__ or "") return wrapper
python
def deprecate(func): """ A deprecation warning emmiter as a decorator. """ @wraps(func) def wrapper(*args, **kwargs): warn("Deprecated, this will be removed in the future", DeprecationWarning) return func(*args, **kwargs) wrapper.__doc__ = "Deprecated.\n" + (wrapper.__doc__ or "") return wrapper
[ "def", "deprecate", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warn", "(", "\"Deprecated, this will be removed in the future\"", ",", "DeprecationWarning", ")", "return", "fu...
A deprecation warning emmiter as a decorator.
[ "A", "deprecation", "warning", "emmiter", "as", "a", "decorator", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/_internals.py#L31-L38
train
210,205
danilobellini/audiolazy
audiolazy/_internals.py
get_module_names
def get_module_names(package_path, pattern="lazy_*.py*"): """ All names in the package directory that matches the given glob, without their extension. Repeated names should appear only once. """ package_contents = glob(os.path.join(package_path[0], pattern)) relative_path_names = (os.path.split(name)[1] for name in package_contents) no_ext_names = (os.path.splitext(name)[0] for name in relative_path_names) return sorted(set(no_ext_names))
python
def get_module_names(package_path, pattern="lazy_*.py*"): """ All names in the package directory that matches the given glob, without their extension. Repeated names should appear only once. """ package_contents = glob(os.path.join(package_path[0], pattern)) relative_path_names = (os.path.split(name)[1] for name in package_contents) no_ext_names = (os.path.splitext(name)[0] for name in relative_path_names) return sorted(set(no_ext_names))
[ "def", "get_module_names", "(", "package_path", ",", "pattern", "=", "\"lazy_*.py*\"", ")", ":", "package_contents", "=", "glob", "(", "os", ".", "path", ".", "join", "(", "package_path", "[", "0", "]", ",", "pattern", ")", ")", "relative_path_names", "=", ...
All names in the package directory that matches the given glob, without their extension. Repeated names should appear only once.
[ "All", "names", "in", "the", "package", "directory", "that", "matches", "the", "given", "glob", "without", "their", "extension", ".", "Repeated", "names", "should", "appear", "only", "once", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/_internals.py#L45-L53
train
210,206
danilobellini/audiolazy
audiolazy/_internals.py
get_modules
def get_modules(package_name, module_names): """ List of module objects from the package, keeping the name order. """ def get_module(name): return __import__(".".join([package_name, name]), fromlist=[package_name]) return [get_module(name) for name in module_names]
python
def get_modules(package_name, module_names): """ List of module objects from the package, keeping the name order. """ def get_module(name): return __import__(".".join([package_name, name]), fromlist=[package_name]) return [get_module(name) for name in module_names]
[ "def", "get_modules", "(", "package_name", ",", "module_names", ")", ":", "def", "get_module", "(", "name", ")", ":", "return", "__import__", "(", "\".\"", ".", "join", "(", "[", "package_name", ",", "name", "]", ")", ",", "fromlist", "=", "[", "package_...
List of module objects from the package, keeping the name order.
[ "List", "of", "module", "objects", "from", "the", "package", "keeping", "the", "name", "order", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/_internals.py#L55-L59
train
210,207
danilobellini/audiolazy
audiolazy/_internals.py
docstring_with_summary
def docstring_with_summary(docstring, pairs, key_header, summary_type): """ Return a string joining the docstring with the pairs summary table. """ return "\n".join( [docstring, "Summary of {}:".format(summary_type), ""] + summary_table(pairs, key_header) + [""] )
python
def docstring_with_summary(docstring, pairs, key_header, summary_type): """ Return a string joining the docstring with the pairs summary table. """ return "\n".join( [docstring, "Summary of {}:".format(summary_type), ""] + summary_table(pairs, key_header) + [""] )
[ "def", "docstring_with_summary", "(", "docstring", ",", "pairs", ",", "key_header", ",", "summary_type", ")", ":", "return", "\"\\n\"", ".", "join", "(", "[", "docstring", ",", "\"Summary of {}:\"", ".", "format", "(", "summary_type", ")", ",", "\"\"", "]", ...
Return a string joining the docstring with the pairs summary table.
[ "Return", "a", "string", "joining", "the", "docstring", "with", "the", "pairs", "summary", "table", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/_internals.py#L80-L85
train
210,208
danilobellini/audiolazy
examples/save_and_memoize_synth.py
memoize
def memoize(func): """ Decorator for unerasable memoization based on function arguments, for functions without keyword arguments. """ class Memoizer(dict): def __missing__(self, args): val = func(*args) self[args] = val return val memory = Memoizer() @wraps(func) def wrapper(*args): return memory[args] return wrapper
python
def memoize(func): """ Decorator for unerasable memoization based on function arguments, for functions without keyword arguments. """ class Memoizer(dict): def __missing__(self, args): val = func(*args) self[args] = val return val memory = Memoizer() @wraps(func) def wrapper(*args): return memory[args] return wrapper
[ "def", "memoize", "(", "func", ")", ":", "class", "Memoizer", "(", "dict", ")", ":", "def", "__missing__", "(", "self", ",", "args", ")", ":", "val", "=", "func", "(", "*", "args", ")", "self", "[", "args", "]", "=", "val", "return", "val", "memo...
Decorator for unerasable memoization based on function arguments, for functions without keyword arguments.
[ "Decorator", "for", "unerasable", "memoization", "based", "on", "function", "arguments", "for", "functions", "without", "keyword", "arguments", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/save_and_memoize_synth.py#L34-L48
train
210,209
danilobellini/audiolazy
examples/save_and_memoize_synth.py
save_to_16bit_wave_file
def save_to_16bit_wave_file(fname, sig, rate): """ Save a given signal ``sig`` to file ``fname`` as a 16-bit one-channel wave with the given ``rate`` sample rate. """ with closing(wave.open(fname, "wb")) as wave_file: wave_file.setnchannels(1) wave_file.setsampwidth(2) wave_file.setframerate(rate) for chunk in chunks((clip(sig) * 2 ** 15).map(int), dfmt="h", padval=0): wave_file.writeframes(chunk)
python
def save_to_16bit_wave_file(fname, sig, rate): """ Save a given signal ``sig`` to file ``fname`` as a 16-bit one-channel wave with the given ``rate`` sample rate. """ with closing(wave.open(fname, "wb")) as wave_file: wave_file.setnchannels(1) wave_file.setsampwidth(2) wave_file.setframerate(rate) for chunk in chunks((clip(sig) * 2 ** 15).map(int), dfmt="h", padval=0): wave_file.writeframes(chunk)
[ "def", "save_to_16bit_wave_file", "(", "fname", ",", "sig", ",", "rate", ")", ":", "with", "closing", "(", "wave", ".", "open", "(", "fname", ",", "\"wb\"", ")", ")", "as", "wave_file", ":", "wave_file", ".", "setnchannels", "(", "1", ")", "wave_file", ...
Save a given signal ``sig`` to file ``fname`` as a 16-bit one-channel wave with the given ``rate`` sample rate.
[ "Save", "a", "given", "signal", "sig", "to", "file", "fname", "as", "a", "16", "-", "bit", "one", "-", "channel", "wave", "with", "the", "given", "rate", "sample", "rate", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/save_and_memoize_synth.py#L51-L61
train
210,210
danilobellini/audiolazy
examples/save_and_memoize_synth.py
new_note_track
def new_note_track(env, synth): """ Audio track with the frequencies. Parameters ---------- env: Envelope Stream (which imposes the duration). synth: One-argument function that receives a frequency (in rad/sample) and returns a Stream instance (a synthesized note). Returns ------- Endless Stream instance that joins synthesized notes. """ list_env = list(env) return chain.from_iterable(synth(freq) * list_env for freq in freq_gen())
python
def new_note_track(env, synth): """ Audio track with the frequencies. Parameters ---------- env: Envelope Stream (which imposes the duration). synth: One-argument function that receives a frequency (in rad/sample) and returns a Stream instance (a synthesized note). Returns ------- Endless Stream instance that joins synthesized notes. """ list_env = list(env) return chain.from_iterable(synth(freq) * list_env for freq in freq_gen())
[ "def", "new_note_track", "(", "env", ",", "synth", ")", ":", "list_env", "=", "list", "(", "env", ")", "return", "chain", ".", "from_iterable", "(", "synth", "(", "freq", ")", "*", "list_env", "for", "freq", "in", "freq_gen", "(", ")", ")" ]
Audio track with the frequencies. Parameters ---------- env: Envelope Stream (which imposes the duration). synth: One-argument function that receives a frequency (in rad/sample) and returns a Stream instance (a synthesized note). Returns ------- Endless Stream instance that joins synthesized notes.
[ "Audio", "track", "with", "the", "frequencies", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/save_and_memoize_synth.py#L92-L110
train
210,211
danilobellini/audiolazy
audiolazy/lazy_stream.py
tostream
def tostream(func, module_name=None): """ Decorator to convert the function output into a Stream. Useful for generator functions. Note ---- Always use the ``module_name`` input when "decorating" a function that was defined in other module. """ @wraps(func) def new_func(*args, **kwargs): return Stream(func(*args, **kwargs)) if module_name is not None: new_func.__module__ = module_name return new_func
python
def tostream(func, module_name=None): """ Decorator to convert the function output into a Stream. Useful for generator functions. Note ---- Always use the ``module_name`` input when "decorating" a function that was defined in other module. """ @wraps(func) def new_func(*args, **kwargs): return Stream(func(*args, **kwargs)) if module_name is not None: new_func.__module__ = module_name return new_func
[ "def", "tostream", "(", "func", ",", "module_name", "=", "None", ")", ":", "@", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Stream", "(", "func", "(", "*", "args", ",", "*", "*", ...
Decorator to convert the function output into a Stream. Useful for generator functions. Note ---- Always use the ``module_name`` input when "decorating" a function that was defined in other module.
[ "Decorator", "to", "convert", "the", "function", "output", "into", "a", "Stream", ".", "Useful", "for", "generator", "functions", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_stream.py#L413-L429
train
210,212
danilobellini/audiolazy
audiolazy/lazy_stream.py
thub
def thub(data, n): """ Tee or "T" hub auto-copier to help working with Stream instances as well as with numbers. Parameters ---------- data : Input to be copied. Can be anything. n : Number of copies. Returns ------- A StreamTeeHub instance, if input data is iterable. The data itself, otherwise. Examples -------- >>> def sub_sum(x, y): ... x = thub(x, 2) # Casts to StreamTeeHub, when needed ... y = thub(y, 2) ... return (x - y) / (x + y) # Return type might be number or Stream With numbers: >>> sub_sum(1, 1.) 0.0 Combining number with iterable: >>> sub_sum(3., [1, 2, 3]) <audiolazy.lazy_stream.Stream object at 0x...> >>> list(sub_sum(3., [1, 2, 3])) [0.5, 0.2, 0.0] Both iterables (the Stream input behaves like an endless [6, 1, 6, 1, ...]): >>> list(sub_sum([4., 3., 2., 1.], [1, 2, 3])) [0.6, 0.2, -0.2] >>> list(sub_sum([4., 3., 2., 1.], Stream(6, 1))) [-0.2, 0.5, -0.5, 0.0] This function can also be used as a an alternative to the Stream constructor when your function has only one parameter, to avoid casting when that's not needed: >>> func = lambda x: 250 * thub(x, 1) >>> func(1) 250 >>> func([2] * 10) <audiolazy.lazy_stream.Stream object at 0x...> >>> func([2] * 10).take(5) [500, 500, 500, 500, 500] """ return StreamTeeHub(data, n) if isinstance(data, Iterable) else data
python
def thub(data, n): """ Tee or "T" hub auto-copier to help working with Stream instances as well as with numbers. Parameters ---------- data : Input to be copied. Can be anything. n : Number of copies. Returns ------- A StreamTeeHub instance, if input data is iterable. The data itself, otherwise. Examples -------- >>> def sub_sum(x, y): ... x = thub(x, 2) # Casts to StreamTeeHub, when needed ... y = thub(y, 2) ... return (x - y) / (x + y) # Return type might be number or Stream With numbers: >>> sub_sum(1, 1.) 0.0 Combining number with iterable: >>> sub_sum(3., [1, 2, 3]) <audiolazy.lazy_stream.Stream object at 0x...> >>> list(sub_sum(3., [1, 2, 3])) [0.5, 0.2, 0.0] Both iterables (the Stream input behaves like an endless [6, 1, 6, 1, ...]): >>> list(sub_sum([4., 3., 2., 1.], [1, 2, 3])) [0.6, 0.2, -0.2] >>> list(sub_sum([4., 3., 2., 1.], Stream(6, 1))) [-0.2, 0.5, -0.5, 0.0] This function can also be used as a an alternative to the Stream constructor when your function has only one parameter, to avoid casting when that's not needed: >>> func = lambda x: 250 * thub(x, 1) >>> func(1) 250 >>> func([2] * 10) <audiolazy.lazy_stream.Stream object at 0x...> >>> func([2] * 10).take(5) [500, 500, 500, 500, 500] """ return StreamTeeHub(data, n) if isinstance(data, Iterable) else data
[ "def", "thub", "(", "data", ",", "n", ")", ":", "return", "StreamTeeHub", "(", "data", ",", "n", ")", "if", "isinstance", "(", "data", ",", "Iterable", ")", "else", "data" ]
Tee or "T" hub auto-copier to help working with Stream instances as well as with numbers. Parameters ---------- data : Input to be copied. Can be anything. n : Number of copies. Returns ------- A StreamTeeHub instance, if input data is iterable. The data itself, otherwise. Examples -------- >>> def sub_sum(x, y): ... x = thub(x, 2) # Casts to StreamTeeHub, when needed ... y = thub(y, 2) ... return (x - y) / (x + y) # Return type might be number or Stream With numbers: >>> sub_sum(1, 1.) 0.0 Combining number with iterable: >>> sub_sum(3., [1, 2, 3]) <audiolazy.lazy_stream.Stream object at 0x...> >>> list(sub_sum(3., [1, 2, 3])) [0.5, 0.2, 0.0] Both iterables (the Stream input behaves like an endless [6, 1, 6, 1, ...]): >>> list(sub_sum([4., 3., 2., 1.], [1, 2, 3])) [0.6, 0.2, -0.2] >>> list(sub_sum([4., 3., 2., 1.], Stream(6, 1))) [-0.2, 0.5, -0.5, 0.0] This function can also be used as a an alternative to the Stream constructor when your function has only one parameter, to avoid casting when that's not needed: >>> func = lambda x: 250 * thub(x, 1) >>> func(1) 250 >>> func([2] * 10) <audiolazy.lazy_stream.Stream object at 0x...> >>> func([2] * 10).take(5) [500, 500, 500, 500, 500]
[ "Tee", "or", "T", "hub", "auto", "-", "copier", "to", "help", "working", "with", "Stream", "instances", "as", "well", "as", "with", "numbers", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_stream.py#L569-L626
train
210,213
danilobellini/audiolazy
audiolazy/lazy_stream.py
Stream.blocks
def blocks(self, *args, **kwargs): """ Interface to apply audiolazy.blocks directly in a stream, returning another stream. Use keyword args. """ return Stream(blocks(iter(self), *args, **kwargs))
python
def blocks(self, *args, **kwargs): """ Interface to apply audiolazy.blocks directly in a stream, returning another stream. Use keyword args. """ return Stream(blocks(iter(self), *args, **kwargs))
[ "def", "blocks", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Stream", "(", "blocks", "(", "iter", "(", "self", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
Interface to apply audiolazy.blocks directly in a stream, returning another stream. Use keyword args.
[ "Interface", "to", "apply", "audiolazy", ".", "blocks", "directly", "in", "a", "stream", "returning", "another", "stream", ".", "Use", "keyword", "args", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_stream.py#L211-L216
train
210,214
danilobellini/audiolazy
audiolazy/lazy_stream.py
Stream.take
def take(self, n=None, constructor=list): """ Returns a container with the n first elements from the Stream, or less if there aren't enough. Use this without args if you need only one element outside a list. Parameters ---------- n : Number of elements to be taken. Defaults to None. Rounded when it's a float, and this can be ``inf`` for taking all. constructor : Container constructor function that can receie a generator as input. Defaults to ``list``. Returns ------- The first ``n`` elements of the Stream sequence, created by the given constructor unless ``n == None``, which means returns the next element from the sequence outside any container. If ``n`` is None, this can raise StopIteration due to lack of data in the Stream. When ``n`` is a number, there's no such exception. Examples -------- >>> Stream(5).take(3) # Three elements [5, 5, 5] >>> Stream(1.2, 2, 3).take() # One element, outside a container 1.2 >>> Stream(1.2, 2, 3).take(1) # With n = 1 argument, it'll be in a list [1.2] >>> Stream(1.2, 2, 3).take(1, constructor=tuple) # Why not a tuple? (1.2,) >>> Stream([1, 2]).take(3) # More than the Stream size, n is integer [1, 2] >>> Stream([]).take() # More than the Stream size, n is None Traceback (most recent call last): ... StopIteration Taking rounded float quantities and "up to infinity" elements (don't try using ``inf`` with endless Stream instances): >>> Stream([4, 3, 2, 3, 2]).take(3.4) [4, 3, 2] >>> Stream([4, 3, 2, 3, 2]).take(3.6) [4, 3, 2, 3] >>> Stream([4, 3, 2, 3, 2]).take(inf) [4, 3, 2, 3, 2] See Also -------- Stream.peek : Returns the n first elements from the Stream, without removing them. Note ---- You should avoid using take() as if this would be an iterator. Streams are iterables that can be easily part of a "for" loop, and their iterators (the ones automatically used in for loops) are slightly faster. Use iter() builtin if you need that, instead, or perhaps the blocks method. """ if n is None: return next(self._data) if isinf(n) and n > 0: return constructor(self._data) if isinstance(n, float): n = rint(n) if n > 0 else 0 # So this works with -inf and nan return constructor(next(self._data) for _ in xrange(n))
python
def take(self, n=None, constructor=list): """ Returns a container with the n first elements from the Stream, or less if there aren't enough. Use this without args if you need only one element outside a list. Parameters ---------- n : Number of elements to be taken. Defaults to None. Rounded when it's a float, and this can be ``inf`` for taking all. constructor : Container constructor function that can receie a generator as input. Defaults to ``list``. Returns ------- The first ``n`` elements of the Stream sequence, created by the given constructor unless ``n == None``, which means returns the next element from the sequence outside any container. If ``n`` is None, this can raise StopIteration due to lack of data in the Stream. When ``n`` is a number, there's no such exception. Examples -------- >>> Stream(5).take(3) # Three elements [5, 5, 5] >>> Stream(1.2, 2, 3).take() # One element, outside a container 1.2 >>> Stream(1.2, 2, 3).take(1) # With n = 1 argument, it'll be in a list [1.2] >>> Stream(1.2, 2, 3).take(1, constructor=tuple) # Why not a tuple? (1.2,) >>> Stream([1, 2]).take(3) # More than the Stream size, n is integer [1, 2] >>> Stream([]).take() # More than the Stream size, n is None Traceback (most recent call last): ... StopIteration Taking rounded float quantities and "up to infinity" elements (don't try using ``inf`` with endless Stream instances): >>> Stream([4, 3, 2, 3, 2]).take(3.4) [4, 3, 2] >>> Stream([4, 3, 2, 3, 2]).take(3.6) [4, 3, 2, 3] >>> Stream([4, 3, 2, 3, 2]).take(inf) [4, 3, 2, 3, 2] See Also -------- Stream.peek : Returns the n first elements from the Stream, without removing them. Note ---- You should avoid using take() as if this would be an iterator. Streams are iterables that can be easily part of a "for" loop, and their iterators (the ones automatically used in for loops) are slightly faster. Use iter() builtin if you need that, instead, or perhaps the blocks method. """ if n is None: return next(self._data) if isinf(n) and n > 0: return constructor(self._data) if isinstance(n, float): n = rint(n) if n > 0 else 0 # So this works with -inf and nan return constructor(next(self._data) for _ in xrange(n))
[ "def", "take", "(", "self", ",", "n", "=", "None", ",", "constructor", "=", "list", ")", ":", "if", "n", "is", "None", ":", "return", "next", "(", "self", ".", "_data", ")", "if", "isinf", "(", "n", ")", "and", "n", ">", "0", ":", "return", "...
Returns a container with the n first elements from the Stream, or less if there aren't enough. Use this without args if you need only one element outside a list. Parameters ---------- n : Number of elements to be taken. Defaults to None. Rounded when it's a float, and this can be ``inf`` for taking all. constructor : Container constructor function that can receie a generator as input. Defaults to ``list``. Returns ------- The first ``n`` elements of the Stream sequence, created by the given constructor unless ``n == None``, which means returns the next element from the sequence outside any container. If ``n`` is None, this can raise StopIteration due to lack of data in the Stream. When ``n`` is a number, there's no such exception. Examples -------- >>> Stream(5).take(3) # Three elements [5, 5, 5] >>> Stream(1.2, 2, 3).take() # One element, outside a container 1.2 >>> Stream(1.2, 2, 3).take(1) # With n = 1 argument, it'll be in a list [1.2] >>> Stream(1.2, 2, 3).take(1, constructor=tuple) # Why not a tuple? (1.2,) >>> Stream([1, 2]).take(3) # More than the Stream size, n is integer [1, 2] >>> Stream([]).take() # More than the Stream size, n is None Traceback (most recent call last): ... StopIteration Taking rounded float quantities and "up to infinity" elements (don't try using ``inf`` with endless Stream instances): >>> Stream([4, 3, 2, 3, 2]).take(3.4) [4, 3, 2] >>> Stream([4, 3, 2, 3, 2]).take(3.6) [4, 3, 2, 3] >>> Stream([4, 3, 2, 3, 2]).take(inf) [4, 3, 2, 3, 2] See Also -------- Stream.peek : Returns the n first elements from the Stream, without removing them. Note ---- You should avoid using take() as if this would be an iterator. Streams are iterables that can be easily part of a "for" loop, and their iterators (the ones automatically used in for loops) are slightly faster. Use iter() builtin if you need that, instead, or perhaps the blocks method.
[ "Returns", "a", "container", "with", "the", "n", "first", "elements", "from", "the", "Stream", "or", "less", "if", "there", "aren", "t", "enough", ".", "Use", "this", "without", "args", "if", "you", "need", "only", "one", "element", "outside", "a", "list...
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_stream.py#L218-L288
train
210,215
danilobellini/audiolazy
audiolazy/lazy_stream.py
Stream.skip
def skip(self, n): """ Throws away the first ``n`` values from the Stream. Note ---- Performs the evaluation lazily, i.e., the values are thrown away only after requesting the next value. """ def skipper(data): for _ in xrange(int(round(n))): next(data) for el in data: yield el self._data = skipper(self._data) return self
python
def skip(self, n): """ Throws away the first ``n`` values from the Stream. Note ---- Performs the evaluation lazily, i.e., the values are thrown away only after requesting the next value. """ def skipper(data): for _ in xrange(int(round(n))): next(data) for el in data: yield el self._data = skipper(self._data) return self
[ "def", "skip", "(", "self", ",", "n", ")", ":", "def", "skipper", "(", "data", ")", ":", "for", "_", "in", "xrange", "(", "int", "(", "round", "(", "n", ")", ")", ")", ":", "next", "(", "data", ")", "for", "el", "in", "data", ":", "yield", ...
Throws away the first ``n`` values from the Stream. Note ---- Performs the evaluation lazily, i.e., the values are thrown away only after requesting the next value.
[ "Throws", "away", "the", "first", "n", "values", "from", "the", "Stream", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_stream.py#L320-L337
train
210,216
danilobellini/audiolazy
audiolazy/lazy_stream.py
Stream.limit
def limit(self, n): """ Enforces the Stream to finish after ``n`` items. """ data = self._data self._data = (next(data) for _ in xrange(int(round(n)))) return self
python
def limit(self, n): """ Enforces the Stream to finish after ``n`` items. """ data = self._data self._data = (next(data) for _ in xrange(int(round(n)))) return self
[ "def", "limit", "(", "self", ",", "n", ")", ":", "data", "=", "self", ".", "_data", "self", ".", "_data", "=", "(", "next", "(", "data", ")", "for", "_", "in", "xrange", "(", "int", "(", "round", "(", "n", ")", ")", ")", ")", "return", "self"...
Enforces the Stream to finish after ``n`` items.
[ "Enforces", "the", "Stream", "to", "finish", "after", "n", "items", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_stream.py#L339-L345
train
210,217
danilobellini/audiolazy
audiolazy/lazy_stream.py
Stream.filter
def filter(self, func): """ A lazy way to skip elements in the stream that gives False for the given function. """ self._data = xfilter(func, self._data) return self
python
def filter(self, func): """ A lazy way to skip elements in the stream that gives False for the given function. """ self._data = xfilter(func, self._data) return self
[ "def", "filter", "(", "self", ",", "func", ")", ":", "self", ".", "_data", "=", "xfilter", "(", "func", ",", "self", ".", "_data", ")", "return", "self" ]
A lazy way to skip elements in the stream that gives False for the given function.
[ "A", "lazy", "way", "to", "skip", "elements", "in", "the", "stream", "that", "gives", "False", "for", "the", "given", "function", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_stream.py#L388-L394
train
210,218
danilobellini/audiolazy
audiolazy/lazy_itertools.py
accumulate
def accumulate(iterable): " Return series of accumulated sums. " iterator = iter(iterable) sum_data = next(iterator) yield sum_data for el in iterator: sum_data += el yield sum_data
python
def accumulate(iterable): " Return series of accumulated sums. " iterator = iter(iterable) sum_data = next(iterator) yield sum_data for el in iterator: sum_data += el yield sum_data
[ "def", "accumulate", "(", "iterable", ")", ":", "iterator", "=", "iter", "(", "iterable", ")", "sum_data", "=", "next", "(", "iterator", ")", "yield", "sum_data", "for", "el", "in", "iterator", ":", "sum_data", "+=", "el", "yield", "sum_data" ]
Return series of accumulated sums.
[ "Return", "series", "of", "accumulated", "sums", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_itertools.py#L69-L76
train
210,219
danilobellini/audiolazy
audiolazy/lazy_itertools.py
tee
def tee(data, n=2): """ Tee or "T" copy to help working with Stream instances as well as with numbers. Parameters ---------- data : Input to be copied. Can be anything. n : Size of returned tuple. Defaults to 2. Returns ------- Tuple of n independent Stream instances, if the input is a Stream or an iterator, otherwise a tuple with n times the same object. See Also -------- thub : use Stream instances *almost* like constants in your equations. """ if isinstance(data, (Stream, Iterator)): return tuple(Stream(cp) for cp in it.tee(data, n)) else: return tuple(data for unused in xrange(n))
python
def tee(data, n=2): """ Tee or "T" copy to help working with Stream instances as well as with numbers. Parameters ---------- data : Input to be copied. Can be anything. n : Size of returned tuple. Defaults to 2. Returns ------- Tuple of n independent Stream instances, if the input is a Stream or an iterator, otherwise a tuple with n times the same object. See Also -------- thub : use Stream instances *almost* like constants in your equations. """ if isinstance(data, (Stream, Iterator)): return tuple(Stream(cp) for cp in it.tee(data, n)) else: return tuple(data for unused in xrange(n))
[ "def", "tee", "(", "data", ",", "n", "=", "2", ")", ":", "if", "isinstance", "(", "data", ",", "(", "Stream", ",", "Iterator", ")", ")", ":", "return", "tuple", "(", "Stream", "(", "cp", ")", "for", "cp", "in", "it", ".", "tee", "(", "data", ...
Tee or "T" copy to help working with Stream instances as well as with numbers. Parameters ---------- data : Input to be copied. Can be anything. n : Size of returned tuple. Defaults to 2. Returns ------- Tuple of n independent Stream instances, if the input is a Stream or an iterator, otherwise a tuple with n times the same object. See Also -------- thub : use Stream instances *almost* like constants in your equations.
[ "Tee", "or", "T", "copy", "to", "help", "working", "with", "Stream", "instances", "as", "well", "as", "with", "numbers", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_itertools.py#L82-L108
train
210,220
danilobellini/audiolazy
audiolazy/lazy_math.py
factorial
def factorial(n): """ Factorial function that works with really big numbers. """ if isinstance(n, float): if n.is_integer(): n = int(n) if not isinstance(n, INT_TYPES): raise TypeError("Non-integer input (perhaps you need Euler Gamma " "function or Gauss Pi function)") if n < 0: raise ValueError("Input shouldn't be negative") return reduce(operator.mul, it.takewhile(lambda m: m <= n, it.count(2)), 1)
python
def factorial(n): """ Factorial function that works with really big numbers. """ if isinstance(n, float): if n.is_integer(): n = int(n) if not isinstance(n, INT_TYPES): raise TypeError("Non-integer input (perhaps you need Euler Gamma " "function or Gauss Pi function)") if n < 0: raise ValueError("Input shouldn't be negative") return reduce(operator.mul, it.takewhile(lambda m: m <= n, it.count(2)), 1)
[ "def", "factorial", "(", "n", ")", ":", "if", "isinstance", "(", "n", ",", "float", ")", ":", "if", "n", ".", "is_integer", "(", ")", ":", "n", "=", "int", "(", "n", ")", "if", "not", "isinstance", "(", "n", ",", "INT_TYPES", ")", ":", "raise",...
Factorial function that works with really big numbers.
[ "Factorial", "function", "that", "works", "with", "really", "big", "numbers", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_math.py#L95-L109
train
210,221
danilobellini/audiolazy
examples/pi.py
mgl_seq
def mgl_seq(x): """ Sequence whose sum is the Madhava-Gregory-Leibniz series. [x, -x^3/3, x^5/5, -x^7/7, x^9/9, -x^11/11, ...] Returns ------- An endless sequence that has the property ``atan(x) = sum(mgl_seq(x))``. Usually you would use the ``atan()`` function, not this one. """ odd_numbers = thub(count(start=1, step=2), 2) return Stream(1, -1) * x ** odd_numbers / odd_numbers
python
def mgl_seq(x): """ Sequence whose sum is the Madhava-Gregory-Leibniz series. [x, -x^3/3, x^5/5, -x^7/7, x^9/9, -x^11/11, ...] Returns ------- An endless sequence that has the property ``atan(x) = sum(mgl_seq(x))``. Usually you would use the ``atan()`` function, not this one. """ odd_numbers = thub(count(start=1, step=2), 2) return Stream(1, -1) * x ** odd_numbers / odd_numbers
[ "def", "mgl_seq", "(", "x", ")", ":", "odd_numbers", "=", "thub", "(", "count", "(", "start", "=", "1", ",", "step", "=", "2", ")", ",", "2", ")", "return", "Stream", "(", "1", ",", "-", "1", ")", "*", "x", "**", "odd_numbers", "/", "odd_number...
Sequence whose sum is the Madhava-Gregory-Leibniz series. [x, -x^3/3, x^5/5, -x^7/7, x^9/9, -x^11/11, ...] Returns ------- An endless sequence that has the property ``atan(x) = sum(mgl_seq(x))``. Usually you would use the ``atan()`` function, not this one.
[ "Sequence", "whose", "sum", "is", "the", "Madhava", "-", "Gregory", "-", "Leibniz", "series", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/pi.py#L24-L38
train
210,222
danilobellini/audiolazy
examples/pi.py
atan_mgl
def atan_mgl(x, n=10): """ Finds the arctan using the Madhava-Gregory-Leibniz series. """ acc = 1 / (1 - z ** -1) # Accumulator filter return acc(mgl_seq(x)).skip(n-1).take()
python
def atan_mgl(x, n=10): """ Finds the arctan using the Madhava-Gregory-Leibniz series. """ acc = 1 / (1 - z ** -1) # Accumulator filter return acc(mgl_seq(x)).skip(n-1).take()
[ "def", "atan_mgl", "(", "x", ",", "n", "=", "10", ")", ":", "acc", "=", "1", "/", "(", "1", "-", "z", "**", "-", "1", ")", "# Accumulator filter", "return", "acc", "(", "mgl_seq", "(", "x", ")", ")", ".", "skip", "(", "n", "-", "1", ")", "....
Finds the arctan using the Madhava-Gregory-Leibniz series.
[ "Finds", "the", "arctan", "using", "the", "Madhava", "-", "Gregory", "-", "Leibniz", "series", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/pi.py#L41-L46
train
210,223
danilobellini/audiolazy
audiolazy/lazy_poly.py
lagrange
def lagrange(pairs): """ Waring-Lagrange interpolator function. Parameters ---------- pairs : Iterable with pairs (tuples with two values), corresponding to points ``(x, y)`` of the function. Returns ------- A function that returns the interpolator result for a given ``x``. """ prod = lambda args: reduce(operator.mul, args) xv, yv = xzip(*pairs) return lambda k: sum( yv[j] * prod( (k - rk) / (rj - rk) for rk in xv if rj != rk ) for j, rj in enumerate(xv) )
python
def lagrange(pairs): """ Waring-Lagrange interpolator function. Parameters ---------- pairs : Iterable with pairs (tuples with two values), corresponding to points ``(x, y)`` of the function. Returns ------- A function that returns the interpolator result for a given ``x``. """ prod = lambda args: reduce(operator.mul, args) xv, yv = xzip(*pairs) return lambda k: sum( yv[j] * prod( (k - rk) / (rj - rk) for rk in xv if rj != rk ) for j, rj in enumerate(xv) )
[ "def", "lagrange", "(", "pairs", ")", ":", "prod", "=", "lambda", "args", ":", "reduce", "(", "operator", ".", "mul", ",", "args", ")", "xv", ",", "yv", "=", "xzip", "(", "*", "pairs", ")", "return", "lambda", "k", ":", "sum", "(", "yv", "[", "...
Waring-Lagrange interpolator function. Parameters ---------- pairs : Iterable with pairs (tuples with two values), corresponding to points ``(x, y)`` of the function. Returns ------- A function that returns the interpolator result for a given ``x``.
[ "Waring", "-", "Lagrange", "interpolator", "function", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_poly.py#L493-L512
train
210,224
danilobellini/audiolazy
audiolazy/lazy_poly.py
resample
def resample(sig, old=1, new=1, order=3, zero=0.): """ Generic resampler based on Waring-Lagrange interpolators. Parameters ---------- sig : Input signal (any iterable). old : Time duration reference (defaults to 1, allowing percentages to the ``new`` keyword argument). This can be float number, or perhaps a Stream instance. new : Time duration that the reference will have after resampling. For example, if ``old = 1, new = 2``, then there will be 2 samples yielded for each sample from input. This can be a float number, or perhaps a Stream instance. order : Lagrange interpolator order. The amount of neighboring samples to be used by the interpolator is ``order + 1``. zero : The input should be thought as zero-padded from the left with this value. Returns ------- The first value will be the first sample from ``sig``, and then the interpolator will find the next samples towards the end of the ``sig``. The actual sampling interval (or time step) for this interpolator obeys to the ``old / new`` relationship. Hint ---- The time step can also be time-varying, although that's certainly difficult to synchonize (one sample is needed for each output sample). Perhaps the best approach for this case would be a ControlStream keeping the desired value at any time. Note ---- The input isn't zero-padded at right. It means that the last output will be one with interpolated with known data. For endless inputs that's ok, this makes no difference, but for finite inputs that may be undesirable. """ sig = Stream(sig) threshold = .5 * (order + 1) step = old / new data = deque([zero] * (order + 1), maxlen=order + 1) data.extend(sig.take(rint(threshold))) idx = int(threshold) isig = iter(sig) if isinstance(step, Iterable): step = iter(step) while True: yield lagrange(enumerate(data))(idx) idx += next(step) while idx > threshold: data.append(next(isig)) idx -= 1 else: while True: yield lagrange(enumerate(data))(idx) idx += step while idx > threshold: data.append(next(isig)) idx -= 1
python
def resample(sig, old=1, new=1, order=3, zero=0.): """ Generic resampler based on Waring-Lagrange interpolators. Parameters ---------- sig : Input signal (any iterable). old : Time duration reference (defaults to 1, allowing percentages to the ``new`` keyword argument). This can be float number, or perhaps a Stream instance. new : Time duration that the reference will have after resampling. For example, if ``old = 1, new = 2``, then there will be 2 samples yielded for each sample from input. This can be a float number, or perhaps a Stream instance. order : Lagrange interpolator order. The amount of neighboring samples to be used by the interpolator is ``order + 1``. zero : The input should be thought as zero-padded from the left with this value. Returns ------- The first value will be the first sample from ``sig``, and then the interpolator will find the next samples towards the end of the ``sig``. The actual sampling interval (or time step) for this interpolator obeys to the ``old / new`` relationship. Hint ---- The time step can also be time-varying, although that's certainly difficult to synchonize (one sample is needed for each output sample). Perhaps the best approach for this case would be a ControlStream keeping the desired value at any time. Note ---- The input isn't zero-padded at right. It means that the last output will be one with interpolated with known data. For endless inputs that's ok, this makes no difference, but for finite inputs that may be undesirable. """ sig = Stream(sig) threshold = .5 * (order + 1) step = old / new data = deque([zero] * (order + 1), maxlen=order + 1) data.extend(sig.take(rint(threshold))) idx = int(threshold) isig = iter(sig) if isinstance(step, Iterable): step = iter(step) while True: yield lagrange(enumerate(data))(idx) idx += next(step) while idx > threshold: data.append(next(isig)) idx -= 1 else: while True: yield lagrange(enumerate(data))(idx) idx += step while idx > threshold: data.append(next(isig)) idx -= 1
[ "def", "resample", "(", "sig", ",", "old", "=", "1", ",", "new", "=", "1", ",", "order", "=", "3", ",", "zero", "=", "0.", ")", ":", "sig", "=", "Stream", "(", "sig", ")", "threshold", "=", ".5", "*", "(", "order", "+", "1", ")", "step", "=...
Generic resampler based on Waring-Lagrange interpolators. Parameters ---------- sig : Input signal (any iterable). old : Time duration reference (defaults to 1, allowing percentages to the ``new`` keyword argument). This can be float number, or perhaps a Stream instance. new : Time duration that the reference will have after resampling. For example, if ``old = 1, new = 2``, then there will be 2 samples yielded for each sample from input. This can be a float number, or perhaps a Stream instance. order : Lagrange interpolator order. The amount of neighboring samples to be used by the interpolator is ``order + 1``. zero : The input should be thought as zero-padded from the left with this value. Returns ------- The first value will be the first sample from ``sig``, and then the interpolator will find the next samples towards the end of the ``sig``. The actual sampling interval (or time step) for this interpolator obeys to the ``old / new`` relationship. Hint ---- The time step can also be time-varying, although that's certainly difficult to synchonize (one sample is needed for each output sample). Perhaps the best approach for this case would be a ControlStream keeping the desired value at any time. Note ---- The input isn't zero-padded at right. It means that the last output will be one with interpolated with known data. For endless inputs that's ok, this makes no difference, but for finite inputs that may be undesirable.
[ "Generic", "resampler", "based", "on", "Waring", "-", "Lagrange", "interpolators", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_poly.py#L535-L599
train
210,225
danilobellini/audiolazy
audiolazy/lazy_poly.py
Poly.is_polynomial
def is_polynomial(self): """ Tells whether it is a linear combination of natural powers of ``x``. """ return all(isinstance(k, INT_TYPES) and k >= 0 for k in self._data)
python
def is_polynomial(self): """ Tells whether it is a linear combination of natural powers of ``x``. """ return all(isinstance(k, INT_TYPES) and k >= 0 for k in self._data)
[ "def", "is_polynomial", "(", "self", ")", ":", "return", "all", "(", "isinstance", "(", "k", ",", "INT_TYPES", ")", "and", "k", ">=", "0", "for", "k", "in", "self", ".", "_data", ")" ]
Tells whether it is a linear combination of natural powers of ``x``.
[ "Tells", "whether", "it", "is", "a", "linear", "combination", "of", "natural", "powers", "of", "x", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_poly.py#L202-L206
train
210,226
danilobellini/audiolazy
audiolazy/lazy_poly.py
Poly.order
def order(self): """ Finds the polynomial order. Examples -------- >>> (x + 4).order 1 >>> (x + 4 - x ** 18).order 18 >>> (x - x).order 0 >>> (x ** -3 + 4).order Traceback (most recent call last): ... AttributeError: Power needs to be positive integers """ if not self.is_polynomial(): raise AttributeError("Power needs to be positive integers") return max(key for key in self._data) if self._data else 0
python
def order(self): """ Finds the polynomial order. Examples -------- >>> (x + 4).order 1 >>> (x + 4 - x ** 18).order 18 >>> (x - x).order 0 >>> (x ** -3 + 4).order Traceback (most recent call last): ... AttributeError: Power needs to be positive integers """ if not self.is_polynomial(): raise AttributeError("Power needs to be positive integers") return max(key for key in self._data) if self._data else 0
[ "def", "order", "(", "self", ")", ":", "if", "not", "self", ".", "is_polynomial", "(", ")", ":", "raise", "AttributeError", "(", "\"Power needs to be positive integers\"", ")", "return", "max", "(", "key", "for", "key", "in", "self", ".", "_data", ")", "if...
Finds the polynomial order. Examples -------- >>> (x + 4).order 1 >>> (x + 4 - x ** 18).order 18 >>> (x - x).order 0 >>> (x ** -3 + 4).order Traceback (most recent call last): ... AttributeError: Power needs to be positive integers
[ "Finds", "the", "polynomial", "order", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_poly.py#L229-L249
train
210,227
danilobellini/audiolazy
audiolazy/lazy_poly.py
Poly.integrate
def integrate(self): """ Integrate without adding an integration constant. """ if -1 in self._data: raise ValueError("Unable to integrate term that powers to -1") return Poly(OrderedDict((k + 1, v / (k + 1)) for k, v in iteritems(self._data)), zero=self.zero)
python
def integrate(self): """ Integrate without adding an integration constant. """ if -1 in self._data: raise ValueError("Unable to integrate term that powers to -1") return Poly(OrderedDict((k + 1, v / (k + 1)) for k, v in iteritems(self._data)), zero=self.zero)
[ "def", "integrate", "(", "self", ")", ":", "if", "-", "1", "in", "self", ".", "_data", ":", "raise", "ValueError", "(", "\"Unable to integrate term that powers to -1\"", ")", "return", "Poly", "(", "OrderedDict", "(", "(", "k", "+", "1", ",", "v", "/", "...
Integrate without adding an integration constant.
[ "Integrate", "without", "adding", "an", "integration", "constant", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_poly.py#L270-L278
train
210,228
danilobellini/audiolazy
audiolazy/lazy_poly.py
Poly.roots
def roots(self): """ Returns a list with all roots. Needs Numpy. """ import numpy as np return np.roots(list(self.values())[::-1]).tolist()
python
def roots(self): """ Returns a list with all roots. Needs Numpy. """ import numpy as np return np.roots(list(self.values())[::-1]).tolist()
[ "def", "roots", "(", "self", ")", ":", "import", "numpy", "as", "np", "return", "np", ".", "roots", "(", "list", "(", "self", ".", "values", "(", ")", ")", "[", ":", ":", "-", "1", "]", ")", ".", "tolist", "(", ")" ]
Returns a list with all roots. Needs Numpy.
[ "Returns", "a", "list", "with", "all", "roots", ".", "Needs", "Numpy", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_poly.py#L478-L483
train
210,229
danilobellini/audiolazy
audiolazy/lazy_filters.py
_exec_eval
def _exec_eval(data, expr): """ Internal function to isolate an exec. Executes ``data`` and returns the ``expr`` evaluation afterwards. """ ns = {} exec(data, ns) return eval(expr, ns)
python
def _exec_eval(data, expr): """ Internal function to isolate an exec. Executes ``data`` and returns the ``expr`` evaluation afterwards. """ ns = {} exec(data, ns) return eval(expr, ns)
[ "def", "_exec_eval", "(", "data", ",", "expr", ")", ":", "ns", "=", "{", "}", "exec", "(", "data", ",", "ns", ")", "return", "eval", "(", "expr", ",", "ns", ")" ]
Internal function to isolate an exec. Executes ``data`` and returns the ``expr`` evaluation afterwards.
[ "Internal", "function", "to", "isolate", "an", "exec", ".", "Executes", "data", "and", "returns", "the", "expr", "evaluation", "afterwards", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_filters.py#L94-L102
train
210,230
danilobellini/audiolazy
audiolazy/lazy_filters.py
highpass
def highpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the one-pole Laplace lowpass filter and mirroring the resulting filter to get a highpass. """ R = thub(exp(cutoff - pi), 2) return (1 - R) / (1 + R * z ** -1)
python
def highpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the one-pole Laplace lowpass filter and mirroring the resulting filter to get a highpass. """ R = thub(exp(cutoff - pi), 2) return (1 - R) / (1 + R * z ** -1)
[ "def", "highpass", "(", "cutoff", ")", ":", "R", "=", "thub", "(", "exp", "(", "cutoff", "-", "pi", ")", ",", "2", ")", "return", "(", "1", "-", "R", ")", "/", "(", "1", "+", "R", "*", "z", "**", "-", "1", ")" ]
This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the one-pole Laplace lowpass filter and mirroring the resulting filter to get a highpass.
[ "This", "strategy", "uses", "an", "exponential", "approximation", "for", "cut", "-", "off", "frequency", "calculation", "found", "by", "matching", "the", "one", "-", "pole", "Laplace", "lowpass", "filter", "and", "mirroring", "the", "resulting", "filter", "to", ...
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_filters.py#L1443-L1450
train
210,231
danilobellini/audiolazy
audiolazy/lazy_filters.py
lowpass
def lowpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the single pole and single zero Laplace highpass filter and mirroring the resulting filter to get a lowpass. """ R = thub(exp(cutoff - pi), 2) G = (R + 1) / 2 return G * (1 + z ** -1) / (1 + R * z ** -1)
python
def lowpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the single pole and single zero Laplace highpass filter and mirroring the resulting filter to get a lowpass. """ R = thub(exp(cutoff - pi), 2) G = (R + 1) / 2 return G * (1 + z ** -1) / (1 + R * z ** -1)
[ "def", "lowpass", "(", "cutoff", ")", ":", "R", "=", "thub", "(", "exp", "(", "cutoff", "-", "pi", ")", ",", "2", ")", "G", "=", "(", "R", "+", "1", ")", "/", "2", "return", "G", "*", "(", "1", "+", "z", "**", "-", "1", ")", "/", "(", ...
This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the single pole and single zero Laplace highpass filter and mirroring the resulting filter to get a lowpass.
[ "This", "strategy", "uses", "an", "exponential", "approximation", "for", "cut", "-", "off", "frequency", "calculation", "found", "by", "matching", "the", "single", "pole", "and", "single", "zero", "Laplace", "highpass", "filter", "and", "mirroring", "the", "resu...
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_filters.py#L1460-L1468
train
210,232
danilobellini/audiolazy
audiolazy/lazy_filters.py
highpass
def highpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the single pole and single zero Laplace highpass filter. """ R = thub(exp(-cutoff), 2) G = (R + 1) / 2 return G * (1 - z ** -1) / (1 - R * z ** -1)
python
def highpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the single pole and single zero Laplace highpass filter. """ R = thub(exp(-cutoff), 2) G = (R + 1) / 2 return G * (1 - z ** -1) / (1 - R * z ** -1)
[ "def", "highpass", "(", "cutoff", ")", ":", "R", "=", "thub", "(", "exp", "(", "-", "cutoff", ")", ",", "2", ")", "G", "=", "(", "R", "+", "1", ")", "/", "2", "return", "G", "*", "(", "1", "-", "z", "**", "-", "1", ")", "/", "(", "1", ...
This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the single pole and single zero Laplace highpass filter.
[ "This", "strategy", "uses", "an", "exponential", "approximation", "for", "cut", "-", "off", "frequency", "calculation", "found", "by", "matching", "the", "single", "pole", "and", "single", "zero", "Laplace", "highpass", "filter", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_filters.py#L1478-L1486
train
210,233
danilobellini/audiolazy
audiolazy/lazy_filters.py
FilterList.is_linear
def is_linear(self): """ Tests whether all filters in the list are linear. CascadeFilter and ParallelFilter instances are also linear if all filters they group are linear. """ return all(isinstance(filt, LinearFilter) or (hasattr(filt, "is_linear") and filt.is_linear()) for filt in self.callables)
python
def is_linear(self): """ Tests whether all filters in the list are linear. CascadeFilter and ParallelFilter instances are also linear if all filters they group are linear. """ return all(isinstance(filt, LinearFilter) or (hasattr(filt, "is_linear") and filt.is_linear()) for filt in self.callables)
[ "def", "is_linear", "(", "self", ")", ":", "return", "all", "(", "isinstance", "(", "filt", ",", "LinearFilter", ")", "or", "(", "hasattr", "(", "filt", ",", "\"is_linear\"", ")", "and", "filt", ".", "is_linear", "(", ")", ")", "for", "filt", "in", "...
Tests whether all filters in the list are linear. CascadeFilter and ParallelFilter instances are also linear if all filters they group are linear.
[ "Tests", "whether", "all", "filters", "in", "the", "list", "are", "linear", ".", "CascadeFilter", "and", "ParallelFilter", "instances", "are", "also", "linear", "if", "all", "filters", "they", "group", "are", "linear", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_filters.py#L916-L925
train
210,234
danilobellini/audiolazy
audiolazy/lazy_auditory.py
erb
def erb(freq, Hz=None): """ ``B. C. J. Moore and B. R. Glasberg, "Suggested formulae for calculating auditory filter bandwidths and excitation patterns". J. Acoust. Soc. Am., 74, 1983, pp. 750-753.`` """ if Hz is None: if freq < 7: # Perhaps user tried something up to 2 * pi raise ValueError("Frequency out of range.") Hz = 1 fHz = freq / Hz result = 6.23e-6 * fHz ** 2 + 93.39e-3 * fHz + 28.52 return result * Hz
python
def erb(freq, Hz=None): """ ``B. C. J. Moore and B. R. Glasberg, "Suggested formulae for calculating auditory filter bandwidths and excitation patterns". J. Acoust. Soc. Am., 74, 1983, pp. 750-753.`` """ if Hz is None: if freq < 7: # Perhaps user tried something up to 2 * pi raise ValueError("Frequency out of range.") Hz = 1 fHz = freq / Hz result = 6.23e-6 * fHz ** 2 + 93.39e-3 * fHz + 28.52 return result * Hz
[ "def", "erb", "(", "freq", ",", "Hz", "=", "None", ")", ":", "if", "Hz", "is", "None", ":", "if", "freq", "<", "7", ":", "# Perhaps user tried something up to 2 * pi", "raise", "ValueError", "(", "\"Frequency out of range.\"", ")", "Hz", "=", "1", "fHz", "...
``B. C. J. Moore and B. R. Glasberg, "Suggested formulae for calculating auditory filter bandwidths and excitation patterns". J. Acoust. Soc. Am., 74, 1983, pp. 750-753.``
[ "B", ".", "C", ".", "J", ".", "Moore", "and", "B", ".", "R", ".", "Glasberg", "Suggested", "formulae", "for", "calculating", "auditory", "filter", "bandwidths", "and", "excitation", "patterns", ".", "J", ".", "Acoust", ".", "Soc", ".", "Am", ".", "74",...
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_auditory.py#L76-L88
train
210,235
danilobellini/audiolazy
audiolazy/lazy_auditory.py
gammatone
def gammatone(freq, bandwidth): """ ``A. Klapuri, "Multipich Analysis of Polyphonic Music and Speech Signals Using an Auditory Model". IEEE Transactions on Audio, Speech and Language Processing, vol. 16, no. 2, 2008, pp. 255-266.`` """ bw = thub(bandwidth, 1) bw2 = thub(bw * 2, 4) freq = thub(freq, 4) resons = [resonator.z_exp, resonator.poles_exp] * 2 return CascadeFilter(reson(freq, bw2) for reson in resons)
python
def gammatone(freq, bandwidth): """ ``A. Klapuri, "Multipich Analysis of Polyphonic Music and Speech Signals Using an Auditory Model". IEEE Transactions on Audio, Speech and Language Processing, vol. 16, no. 2, 2008, pp. 255-266.`` """ bw = thub(bandwidth, 1) bw2 = thub(bw * 2, 4) freq = thub(freq, 4) resons = [resonator.z_exp, resonator.poles_exp] * 2 return CascadeFilter(reson(freq, bw2) for reson in resons)
[ "def", "gammatone", "(", "freq", ",", "bandwidth", ")", ":", "bw", "=", "thub", "(", "bandwidth", ",", "1", ")", "bw2", "=", "thub", "(", "bw", "*", "2", ",", "4", ")", "freq", "=", "thub", "(", "freq", ",", "4", ")", "resons", "=", "[", "res...
``A. Klapuri, "Multipich Analysis of Polyphonic Music and Speech Signals Using an Auditory Model". IEEE Transactions on Audio, Speech and Language Processing, vol. 16, no. 2, 2008, pp. 255-266.``
[ "A", ".", "Klapuri", "Multipich", "Analysis", "of", "Polyphonic", "Music", "and", "Speech", "Signals", "Using", "an", "Auditory", "Model", ".", "IEEE", "Transactions", "on", "Audio", "Speech", "and", "Language", "Processing", "vol", ".", "16", "no", ".", "2"...
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_auditory.py#L208-L218
train
210,236
danilobellini/audiolazy
audiolazy/lazy_analysis.py
_generate_window_strategies
def _generate_window_strategies(): """ Create all window and wsymm strategies """ for wnd_dict in window._content_generation_table: names = wnd_dict["names"] sname = wnd_dict["sname"] = names[0] wnd_dict.setdefault("params_def", "") for sdict in [window, wsymm]: docs_dict = window._doc_kwargs(symm = sdict is wsymm, **wnd_dict) decorators = [format_docstring(**docs_dict), sdict.strategy(*names)] ns = dict(pi=pi, sin=sin, cos=cos, xrange=xrange, __name__=__name__) exec(sdict._code_template.format(**wnd_dict), ns, ns) reduce(lambda func, dec: dec(func), decorators, ns[sname]) if not wnd_dict.get("distinct", True): wsymm[sname] = window[sname] break wsymm[sname].periodic = window[sname].periodic = window[sname] wsymm[sname].symm = window[sname].symm = wsymm[sname]
python
def _generate_window_strategies(): """ Create all window and wsymm strategies """ for wnd_dict in window._content_generation_table: names = wnd_dict["names"] sname = wnd_dict["sname"] = names[0] wnd_dict.setdefault("params_def", "") for sdict in [window, wsymm]: docs_dict = window._doc_kwargs(symm = sdict is wsymm, **wnd_dict) decorators = [format_docstring(**docs_dict), sdict.strategy(*names)] ns = dict(pi=pi, sin=sin, cos=cos, xrange=xrange, __name__=__name__) exec(sdict._code_template.format(**wnd_dict), ns, ns) reduce(lambda func, dec: dec(func), decorators, ns[sname]) if not wnd_dict.get("distinct", True): wsymm[sname] = window[sname] break wsymm[sname].periodic = window[sname].periodic = window[sname] wsymm[sname].symm = window[sname].symm = wsymm[sname]
[ "def", "_generate_window_strategies", "(", ")", ":", "for", "wnd_dict", "in", "window", ".", "_content_generation_table", ":", "names", "=", "wnd_dict", "[", "\"names\"", "]", "sname", "=", "wnd_dict", "[", "\"sname\"", "]", "=", "names", "[", "0", "]", "wnd...
Create all window and wsymm strategies
[ "Create", "all", "window", "and", "wsymm", "strategies" ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L252-L268
train
210,237
danilobellini/audiolazy
audiolazy/lazy_analysis.py
acorr
def acorr(blk, max_lag=None): """ Calculate the autocorrelation of a given 1-D block sequence. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! max_lag : The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``, since any lag beyond would result in zero. Returns ------- A list with lags from 0 up to max_lag, where its ``i``-th element has the autocorrelation for a lag equals to ``i``. Be careful with negative lags! You should use abs(lag) indexes when working with them. Examples -------- >>> seq = [1, 2, 3, 4, 3, 4, 2] >>> acorr(seq) # Default max_lag is len(seq) - 1 [59, 52, 42, 30, 17, 8, 2] >>> acorr(seq, 9) # Zeros at the end [59, 52, 42, 30, 17, 8, 2, 0, 0, 0] >>> len(acorr(seq, 3)) # Resulting length is max_lag + 1 4 >>> acorr(seq, 3) [59, 52, 42, 30] """ if max_lag is None: max_lag = len(blk) - 1 return [sum(blk[n] * blk[n + tau] for n in xrange(len(blk) - tau)) for tau in xrange(max_lag + 1)]
python
def acorr(blk, max_lag=None): """ Calculate the autocorrelation of a given 1-D block sequence. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! max_lag : The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``, since any lag beyond would result in zero. Returns ------- A list with lags from 0 up to max_lag, where its ``i``-th element has the autocorrelation for a lag equals to ``i``. Be careful with negative lags! You should use abs(lag) indexes when working with them. Examples -------- >>> seq = [1, 2, 3, 4, 3, 4, 2] >>> acorr(seq) # Default max_lag is len(seq) - 1 [59, 52, 42, 30, 17, 8, 2] >>> acorr(seq, 9) # Zeros at the end [59, 52, 42, 30, 17, 8, 2, 0, 0, 0] >>> len(acorr(seq, 3)) # Resulting length is max_lag + 1 4 >>> acorr(seq, 3) [59, 52, 42, 30] """ if max_lag is None: max_lag = len(blk) - 1 return [sum(blk[n] * blk[n + tau] for n in xrange(len(blk) - tau)) for tau in xrange(max_lag + 1)]
[ "def", "acorr", "(", "blk", ",", "max_lag", "=", "None", ")", ":", "if", "max_lag", "is", "None", ":", "max_lag", "=", "len", "(", "blk", ")", "-", "1", "return", "[", "sum", "(", "blk", "[", "n", "]", "*", "blk", "[", "n", "+", "tau", "]", ...
Calculate the autocorrelation of a given 1-D block sequence. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! max_lag : The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``, since any lag beyond would result in zero. Returns ------- A list with lags from 0 up to max_lag, where its ``i``-th element has the autocorrelation for a lag equals to ``i``. Be careful with negative lags! You should use abs(lag) indexes when working with them. Examples -------- >>> seq = [1, 2, 3, 4, 3, 4, 2] >>> acorr(seq) # Default max_lag is len(seq) - 1 [59, 52, 42, 30, 17, 8, 2] >>> acorr(seq, 9) # Zeros at the end [59, 52, 42, 30, 17, 8, 2, 0, 0, 0] >>> len(acorr(seq, 3)) # Resulting length is max_lag + 1 4 >>> acorr(seq, 3) [59, 52, 42, 30]
[ "Calculate", "the", "autocorrelation", "of", "a", "given", "1", "-", "D", "block", "sequence", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L273-L308
train
210,238
danilobellini/audiolazy
audiolazy/lazy_analysis.py
lag_matrix
def lag_matrix(blk, max_lag=None): """ Finds the lag matrix for a given 1-D block sequence. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! max_lag : The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``, the maximum lag that doesn't create fully zeroed matrices. Returns ------- The covariance matrix as a list of lists. Each cell (i, j) contains the sum of ``blk[n - i] * blk[n - j]`` elements for all n that allows such without padding the given block. """ if max_lag is None: max_lag = len(blk) - 1 elif max_lag >= len(blk): raise ValueError("Block length should be higher than order") return [[sum(blk[n - i] * blk[n - j] for n in xrange(max_lag, len(blk)) ) for i in xrange(max_lag + 1) ] for j in xrange(max_lag + 1)]
python
def lag_matrix(blk, max_lag=None): """ Finds the lag matrix for a given 1-D block sequence. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! max_lag : The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``, the maximum lag that doesn't create fully zeroed matrices. Returns ------- The covariance matrix as a list of lists. Each cell (i, j) contains the sum of ``blk[n - i] * blk[n - j]`` elements for all n that allows such without padding the given block. """ if max_lag is None: max_lag = len(blk) - 1 elif max_lag >= len(blk): raise ValueError("Block length should be higher than order") return [[sum(blk[n - i] * blk[n - j] for n in xrange(max_lag, len(blk)) ) for i in xrange(max_lag + 1) ] for j in xrange(max_lag + 1)]
[ "def", "lag_matrix", "(", "blk", ",", "max_lag", "=", "None", ")", ":", "if", "max_lag", "is", "None", ":", "max_lag", "=", "len", "(", "blk", ")", "-", "1", "elif", "max_lag", ">=", "len", "(", "blk", ")", ":", "raise", "ValueError", "(", "\"Block...
Finds the lag matrix for a given 1-D block sequence. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! max_lag : The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``, the maximum lag that doesn't create fully zeroed matrices. Returns ------- The covariance matrix as a list of lists. Each cell (i, j) contains the sum of ``blk[n - i] * blk[n - j]`` elements for all n that allows such without padding the given block.
[ "Finds", "the", "lag", "matrix", "for", "a", "given", "1", "-", "D", "block", "sequence", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L311-L338
train
210,239
danilobellini/audiolazy
audiolazy/lazy_analysis.py
dft
def dft(blk, freqs, normalize=True): """ Complex non-optimized Discrete Fourier Transform Finds the DFT for values in a given frequency list, in order, over the data block seen as periodic. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! freqs : List of frequencies to find the DFT, in rad/sample. FFT implementations like numpy.fft.ftt finds the coefficients for N frequencies equally spaced as ``line(N, 0, 2 * pi, finish=False)`` for N frequencies. normalize : If True (default), the coefficient sums are divided by ``len(blk)``, and the coefficient for the DC level (frequency equals to zero) is the mean of the block. If False, that coefficient would be the sum of the data in the block. Returns ------- A list of DFT values for each frequency, in the same order that they appear in the freqs input. Note ---- This isn't a FFT implementation, and performs :math:`O(M . N)` float pointing operations, with :math:`M` and :math:`N` equals to the length of the inputs. This function can find the DFT for any specific frequency, with no need for zero padding or finding all frequencies in a linearly spaced band grid with N frequency bins at once. """ dft_data = (sum(xn * cexp(-1j * n * f) for n, xn in enumerate(blk)) for f in freqs) if normalize: lblk = len(blk) return [v / lblk for v in dft_data] return list(dft_data)
python
def dft(blk, freqs, normalize=True): """ Complex non-optimized Discrete Fourier Transform Finds the DFT for values in a given frequency list, in order, over the data block seen as periodic. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! freqs : List of frequencies to find the DFT, in rad/sample. FFT implementations like numpy.fft.ftt finds the coefficients for N frequencies equally spaced as ``line(N, 0, 2 * pi, finish=False)`` for N frequencies. normalize : If True (default), the coefficient sums are divided by ``len(blk)``, and the coefficient for the DC level (frequency equals to zero) is the mean of the block. If False, that coefficient would be the sum of the data in the block. Returns ------- A list of DFT values for each frequency, in the same order that they appear in the freqs input. Note ---- This isn't a FFT implementation, and performs :math:`O(M . N)` float pointing operations, with :math:`M` and :math:`N` equals to the length of the inputs. This function can find the DFT for any specific frequency, with no need for zero padding or finding all frequencies in a linearly spaced band grid with N frequency bins at once. """ dft_data = (sum(xn * cexp(-1j * n * f) for n, xn in enumerate(blk)) for f in freqs) if normalize: lblk = len(blk) return [v / lblk for v in dft_data] return list(dft_data)
[ "def", "dft", "(", "blk", ",", "freqs", ",", "normalize", "=", "True", ")", ":", "dft_data", "=", "(", "sum", "(", "xn", "*", "cexp", "(", "-", "1j", "*", "n", "*", "f", ")", "for", "n", ",", "xn", "in", "enumerate", "(", "blk", ")", ")", "...
Complex non-optimized Discrete Fourier Transform Finds the DFT for values in a given frequency list, in order, over the data block seen as periodic. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! freqs : List of frequencies to find the DFT, in rad/sample. FFT implementations like numpy.fft.ftt finds the coefficients for N frequencies equally spaced as ``line(N, 0, 2 * pi, finish=False)`` for N frequencies. normalize : If True (default), the coefficient sums are divided by ``len(blk)``, and the coefficient for the DC level (frequency equals to zero) is the mean of the block. If False, that coefficient would be the sum of the data in the block. Returns ------- A list of DFT values for each frequency, in the same order that they appear in the freqs input. Note ---- This isn't a FFT implementation, and performs :math:`O(M . N)` float pointing operations, with :math:`M` and :math:`N` equals to the length of the inputs. This function can find the DFT for any specific frequency, with no need for zero padding or finding all frequencies in a linearly spaced band grid with N frequency bins at once.
[ "Complex", "non", "-", "optimized", "Discrete", "Fourier", "Transform" ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L341-L382
train
210,240
danilobellini/audiolazy
audiolazy/lazy_analysis.py
zcross
def zcross(seq, hysteresis=0, first_sign=0): """ Zero-crossing stream. Parameters ---------- seq : Any iterable to be used as input for the zero crossing analysis hysteresis : Crossing exactly zero might happen many times too fast due to high frequency oscilations near zero. To avoid this, you can make two threshold limits for the zero crossing detection: ``hysteresis`` and ``-hysteresis``. Defaults to zero (0), which means no hysteresis and only one threshold. first_sign : Optional argument with the sign memory from past. Gets the sig from any signed number. Defaults to zero (0), which means "any", and the first sign will be the first one found in data. Returns ------- A Stream instance that outputs 1 for each crossing detected, 0 otherwise. """ neg_hyst = -hysteresis seq_iter = iter(seq) # Gets the first sign if first_sign == 0: last_sign = 0 for el in seq_iter: yield 0 if (el > hysteresis) or (el < neg_hyst): # Ignores hysteresis region last_sign = -1 if el < 0 else 1 # Define the first sign break else: last_sign = -1 if first_sign < 0 else 1 # Finds the full zero-crossing sequence for el in seq_iter: # Keep the same iterator (needed for non-generators) if el * last_sign < neg_hyst: last_sign = -1 if el < 0 else 1 yield 1 else: yield 0
python
def zcross(seq, hysteresis=0, first_sign=0): """ Zero-crossing stream. Parameters ---------- seq : Any iterable to be used as input for the zero crossing analysis hysteresis : Crossing exactly zero might happen many times too fast due to high frequency oscilations near zero. To avoid this, you can make two threshold limits for the zero crossing detection: ``hysteresis`` and ``-hysteresis``. Defaults to zero (0), which means no hysteresis and only one threshold. first_sign : Optional argument with the sign memory from past. Gets the sig from any signed number. Defaults to zero (0), which means "any", and the first sign will be the first one found in data. Returns ------- A Stream instance that outputs 1 for each crossing detected, 0 otherwise. """ neg_hyst = -hysteresis seq_iter = iter(seq) # Gets the first sign if first_sign == 0: last_sign = 0 for el in seq_iter: yield 0 if (el > hysteresis) or (el < neg_hyst): # Ignores hysteresis region last_sign = -1 if el < 0 else 1 # Define the first sign break else: last_sign = -1 if first_sign < 0 else 1 # Finds the full zero-crossing sequence for el in seq_iter: # Keep the same iterator (needed for non-generators) if el * last_sign < neg_hyst: last_sign = -1 if el < 0 else 1 yield 1 else: yield 0
[ "def", "zcross", "(", "seq", ",", "hysteresis", "=", "0", ",", "first_sign", "=", "0", ")", ":", "neg_hyst", "=", "-", "hysteresis", "seq_iter", "=", "iter", "(", "seq", ")", "# Gets the first sign", "if", "first_sign", "==", "0", ":", "last_sign", "=", ...
Zero-crossing stream. Parameters ---------- seq : Any iterable to be used as input for the zero crossing analysis hysteresis : Crossing exactly zero might happen many times too fast due to high frequency oscilations near zero. To avoid this, you can make two threshold limits for the zero crossing detection: ``hysteresis`` and ``-hysteresis``. Defaults to zero (0), which means no hysteresis and only one threshold. first_sign : Optional argument with the sign memory from past. Gets the sig from any signed number. Defaults to zero (0), which means "any", and the first sign will be the first one found in data. Returns ------- A Stream instance that outputs 1 for each crossing detected, 0 otherwise.
[ "Zero", "-", "crossing", "stream", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L386-L430
train
210,241
danilobellini/audiolazy
audiolazy/lazy_analysis.py
clip
def clip(sig, low=-1., high=1.): """ Clips the signal up to both a lower and a higher limit. Parameters ---------- sig : The signal to be clipped, be it a Stream instance, a list or any iterable. low, high : Lower and higher clipping limit, "saturating" the input to them. Defaults to -1.0 and 1.0, respectively. These can be None when needed one-sided clipping. When both limits are set to None, the output will be a Stream that yields exactly the ``sig`` input data. Returns ------- Clipped signal as a Stream instance. """ if low is None: if high is None: return Stream(sig) return Stream(el if el < high else high for el in sig) if high is None: return Stream(el if el > low else low for el in sig) if high < low: raise ValueError("Higher clipping limit is smaller than lower one") return Stream(high if el > high else (low if el < low else el) for el in sig)
python
def clip(sig, low=-1., high=1.): """ Clips the signal up to both a lower and a higher limit. Parameters ---------- sig : The signal to be clipped, be it a Stream instance, a list or any iterable. low, high : Lower and higher clipping limit, "saturating" the input to them. Defaults to -1.0 and 1.0, respectively. These can be None when needed one-sided clipping. When both limits are set to None, the output will be a Stream that yields exactly the ``sig`` input data. Returns ------- Clipped signal as a Stream instance. """ if low is None: if high is None: return Stream(sig) return Stream(el if el < high else high for el in sig) if high is None: return Stream(el if el > low else low for el in sig) if high < low: raise ValueError("Higher clipping limit is smaller than lower one") return Stream(high if el > high else (low if el < low else el) for el in sig)
[ "def", "clip", "(", "sig", ",", "low", "=", "-", "1.", ",", "high", "=", "1.", ")", ":", "if", "low", "is", "None", ":", "if", "high", "is", "None", ":", "return", "Stream", "(", "sig", ")", "return", "Stream", "(", "el", "if", "el", "<", "hi...
Clips the signal up to both a lower and a higher limit. Parameters ---------- sig : The signal to be clipped, be it a Stream instance, a list or any iterable. low, high : Lower and higher clipping limit, "saturating" the input to them. Defaults to -1.0 and 1.0, respectively. These can be None when needed one-sided clipping. When both limits are set to None, the output will be a Stream that yields exactly the ``sig`` input data. Returns ------- Clipped signal as a Stream instance.
[ "Clips", "the", "signal", "up", "to", "both", "a", "lower", "and", "a", "higher", "limit", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L615-L643
train
210,242
danilobellini/audiolazy
audiolazy/lazy_analysis.py
unwrap
def unwrap(sig, max_delta=pi, step=2*pi): """ Parametrized signal unwrapping. Parameters ---------- sig : An iterable seen as an input signal. max_delta : Maximum value of :math:`\Delta = sig_i - sig_{i-1}` to keep output without another minimizing step change. Defaults to :math:`\pi`. step : The change in order to minimize the delta is an integer multiple of this value. Defaults to :math:`2 . \pi`. Returns ------- The signal unwrapped as a Stream, minimizing the step difference when any adjacency step in the input signal is higher than ``max_delta`` by summing/subtracting ``step``. """ idata = iter(sig) d0 = next(idata) yield d0 delta = d0 - d0 # Get the zero (e.g., integer, float) from data for d1 in idata: d_diff = d1 - d0 if abs(d_diff) > max_delta: delta += - d_diff + min((d_diff) % step, (d_diff) % -step, key=lambda x: abs(x)) yield d1 + delta d0 = d1
python
def unwrap(sig, max_delta=pi, step=2*pi): """ Parametrized signal unwrapping. Parameters ---------- sig : An iterable seen as an input signal. max_delta : Maximum value of :math:`\Delta = sig_i - sig_{i-1}` to keep output without another minimizing step change. Defaults to :math:`\pi`. step : The change in order to minimize the delta is an integer multiple of this value. Defaults to :math:`2 . \pi`. Returns ------- The signal unwrapped as a Stream, minimizing the step difference when any adjacency step in the input signal is higher than ``max_delta`` by summing/subtracting ``step``. """ idata = iter(sig) d0 = next(idata) yield d0 delta = d0 - d0 # Get the zero (e.g., integer, float) from data for d1 in idata: d_diff = d1 - d0 if abs(d_diff) > max_delta: delta += - d_diff + min((d_diff) % step, (d_diff) % -step, key=lambda x: abs(x)) yield d1 + delta d0 = d1
[ "def", "unwrap", "(", "sig", ",", "max_delta", "=", "pi", ",", "step", "=", "2", "*", "pi", ")", ":", "idata", "=", "iter", "(", "sig", ")", "d0", "=", "next", "(", "idata", ")", "yield", "d0", "delta", "=", "d0", "-", "d0", "# Get the zero (e.g....
Parametrized signal unwrapping. Parameters ---------- sig : An iterable seen as an input signal. max_delta : Maximum value of :math:`\Delta = sig_i - sig_{i-1}` to keep output without another minimizing step change. Defaults to :math:`\pi`. step : The change in order to minimize the delta is an integer multiple of this value. Defaults to :math:`2 . \pi`. Returns ------- The signal unwrapped as a Stream, minimizing the step difference when any adjacency step in the input signal is higher than ``max_delta`` by summing/subtracting ``step``.
[ "Parametrized", "signal", "unwrapping", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L647-L679
train
210,243
danilobellini/audiolazy
audiolazy/lazy_analysis.py
amdf
def amdf(lag, size): """ Average Magnitude Difference Function non-linear filter for a given size and a fixed lag. Parameters ---------- lag : Time lag, in samples. See ``freq2lag`` if needs conversion from frequency values. size : Moving average size. Returns ------- A callable that accepts two parameters: a signal ``sig`` and the starting memory element ``zero`` that behaves like the ``LinearFilter.__call__`` arguments. The output from that callable is a Stream instance, and has no decimation applied. See Also -------- freq2lag : Frequency (in rad/sample) to lag (in samples) converter. """ filt = (1 - z ** -lag).linearize() @tostream def amdf_filter(sig, zero=0.): return maverage(size)(abs(filt(sig, zero=zero)), zero=zero) return amdf_filter
python
def amdf(lag, size): """ Average Magnitude Difference Function non-linear filter for a given size and a fixed lag. Parameters ---------- lag : Time lag, in samples. See ``freq2lag`` if needs conversion from frequency values. size : Moving average size. Returns ------- A callable that accepts two parameters: a signal ``sig`` and the starting memory element ``zero`` that behaves like the ``LinearFilter.__call__`` arguments. The output from that callable is a Stream instance, and has no decimation applied. See Also -------- freq2lag : Frequency (in rad/sample) to lag (in samples) converter. """ filt = (1 - z ** -lag).linearize() @tostream def amdf_filter(sig, zero=0.): return maverage(size)(abs(filt(sig, zero=zero)), zero=zero) return amdf_filter
[ "def", "amdf", "(", "lag", ",", "size", ")", ":", "filt", "=", "(", "1", "-", "z", "**", "-", "lag", ")", ".", "linearize", "(", ")", "@", "tostream", "def", "amdf_filter", "(", "sig", ",", "zero", "=", "0.", ")", ":", "return", "maverage", "("...
Average Magnitude Difference Function non-linear filter for a given size and a fixed lag. Parameters ---------- lag : Time lag, in samples. See ``freq2lag`` if needs conversion from frequency values. size : Moving average size. Returns ------- A callable that accepts two parameters: a signal ``sig`` and the starting memory element ``zero`` that behaves like the ``LinearFilter.__call__`` arguments. The output from that callable is a Stream instance, and has no decimation applied. See Also -------- freq2lag : Frequency (in rad/sample) to lag (in samples) converter.
[ "Average", "Magnitude", "Difference", "Function", "non", "-", "linear", "filter", "for", "a", "given", "size", "and", "a", "fixed", "lag", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L682-L714
train
210,244
danilobellini/audiolazy
audiolazy/lazy_analysis.py
overlap_add
def overlap_add(blk_sig, size=None, hop=None, wnd=None, normalize=True): """ Overlap-add algorithm using Numpy arrays. Parameters ---------- blk_sig : An iterable of blocks (sequences), such as the ``Stream.blocks`` result. size : Block size for each ``blk_sig`` element, in samples. hop : Number of samples for two adjacent blocks (defaults to the size). wnd : Windowing function to be applied to each block or any iterable with exactly ``size`` elements. If ``None`` (default), applies a rectangular window. normalize : Flag whether the window should be normalized so that the process could happen in the [-1; 1] range, dividing the window by its hop gain. Default is ``True``. Returns ------- A Stream instance with the blocks overlapped and added. See Also -------- Stream.blocks : Splits the Stream instance into blocks with given size and hop. blocks : Same to Stream.blocks but for without using the Stream class. chain : Lazily joins all iterables given as parameters. chain.from_iterable : Same to ``chain(*data)``, but the ``data`` evaluation is lazy. window : Window/apodization/tapering functions for a given size as a StrategyDict. Note ---- Each block has the window function applied to it and the result is the sum of the blocks without any edge-case special treatment for the first and last few blocks. """ import numpy as np # Finds the size from data, if needed if size is None: blk_sig = Stream(blk_sig) size = len(blk_sig.peek()) if hop is None: hop = size # Find the right windowing function to be applied if wnd is None: wnd = np.ones(size) elif callable(wnd) and not isinstance(wnd, Stream): wnd = wnd(size) if isinstance(wnd, Sequence): wnd = np.array(wnd) elif isinstance(wnd, Iterable): wnd = np.hstack(wnd) else: raise TypeError("Window should be an iterable or a callable") # Normalization to the [-1; 1] range if normalize: steps = Stream(wnd).blocks(hop).map(np.array) gain = np.sum(np.abs(np.vstack(steps)), 0).max() if gain: # If gain is zero, normalization couldn't have any effect wnd = wnd / gain # Can't use "/=" nor "*=" as Numpy would keep datatype # Overlap-add algorithm old = np.zeros(size) for blk in (wnd * blk for blk in blk_sig): blk[:-hop] += old[hop:] for el in blk[:hop]: yield el old = blk for el in old[hop:]: # No more blocks, finish yielding the last one yield el
python
def overlap_add(blk_sig, size=None, hop=None, wnd=None, normalize=True): """ Overlap-add algorithm using Numpy arrays. Parameters ---------- blk_sig : An iterable of blocks (sequences), such as the ``Stream.blocks`` result. size : Block size for each ``blk_sig`` element, in samples. hop : Number of samples for two adjacent blocks (defaults to the size). wnd : Windowing function to be applied to each block or any iterable with exactly ``size`` elements. If ``None`` (default), applies a rectangular window. normalize : Flag whether the window should be normalized so that the process could happen in the [-1; 1] range, dividing the window by its hop gain. Default is ``True``. Returns ------- A Stream instance with the blocks overlapped and added. See Also -------- Stream.blocks : Splits the Stream instance into blocks with given size and hop. blocks : Same to Stream.blocks but for without using the Stream class. chain : Lazily joins all iterables given as parameters. chain.from_iterable : Same to ``chain(*data)``, but the ``data`` evaluation is lazy. window : Window/apodization/tapering functions for a given size as a StrategyDict. Note ---- Each block has the window function applied to it and the result is the sum of the blocks without any edge-case special treatment for the first and last few blocks. """ import numpy as np # Finds the size from data, if needed if size is None: blk_sig = Stream(blk_sig) size = len(blk_sig.peek()) if hop is None: hop = size # Find the right windowing function to be applied if wnd is None: wnd = np.ones(size) elif callable(wnd) and not isinstance(wnd, Stream): wnd = wnd(size) if isinstance(wnd, Sequence): wnd = np.array(wnd) elif isinstance(wnd, Iterable): wnd = np.hstack(wnd) else: raise TypeError("Window should be an iterable or a callable") # Normalization to the [-1; 1] range if normalize: steps = Stream(wnd).blocks(hop).map(np.array) gain = np.sum(np.abs(np.vstack(steps)), 0).max() if gain: # If gain is zero, normalization couldn't have any effect wnd = wnd / gain # Can't use "/=" nor "*=" as Numpy would keep datatype # Overlap-add algorithm old = np.zeros(size) for blk in (wnd * blk for blk in blk_sig): blk[:-hop] += old[hop:] for el in blk[:hop]: yield el old = blk for el in old[hop:]: # No more blocks, finish yielding the last one yield el
[ "def", "overlap_add", "(", "blk_sig", ",", "size", "=", "None", ",", "hop", "=", "None", ",", "wnd", "=", "None", ",", "normalize", "=", "True", ")", ":", "import", "numpy", "as", "np", "# Finds the size from data, if needed", "if", "size", "is", "None", ...
Overlap-add algorithm using Numpy arrays. Parameters ---------- blk_sig : An iterable of blocks (sequences), such as the ``Stream.blocks`` result. size : Block size for each ``blk_sig`` element, in samples. hop : Number of samples for two adjacent blocks (defaults to the size). wnd : Windowing function to be applied to each block or any iterable with exactly ``size`` elements. If ``None`` (default), applies a rectangular window. normalize : Flag whether the window should be normalized so that the process could happen in the [-1; 1] range, dividing the window by its hop gain. Default is ``True``. Returns ------- A Stream instance with the blocks overlapped and added. See Also -------- Stream.blocks : Splits the Stream instance into blocks with given size and hop. blocks : Same to Stream.blocks but for without using the Stream class. chain : Lazily joins all iterables given as parameters. chain.from_iterable : Same to ``chain(*data)``, but the ``data`` evaluation is lazy. window : Window/apodization/tapering functions for a given size as a StrategyDict. Note ---- Each block has the window function applied to it and the result is the sum of the blocks without any edge-case special treatment for the first and last few blocks.
[ "Overlap", "-", "add", "algorithm", "using", "Numpy", "arrays", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L722-L802
train
210,245
danilobellini/audiolazy
audiolazy/lazy_analysis.py
overlap_add
def overlap_add(blk_sig, size=None, hop=None, wnd=None, normalize=True): """ Overlap-add algorithm using lists instead of Numpy arrays. The behavior is the same to the ``overlap_add.numpy`` strategy, besides the data types. """ # Finds the size from data, if needed if size is None: blk_sig = Stream(blk_sig) size = len(blk_sig.peek()) if hop is None: hop = size # Find the window to be applied, resulting on a list or None if wnd is not None: if callable(wnd) and not isinstance(wnd, Stream): wnd = wnd(size) if isinstance(wnd, Iterable): wnd = list(wnd) else: raise TypeError("Window should be an iterable or a callable") # Normalization to the [-1; 1] range if normalize: if wnd: steps = Stream(wnd).map(abs).blocks(hop).map(tuple) gain = max(xmap(sum, xzip(*steps))) if gain: # If gain is zero, normalization couldn't have any effect wnd[:] = (w / gain for w in wnd) else: wnd = [1 / ceil(size / hop)] * size # Window application if wnd: mul = operator.mul if len(wnd) != size: raise ValueError("Incompatible window size") wnd = wnd + [0.] # Allows detecting when block size is wrong blk_sig = (xmap(mul, wnd, blk) for blk in blk_sig) # Overlap-add algorithm add = operator.add mem = [0.] * size s_h = size - hop for blk in xmap(iter, blk_sig): mem[:s_h] = xmap(add, mem[hop:], blk) mem[s_h:] = blk # Remaining elements if len(mem) != size: raise ValueError("Wrong block size or declared") for el in mem[:hop]: yield el for el in mem[hop:]: # No more blocks, finish yielding the last one yield el
python
def overlap_add(blk_sig, size=None, hop=None, wnd=None, normalize=True): """ Overlap-add algorithm using lists instead of Numpy arrays. The behavior is the same to the ``overlap_add.numpy`` strategy, besides the data types. """ # Finds the size from data, if needed if size is None: blk_sig = Stream(blk_sig) size = len(blk_sig.peek()) if hop is None: hop = size # Find the window to be applied, resulting on a list or None if wnd is not None: if callable(wnd) and not isinstance(wnd, Stream): wnd = wnd(size) if isinstance(wnd, Iterable): wnd = list(wnd) else: raise TypeError("Window should be an iterable or a callable") # Normalization to the [-1; 1] range if normalize: if wnd: steps = Stream(wnd).map(abs).blocks(hop).map(tuple) gain = max(xmap(sum, xzip(*steps))) if gain: # If gain is zero, normalization couldn't have any effect wnd[:] = (w / gain for w in wnd) else: wnd = [1 / ceil(size / hop)] * size # Window application if wnd: mul = operator.mul if len(wnd) != size: raise ValueError("Incompatible window size") wnd = wnd + [0.] # Allows detecting when block size is wrong blk_sig = (xmap(mul, wnd, blk) for blk in blk_sig) # Overlap-add algorithm add = operator.add mem = [0.] * size s_h = size - hop for blk in xmap(iter, blk_sig): mem[:s_h] = xmap(add, mem[hop:], blk) mem[s_h:] = blk # Remaining elements if len(mem) != size: raise ValueError("Wrong block size or declared") for el in mem[:hop]: yield el for el in mem[hop:]: # No more blocks, finish yielding the last one yield el
[ "def", "overlap_add", "(", "blk_sig", ",", "size", "=", "None", ",", "hop", "=", "None", ",", "wnd", "=", "None", ",", "normalize", "=", "True", ")", ":", "# Finds the size from data, if needed", "if", "size", "is", "None", ":", "blk_sig", "=", "Stream", ...
Overlap-add algorithm using lists instead of Numpy arrays. The behavior is the same to the ``overlap_add.numpy`` strategy, besides the data types.
[ "Overlap", "-", "add", "algorithm", "using", "lists", "instead", "of", "Numpy", "arrays", ".", "The", "behavior", "is", "the", "same", "to", "the", "overlap_add", ".", "numpy", "strategy", "besides", "the", "data", "types", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L807-L858
train
210,246
danilobellini/audiolazy
audiolazy/lazy_analysis.py
stft
def stft(func=None, **kwparams): """ Short Time Fourier Transform for complex data. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft) See ``stft.base`` docs for more. """ from numpy.fft import fft, ifft return stft.base(transform=fft, inverse_transform=ifft)(func, **kwparams)
python
def stft(func=None, **kwparams): """ Short Time Fourier Transform for complex data. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft) See ``stft.base`` docs for more. """ from numpy.fft import fft, ifft return stft.base(transform=fft, inverse_transform=ifft)(func, **kwparams)
[ "def", "stft", "(", "func", "=", "None", ",", "*", "*", "kwparams", ")", ":", "from", "numpy", ".", "fft", "import", "fft", ",", "ifft", "return", "stft", ".", "base", "(", "transform", "=", "fft", ",", "inverse_transform", "=", "ifft", ")", "(", "...
Short Time Fourier Transform for complex data. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft) See ``stft.base`` docs for more.
[ "Short", "Time", "Fourier", "Transform", "for", "complex", "data", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L1147-L1161
train
210,247
danilobellini/audiolazy
audiolazy/lazy_analysis.py
stft
def stft(func=None, **kwparams): """ Short Time Fourier Transform for real data keeping the full FFT block. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=lambda *args: numpy.fft.ifft(*args).real) See ``stft.base`` docs for more. """ from numpy.fft import fft, ifft ifft_r = lambda *args: ifft(*args).real return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)
python
def stft(func=None, **kwparams): """ Short Time Fourier Transform for real data keeping the full FFT block. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=lambda *args: numpy.fft.ifft(*args).real) See ``stft.base`` docs for more. """ from numpy.fft import fft, ifft ifft_r = lambda *args: ifft(*args).real return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)
[ "def", "stft", "(", "func", "=", "None", ",", "*", "*", "kwparams", ")", ":", "from", "numpy", ".", "fft", "import", "fft", ",", "ifft", "ifft_r", "=", "lambda", "*", "args", ":", "ifft", "(", "*", "args", ")", ".", "real", "return", "stft", ".",...
Short Time Fourier Transform for real data keeping the full FFT block. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=lambda *args: numpy.fft.ifft(*args).real) See ``stft.base`` docs for more.
[ "Short", "Time", "Fourier", "Transform", "for", "real", "data", "keeping", "the", "full", "FFT", "block", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L1165-L1181
train
210,248
danilobellini/audiolazy
audiolazy/lazy_io.py
AudioIO.close
def close(self): """ Destructor for this audio interface. Waits the threads to finish their streams, if desired. """ with self.halting: # Avoid simultaneous "close" threads if not self.finished: # Ignore all "close" calls, but the first, self.finished = True # and any call to play would raise ThreadError # Closes all playing AudioThread instances while True: with self.lock: # Ensure there's no other thread messing around try: thread = self._threads[0] # Needless to say: pop = deadlock except IndexError: # Empty list break # No more threads if not self.wait: thread.stop() thread.join() # Closes all recording RecStream instances while self._recordings: recst = self._recordings[-1] recst.stop() recst.take(inf) # Ensure it'll be closed # Finishes assert not self._pa._streams # No stream should survive self._pa.terminate()
python
def close(self): """ Destructor for this audio interface. Waits the threads to finish their streams, if desired. """ with self.halting: # Avoid simultaneous "close" threads if not self.finished: # Ignore all "close" calls, but the first, self.finished = True # and any call to play would raise ThreadError # Closes all playing AudioThread instances while True: with self.lock: # Ensure there's no other thread messing around try: thread = self._threads[0] # Needless to say: pop = deadlock except IndexError: # Empty list break # No more threads if not self.wait: thread.stop() thread.join() # Closes all recording RecStream instances while self._recordings: recst = self._recordings[-1] recst.stop() recst.take(inf) # Ensure it'll be closed # Finishes assert not self._pa._streams # No stream should survive self._pa.terminate()
[ "def", "close", "(", "self", ")", ":", "with", "self", ".", "halting", ":", "# Avoid simultaneous \"close\" threads", "if", "not", "self", ".", "finished", ":", "# Ignore all \"close\" calls, but the first,", "self", ".", "finished", "=", "True", "# and any call to pl...
Destructor for this audio interface. Waits the threads to finish their streams, if desired.
[ "Destructor", "for", "this", "audio", "interface", ".", "Waits", "the", "threads", "to", "finish", "their", "streams", "if", "desired", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_io.py#L220-L250
train
210,249
danilobellini/audiolazy
audiolazy/lazy_io.py
AudioIO.record
def record(self, chunk_size = None, dfmt = "f", channels = 1, rate = DEFAULT_SAMPLE_RATE, **kwargs ): """ Records audio from device into a Stream. Parameters ---------- chunk_size : Number of samples per chunk (block sent to device). dfmt : Format, as in chunks(). Default is "f" (Float32). channels : Channels in audio stream (serialized). rate : Sample rate (same input used in sHz). Returns ------- Endless Stream instance that gather data from the audio input device. """ if chunk_size is None: chunk_size = chunks.size if hasattr(self, "api"): kwargs.setdefault("input_device_index", self.api["defaultInputDevice"]) channels = kwargs.pop("nchannels", channels) # Backwards compatibility input_stream = RecStream(self, self._pa.open(format=_STRUCT2PYAUDIO[dfmt], channels=channels, rate=rate, frames_per_buffer=chunk_size, input=True, **kwargs), chunk_size, dfmt ) self._recordings.append(input_stream) return input_stream
python
def record(self, chunk_size = None, dfmt = "f", channels = 1, rate = DEFAULT_SAMPLE_RATE, **kwargs ): """ Records audio from device into a Stream. Parameters ---------- chunk_size : Number of samples per chunk (block sent to device). dfmt : Format, as in chunks(). Default is "f" (Float32). channels : Channels in audio stream (serialized). rate : Sample rate (same input used in sHz). Returns ------- Endless Stream instance that gather data from the audio input device. """ if chunk_size is None: chunk_size = chunks.size if hasattr(self, "api"): kwargs.setdefault("input_device_index", self.api["defaultInputDevice"]) channels = kwargs.pop("nchannels", channels) # Backwards compatibility input_stream = RecStream(self, self._pa.open(format=_STRUCT2PYAUDIO[dfmt], channels=channels, rate=rate, frames_per_buffer=chunk_size, input=True, **kwargs), chunk_size, dfmt ) self._recordings.append(input_stream) return input_stream
[ "def", "record", "(", "self", ",", "chunk_size", "=", "None", ",", "dfmt", "=", "\"f\"", ",", "channels", "=", "1", ",", "rate", "=", "DEFAULT_SAMPLE_RATE", ",", "*", "*", "kwargs", ")", ":", "if", "chunk_size", "is", "None", ":", "chunk_size", "=", ...
Records audio from device into a Stream. Parameters ---------- chunk_size : Number of samples per chunk (block sent to device). dfmt : Format, as in chunks(). Default is "f" (Float32). channels : Channels in audio stream (serialized). rate : Sample rate (same input used in sHz). Returns ------- Endless Stream instance that gather data from the audio input device.
[ "Records", "audio", "from", "device", "into", "a", "Stream", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_io.py#L290-L333
train
210,250
danilobellini/audiolazy
audiolazy/lazy_io.py
AudioThread.run
def run(self): """ Plays the audio. This method plays the audio, and shouldn't be called explicitly, let the constructor do so. """ # From now on, it's multi-thread. Let the force be with them. st = self.stream._stream for chunk in chunks(self.audio, size=self.chunk_size*self.nchannels, dfmt=self.dfmt): #Below is a faster way to call: # self.stream.write(chunk, self.chunk_size) self.write_stream(st, chunk, self.chunk_size, False) if not self.go.is_set(): self.stream.stop_stream() if self.halting: break self.go.wait() self.stream.start_stream() # Finished playing! Destructor-like step: let's close the thread with self.lock: if self in self.device_manager._threads: # If not already closed self.stream.close() self.device_manager.thread_finished(self)
python
def run(self): """ Plays the audio. This method plays the audio, and shouldn't be called explicitly, let the constructor do so. """ # From now on, it's multi-thread. Let the force be with them. st = self.stream._stream for chunk in chunks(self.audio, size=self.chunk_size*self.nchannels, dfmt=self.dfmt): #Below is a faster way to call: # self.stream.write(chunk, self.chunk_size) self.write_stream(st, chunk, self.chunk_size, False) if not self.go.is_set(): self.stream.stop_stream() if self.halting: break self.go.wait() self.stream.start_stream() # Finished playing! Destructor-like step: let's close the thread with self.lock: if self in self.device_manager._threads: # If not already closed self.stream.close() self.device_manager.thread_finished(self)
[ "def", "run", "(", "self", ")", ":", "# From now on, it's multi-thread. Let the force be with them.", "st", "=", "self", ".", "stream", ".", "_stream", "for", "chunk", "in", "chunks", "(", "self", ".", "audio", ",", "size", "=", "self", ".", "chunk_size", "*",...
Plays the audio. This method plays the audio, and shouldn't be called explicitly, let the constructor do so.
[ "Plays", "the", "audio", ".", "This", "method", "plays", "the", "audio", "and", "shouldn", "t", "be", "called", "explicitly", "let", "the", "constructor", "do", "so", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_io.py#L406-L431
train
210,251
danilobellini/audiolazy
audiolazy/lazy_io.py
AudioThread.stop
def stop(self): """ Stops the playing thread and close """ with self.lock: self.halting = True self.go.clear()
python
def stop(self): """ Stops the playing thread and close """ with self.lock: self.halting = True self.go.clear()
[ "def", "stop", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "halting", "=", "True", "self", ".", "go", ".", "clear", "(", ")" ]
Stops the playing thread and close
[ "Stops", "the", "playing", "thread", "and", "close" ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_io.py#L433-L437
train
210,252
danilobellini/audiolazy
audiolazy/lazy_midi.py
freq2midi
def freq2midi(freq): """ Given a frequency in Hz, returns its MIDI pitch number. """ result = 12 * (log2(freq) - log2(FREQ_A4)) + MIDI_A4 return nan if isinstance(result, complex) else result
python
def freq2midi(freq): """ Given a frequency in Hz, returns its MIDI pitch number. """ result = 12 * (log2(freq) - log2(FREQ_A4)) + MIDI_A4 return nan if isinstance(result, complex) else result
[ "def", "freq2midi", "(", "freq", ")", ":", "result", "=", "12", "*", "(", "log2", "(", "freq", ")", "-", "log2", "(", "FREQ_A4", ")", ")", "+", "MIDI_A4", "return", "nan", "if", "isinstance", "(", "result", ",", "complex", ")", "else", "result" ]
Given a frequency in Hz, returns its MIDI pitch number.
[ "Given", "a", "frequency", "in", "Hz", "returns", "its", "MIDI", "pitch", "number", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_midi.py#L71-L76
train
210,253
danilobellini/audiolazy
audiolazy/lazy_midi.py
octaves
def octaves(freq, fmin=20., fmax=2e4): """ Given a frequency and a frequency range, returns all frequencies in that range that is an integer number of octaves related to the given frequency. Parameters ---------- freq : Frequency, in any (linear) unit. fmin, fmax : Frequency range, in the same unit of ``freq``. Defaults to 20.0 and 20,000.0, respectively. Returns ------- A list of frequencies, in the same unit of ``freq`` and in ascending order. Examples -------- >>> from audiolazy import octaves, sHz >>> octaves(440.) [27.5, 55.0, 110.0, 220.0, 440.0, 880.0, 1760.0, 3520.0, 7040.0, 14080.0] >>> octaves(440., fmin=3000) [3520.0, 7040.0, 14080.0] >>> Hz = sHz(44100)[1] # Conversion unit from sample rate >>> freqs = octaves(440 * Hz, fmin=300 * Hz, fmax = 1000 * Hz) # rad/sample >>> len(freqs) # Number of octaves 2 >>> [round(f, 6) for f in freqs] # Values in rad/sample [0.062689, 0.125379] >>> [round(f / Hz, 6) for f in freqs] # Values in Hz [440.0, 880.0] """ # Input validation if any(f <= 0 for f in (freq, fmin, fmax)): raise ValueError("Frequencies have to be positive") # If freq is out of range, avoid range extension while freq < fmin: freq *= 2 while freq > fmax: freq /= 2 if freq < fmin: # Gone back and forth return [] # Finds the range for a valid input return list(it.takewhile(lambda x: x > fmin, (freq * 2 ** harm for harm in it.count(0, -1)) ))[::-1] \ + list(it.takewhile(lambda x: x < fmax, (freq * 2 ** harm for harm in it.count(1)) ))
python
def octaves(freq, fmin=20., fmax=2e4): """ Given a frequency and a frequency range, returns all frequencies in that range that is an integer number of octaves related to the given frequency. Parameters ---------- freq : Frequency, in any (linear) unit. fmin, fmax : Frequency range, in the same unit of ``freq``. Defaults to 20.0 and 20,000.0, respectively. Returns ------- A list of frequencies, in the same unit of ``freq`` and in ascending order. Examples -------- >>> from audiolazy import octaves, sHz >>> octaves(440.) [27.5, 55.0, 110.0, 220.0, 440.0, 880.0, 1760.0, 3520.0, 7040.0, 14080.0] >>> octaves(440., fmin=3000) [3520.0, 7040.0, 14080.0] >>> Hz = sHz(44100)[1] # Conversion unit from sample rate >>> freqs = octaves(440 * Hz, fmin=300 * Hz, fmax = 1000 * Hz) # rad/sample >>> len(freqs) # Number of octaves 2 >>> [round(f, 6) for f in freqs] # Values in rad/sample [0.062689, 0.125379] >>> [round(f / Hz, 6) for f in freqs] # Values in Hz [440.0, 880.0] """ # Input validation if any(f <= 0 for f in (freq, fmin, fmax)): raise ValueError("Frequencies have to be positive") # If freq is out of range, avoid range extension while freq < fmin: freq *= 2 while freq > fmax: freq /= 2 if freq < fmin: # Gone back and forth return [] # Finds the range for a valid input return list(it.takewhile(lambda x: x > fmin, (freq * 2 ** harm for harm in it.count(0, -1)) ))[::-1] \ + list(it.takewhile(lambda x: x < fmax, (freq * 2 ** harm for harm in it.count(1)) ))
[ "def", "octaves", "(", "freq", ",", "fmin", "=", "20.", ",", "fmax", "=", "2e4", ")", ":", "# Input validation", "if", "any", "(", "f", "<=", "0", "for", "f", "in", "(", "freq", ",", "fmin", ",", "fmax", ")", ")", ":", "raise", "ValueError", "(",...
Given a frequency and a frequency range, returns all frequencies in that range that is an integer number of octaves related to the given frequency. Parameters ---------- freq : Frequency, in any (linear) unit. fmin, fmax : Frequency range, in the same unit of ``freq``. Defaults to 20.0 and 20,000.0, respectively. Returns ------- A list of frequencies, in the same unit of ``freq`` and in ascending order. Examples -------- >>> from audiolazy import octaves, sHz >>> octaves(440.) [27.5, 55.0, 110.0, 220.0, 440.0, 880.0, 1760.0, 3520.0, 7040.0, 14080.0] >>> octaves(440., fmin=3000) [3520.0, 7040.0, 14080.0] >>> Hz = sHz(44100)[1] # Conversion unit from sample rate >>> freqs = octaves(440 * Hz, fmin=300 * Hz, fmax = 1000 * Hz) # rad/sample >>> len(freqs) # Number of octaves 2 >>> [round(f, 6) for f in freqs] # Values in rad/sample [0.062689, 0.125379] >>> [round(f / Hz, 6) for f in freqs] # Values in Hz [440.0, 880.0]
[ "Given", "a", "frequency", "and", "a", "frequency", "range", "returns", "all", "frequencies", "in", "that", "range", "that", "is", "an", "integer", "number", "of", "octaves", "related", "to", "the", "given", "frequency", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_midi.py#L111-L163
train
210,254
danilobellini/audiolazy
setup.py
image_path_processor_factory
def image_path_processor_factory(path): """ Processor for concatenating the ``path`` to relative path images """ def processor(line): markup = ".. image::" if line.startswith(markup): fname = line[len(markup):].strip() if not(fname.startswith("/") or "://" in fname): return "{} {}{}".format(markup, path, fname) return line return processor
python
def image_path_processor_factory(path): """ Processor for concatenating the ``path`` to relative path images """ def processor(line): markup = ".. image::" if line.startswith(markup): fname = line[len(markup):].strip() if not(fname.startswith("/") or "://" in fname): return "{} {}{}".format(markup, path, fname) return line return processor
[ "def", "image_path_processor_factory", "(", "path", ")", ":", "def", "processor", "(", "line", ")", ":", "markup", "=", "\".. image::\"", "if", "line", ".", "startswith", "(", "markup", ")", ":", "fname", "=", "line", "[", "len", "(", "markup", ")", ":",...
Processor for concatenating the ``path`` to relative path images
[ "Processor", "for", "concatenating", "the", "path", "to", "relative", "path", "images" ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/setup.py#L69-L78
train
210,255
danilobellini/audiolazy
examples/ode_to_joy.py
delay
def delay(sig): """ Simple feedforward delay effect """ smix = Streamix() sig = thub(sig, 3) # Auto-copy 3 times (remove this line if using feedback) smix.add(0, sig) # To get a feedback delay, use "smix.copy()" below instead of both "sig" smix.add(280 * ms, .1 * sig) # You can also try other constants smix.add(220 * ms, .1 * sig) return smix
python
def delay(sig): """ Simple feedforward delay effect """ smix = Streamix() sig = thub(sig, 3) # Auto-copy 3 times (remove this line if using feedback) smix.add(0, sig) # To get a feedback delay, use "smix.copy()" below instead of both "sig" smix.add(280 * ms, .1 * sig) # You can also try other constants smix.add(220 * ms, .1 * sig) return smix
[ "def", "delay", "(", "sig", ")", ":", "smix", "=", "Streamix", "(", ")", "sig", "=", "thub", "(", "sig", ",", "3", ")", "# Auto-copy 3 times (remove this line if using feedback)", "smix", ".", "add", "(", "0", ",", "sig", ")", "# To get a feedback delay, use \...
Simple feedforward delay effect
[ "Simple", "feedforward", "delay", "effect" ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/ode_to_joy.py#L34-L42
train
210,256
danilobellini/audiolazy
examples/ode_to_joy.py
note2snd
def note2snd(pitch, quarters): """ Creates an audio Stream object for a single note. Parameters ---------- pitch : Pitch note like ``"A4"``, as a string, or ``None`` for a rest. quarters : Duration in quarters (see ``quarter_dur``). """ dur = quarters * quarter_dur if pitch is None: return zeros(dur) freq = str2freq(pitch) * Hz return synth(freq, dur)
python
def note2snd(pitch, quarters): """ Creates an audio Stream object for a single note. Parameters ---------- pitch : Pitch note like ``"A4"``, as a string, or ``None`` for a rest. quarters : Duration in quarters (see ``quarter_dur``). """ dur = quarters * quarter_dur if pitch is None: return zeros(dur) freq = str2freq(pitch) * Hz return synth(freq, dur)
[ "def", "note2snd", "(", "pitch", ",", "quarters", ")", ":", "dur", "=", "quarters", "*", "quarter_dur", "if", "pitch", "is", "None", ":", "return", "zeros", "(", "dur", ")", "freq", "=", "str2freq", "(", "pitch", ")", "*", "Hz", "return", "synth", "(...
Creates an audio Stream object for a single note. Parameters ---------- pitch : Pitch note like ``"A4"``, as a string, or ``None`` for a rest. quarters : Duration in quarters (see ``quarter_dur``).
[ "Creates", "an", "audio", "Stream", "object", "for", "a", "single", "note", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/ode_to_joy.py#L49-L64
train
210,257
danilobellini/audiolazy
docs/rst_creator.py
find_full_name
def find_full_name(prefix, suffix="rst"): """ Script path to actual path relative file name converter. Parameters ---------- prefix : File name prefix (without extension), relative to the script location. suffix : File name extension (defaults to "rst"). Returns ------- A file name path relative to the actual location to a file inside the script location. Warning ------- Calling this OVERWRITES the RST files in the directory it's in, and don't ask for confirmation! """ return os.path.join(os.path.split(__file__)[0], os.path.extsep.join([prefix, suffix]))
python
def find_full_name(prefix, suffix="rst"): """ Script path to actual path relative file name converter. Parameters ---------- prefix : File name prefix (without extension), relative to the script location. suffix : File name extension (defaults to "rst"). Returns ------- A file name path relative to the actual location to a file inside the script location. Warning ------- Calling this OVERWRITES the RST files in the directory it's in, and don't ask for confirmation! """ return os.path.join(os.path.split(__file__)[0], os.path.extsep.join([prefix, suffix]))
[ "def", "find_full_name", "(", "prefix", ",", "suffix", "=", "\"rst\"", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "split", "(", "__file__", ")", "[", "0", "]", ",", "os", ".", "path", ".", "extsep", ".", "joi...
Script path to actual path relative file name converter. Parameters ---------- prefix : File name prefix (without extension), relative to the script location. suffix : File name extension (defaults to "rst"). Returns ------- A file name path relative to the actual location to a file inside the script location. Warning ------- Calling this OVERWRITES the RST files in the directory it's in, and don't ask for confirmation!
[ "Script", "path", "to", "actual", "path", "relative", "file", "name", "converter", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/docs/rst_creator.py#L39-L62
train
210,258
danilobellini/audiolazy
docs/rst_creator.py
save_to_rst
def save_to_rst(prefix, data): """ Saves a RST file with the given prefix into the script file location. """ with open(find_full_name(prefix), "w") as rst_file: rst_file.write(full_gpl_for_rst) rst_file.write(data)
python
def save_to_rst(prefix, data): """ Saves a RST file with the given prefix into the script file location. """ with open(find_full_name(prefix), "w") as rst_file: rst_file.write(full_gpl_for_rst) rst_file.write(data)
[ "def", "save_to_rst", "(", "prefix", ",", "data", ")", ":", "with", "open", "(", "find_full_name", "(", "prefix", ")", ",", "\"w\"", ")", "as", "rst_file", ":", "rst_file", ".", "write", "(", "full_gpl_for_rst", ")", "rst_file", ".", "write", "(", "data"...
Saves a RST file with the given prefix into the script file location.
[ "Saves", "a", "RST", "file", "with", "the", "given", "prefix", "into", "the", "script", "file", "location", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/docs/rst_creator.py#L65-L72
train
210,259
danilobellini/audiolazy
examples/play_bach_choral.py
ks_synth
def ks_synth(freq): """ Synthesize the given frequency into a Stream by using a model based on Karplus-Strong. """ ks_mem = (sum(lz.sinusoid(x * freq) for x in [1, 3, 9]) + lz.white_noise() + lz.Stream(-1, 1)) / 5 return lz.karplus_strong(freq, memory=ks_mem)
python
def ks_synth(freq): """ Synthesize the given frequency into a Stream by using a model based on Karplus-Strong. """ ks_mem = (sum(lz.sinusoid(x * freq) for x in [1, 3, 9]) + lz.white_noise() + lz.Stream(-1, 1)) / 5 return lz.karplus_strong(freq, memory=ks_mem)
[ "def", "ks_synth", "(", "freq", ")", ":", "ks_mem", "=", "(", "sum", "(", "lz", ".", "sinusoid", "(", "x", "*", "freq", ")", "for", "x", "in", "[", "1", ",", "3", ",", "9", "]", ")", "+", "lz", ".", "white_noise", "(", ")", "+", "lz", ".", ...
Synthesize the given frequency into a Stream by using a model based on Karplus-Strong.
[ "Synthesize", "the", "given", "frequency", "into", "a", "Stream", "by", "using", "a", "model", "based", "on", "Karplus", "-", "Strong", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/play_bach_choral.py#L33-L40
train
210,260
danilobellini/audiolazy
examples/play_bach_choral.py
m21_to_stream
def m21_to_stream(score, synth=ks_synth, beat=90, fdur=2., pad_dur=.5, rate=lz.DEFAULT_SAMPLE_RATE): """ Converts Music21 data to a Stream object. Parameters ---------- score : A Music21 data, usually a music21.stream.Score instance. synth : A function that receives a frequency as input and should yield a Stream instance with the note being played. beat : The BPM (beats per minute) value to be used in playing. fdur : Relative duration of a fermata. For example, 1.0 ignores the fermata, and 2.0 (default) doubles its duration. pad_dur : Duration in seconds, but not multiplied by ``s``, to be used as a zero-padding ending event (avoids clicks at the end when playing). rate : The sample rate, given in samples per second. """ # Configuration s, Hz = lz.sHz(rate) step = 60. / beat * s # Creates a score from the music21 data score = reduce(operator.concat, [[(pitch.frequency * Hz, # Note note.offset * step, # Starting time note.quarterLength * step, # Duration Fermata in note.expressions) for pitch in note.pitches] for note in score.flat.notes] ) # Mix all notes into song song = lz.Streamix() last_start = 0 for freq, start, dur, has_fermata in score: delta = start - last_start if has_fermata: delta *= 2 song.add(delta, synth(freq).limit(dur)) last_start = start # Zero-padding and finishing song.add(dur + pad_dur * s, lz.Stream([])) return song
python
def m21_to_stream(score, synth=ks_synth, beat=90, fdur=2., pad_dur=.5, rate=lz.DEFAULT_SAMPLE_RATE): """ Converts Music21 data to a Stream object. Parameters ---------- score : A Music21 data, usually a music21.stream.Score instance. synth : A function that receives a frequency as input and should yield a Stream instance with the note being played. beat : The BPM (beats per minute) value to be used in playing. fdur : Relative duration of a fermata. For example, 1.0 ignores the fermata, and 2.0 (default) doubles its duration. pad_dur : Duration in seconds, but not multiplied by ``s``, to be used as a zero-padding ending event (avoids clicks at the end when playing). rate : The sample rate, given in samples per second. """ # Configuration s, Hz = lz.sHz(rate) step = 60. / beat * s # Creates a score from the music21 data score = reduce(operator.concat, [[(pitch.frequency * Hz, # Note note.offset * step, # Starting time note.quarterLength * step, # Duration Fermata in note.expressions) for pitch in note.pitches] for note in score.flat.notes] ) # Mix all notes into song song = lz.Streamix() last_start = 0 for freq, start, dur, has_fermata in score: delta = start - last_start if has_fermata: delta *= 2 song.add(delta, synth(freq).limit(dur)) last_start = start # Zero-padding and finishing song.add(dur + pad_dur * s, lz.Stream([])) return song
[ "def", "m21_to_stream", "(", "score", ",", "synth", "=", "ks_synth", ",", "beat", "=", "90", ",", "fdur", "=", "2.", ",", "pad_dur", "=", ".5", ",", "rate", "=", "lz", ".", "DEFAULT_SAMPLE_RATE", ")", ":", "# Configuration", "s", ",", "Hz", "=", "lz"...
Converts Music21 data to a Stream object. Parameters ---------- score : A Music21 data, usually a music21.stream.Score instance. synth : A function that receives a frequency as input and should yield a Stream instance with the note being played. beat : The BPM (beats per minute) value to be used in playing. fdur : Relative duration of a fermata. For example, 1.0 ignores the fermata, and 2.0 (default) doubles its duration. pad_dur : Duration in seconds, but not multiplied by ``s``, to be used as a zero-padding ending event (avoids clicks at the end when playing). rate : The sample rate, given in samples per second.
[ "Converts", "Music21", "data", "to", "a", "Stream", "object", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/play_bach_choral.py#L52-L101
train
210,261
danilobellini/audiolazy
audiolazy/lazy_text.py
pair_strings_sum_formatter
def pair_strings_sum_formatter(a, b): """ Formats the sum of a and b. Note ---- Both inputs are numbers already converted to strings. """ if b[:1] == "-": return "{0} - {1}".format(a, b[1:]) return "{0} + {1}".format(a, b)
python
def pair_strings_sum_formatter(a, b): """ Formats the sum of a and b. Note ---- Both inputs are numbers already converted to strings. """ if b[:1] == "-": return "{0} - {1}".format(a, b[1:]) return "{0} + {1}".format(a, b)
[ "def", "pair_strings_sum_formatter", "(", "a", ",", "b", ")", ":", "if", "b", "[", ":", "1", "]", "==", "\"-\"", ":", "return", "\"{0} - {1}\"", ".", "format", "(", "a", ",", "b", "[", "1", ":", "]", ")", "return", "\"{0} + {1}\"", ".", "format", "...
Formats the sum of a and b. Note ---- Both inputs are numbers already converted to strings.
[ "Formats", "the", "sum", "of", "a", "and", "b", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_text.py#L60-L71
train
210,262
danilobellini/audiolazy
audiolazy/lazy_text.py
float_str
def float_str(value, symbol_str="", symbol_value=1, after=False, max_denominator=1000000): """ Pretty rational string from float numbers. Converts a given numeric value to a string based on rational fractions of the given symbol, useful for labels in plots. Parameters ---------- value : A float number or an iterable with floats. symbol_str : String data that will be in the output representing the data as a numerator multiplier, if needed. Defaults to an empty string. symbol_value : The conversion value for the given symbol (e.g. pi = 3.1415...). Defaults to one (no effect). after : Chooses the place where the ``symbol_str`` should be written. If ``True``, that's the end of the string. If ``False``, that's in between the numerator and the denominator, before the slash. Defaults to ``False``. max_denominator : An int instance, used to round the float following the given limit. Defaults to the integer 1,000,000 (one million). Returns ------- A string with the rational number written into as a fraction, with or without a multiplying symbol. Examples -------- >>> float_str.frac(12.5) '25/2' >>> float_str.frac(0.333333333333333) '1/3' >>> float_str.frac(0.333) '333/1000' >>> float_str.frac(0.333, max_denominator=100) '1/3' >>> float_str.frac(0.125, symbol_str="steps") 'steps/8' >>> float_str.frac(0.125, symbol_str=" Hz", ... after=True) # The symbol includes whitespace! '1/8 Hz' See Also -------- float_str.pi : This fraction/ratio formatter, but configured with the "pi" symbol. """ if value == 0: return "0" frac = Fraction(value/symbol_value).limit_denominator(max_denominator) num, den = frac.numerator, frac.denominator output_data = [] if num < 0: num = -num output_data.append("-") if (num != 1) or (symbol_str == "") or after: output_data.append(str(num)) if (value != 0) and not after: output_data.append(symbol_str) if den != 1: output_data.extend(["/", str(den)]) if after: output_data.append(symbol_str) return "".join(output_data)
python
def float_str(value, symbol_str="", symbol_value=1, after=False, max_denominator=1000000): """ Pretty rational string from float numbers. Converts a given numeric value to a string based on rational fractions of the given symbol, useful for labels in plots. Parameters ---------- value : A float number or an iterable with floats. symbol_str : String data that will be in the output representing the data as a numerator multiplier, if needed. Defaults to an empty string. symbol_value : The conversion value for the given symbol (e.g. pi = 3.1415...). Defaults to one (no effect). after : Chooses the place where the ``symbol_str`` should be written. If ``True``, that's the end of the string. If ``False``, that's in between the numerator and the denominator, before the slash. Defaults to ``False``. max_denominator : An int instance, used to round the float following the given limit. Defaults to the integer 1,000,000 (one million). Returns ------- A string with the rational number written into as a fraction, with or without a multiplying symbol. Examples -------- >>> float_str.frac(12.5) '25/2' >>> float_str.frac(0.333333333333333) '1/3' >>> float_str.frac(0.333) '333/1000' >>> float_str.frac(0.333, max_denominator=100) '1/3' >>> float_str.frac(0.125, symbol_str="steps") 'steps/8' >>> float_str.frac(0.125, symbol_str=" Hz", ... after=True) # The symbol includes whitespace! '1/8 Hz' See Also -------- float_str.pi : This fraction/ratio formatter, but configured with the "pi" symbol. """ if value == 0: return "0" frac = Fraction(value/symbol_value).limit_denominator(max_denominator) num, den = frac.numerator, frac.denominator output_data = [] if num < 0: num = -num output_data.append("-") if (num != 1) or (symbol_str == "") or after: output_data.append(str(num)) if (value != 0) and not after: output_data.append(symbol_str) if den != 1: output_data.extend(["/", str(den)]) if after: output_data.append(symbol_str) return "".join(output_data)
[ "def", "float_str", "(", "value", ",", "symbol_str", "=", "\"\"", ",", "symbol_value", "=", "1", ",", "after", "=", "False", ",", "max_denominator", "=", "1000000", ")", ":", "if", "value", "==", "0", ":", "return", "\"0\"", "frac", "=", "Fraction", "(...
Pretty rational string from float numbers. Converts a given numeric value to a string based on rational fractions of the given symbol, useful for labels in plots. Parameters ---------- value : A float number or an iterable with floats. symbol_str : String data that will be in the output representing the data as a numerator multiplier, if needed. Defaults to an empty string. symbol_value : The conversion value for the given symbol (e.g. pi = 3.1415...). Defaults to one (no effect). after : Chooses the place where the ``symbol_str`` should be written. If ``True``, that's the end of the string. If ``False``, that's in between the numerator and the denominator, before the slash. Defaults to ``False``. max_denominator : An int instance, used to round the float following the given limit. Defaults to the integer 1,000,000 (one million). Returns ------- A string with the rational number written into as a fraction, with or without a multiplying symbol. Examples -------- >>> float_str.frac(12.5) '25/2' >>> float_str.frac(0.333333333333333) '1/3' >>> float_str.frac(0.333) '333/1000' >>> float_str.frac(0.333, max_denominator=100) '1/3' >>> float_str.frac(0.125, symbol_str="steps") 'steps/8' >>> float_str.frac(0.125, symbol_str=" Hz", ... after=True) # The symbol includes whitespace! '1/8 Hz' See Also -------- float_str.pi : This fraction/ratio formatter, but configured with the "pi" symbol.
[ "Pretty", "rational", "string", "from", "float", "numbers", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_text.py#L149-L226
train
210,263
danilobellini/audiolazy
audiolazy/lazy_text.py
small_doc
def small_doc(obj, indent="", max_width=80): """ Finds a useful small doc representation of an object. Parameters ---------- obj : Any object, which the documentation representation should be taken from. indent : Result indentation string to be insert in front of all lines. max_width : Each line of the result may have at most this length. Returns ------- For classes, modules, functions, methods, properties and StrategyDict instances, returns the first paragraph in the doctring of the given object, as a list of strings, stripped at right and with indent at left. For other inputs, it will use themselves cast to string as their docstring. """ if not getattr(obj, "__doc__", False): data = [el.strip() for el in str(obj).splitlines()] if len(data) == 1: if data[0].startswith("<audiolazy.lazy_"): # Instance data = data[0].split("0x", -1)[0] + "0x...>" # Hide its address else: data = "".join(["``", data[0], "``"]) else: data = " ".join(data) # No docstring elif (not obj.__doc__) or (obj.__doc__.strip() == ""): data = "\ * * * * ...no docstring... * * * * \ " # Docstring else: data = (el.strip() for el in obj.__doc__.strip().splitlines()) data = " ".join(it.takewhile(lambda el: el != "", data)) # Ensure max_width (word wrap) max_width -= len(indent) result = [] for word in data.split(): if len(word) <= max_width: if result: if len(result[-1]) + len(word) + 1 <= max_width: word = " ".join([result.pop(), word]) result.append(word) else: result = [word] else: # Splits big words result.extend("".join(w) for w in blocks(word, max_width, padval="")) # Apply indentation and finishes return [indent + el for el in result]
python
def small_doc(obj, indent="", max_width=80): """ Finds a useful small doc representation of an object. Parameters ---------- obj : Any object, which the documentation representation should be taken from. indent : Result indentation string to be insert in front of all lines. max_width : Each line of the result may have at most this length. Returns ------- For classes, modules, functions, methods, properties and StrategyDict instances, returns the first paragraph in the doctring of the given object, as a list of strings, stripped at right and with indent at left. For other inputs, it will use themselves cast to string as their docstring. """ if not getattr(obj, "__doc__", False): data = [el.strip() for el in str(obj).splitlines()] if len(data) == 1: if data[0].startswith("<audiolazy.lazy_"): # Instance data = data[0].split("0x", -1)[0] + "0x...>" # Hide its address else: data = "".join(["``", data[0], "``"]) else: data = " ".join(data) # No docstring elif (not obj.__doc__) or (obj.__doc__.strip() == ""): data = "\ * * * * ...no docstring... * * * * \ " # Docstring else: data = (el.strip() for el in obj.__doc__.strip().splitlines()) data = " ".join(it.takewhile(lambda el: el != "", data)) # Ensure max_width (word wrap) max_width -= len(indent) result = [] for word in data.split(): if len(word) <= max_width: if result: if len(result[-1]) + len(word) + 1 <= max_width: word = " ".join([result.pop(), word]) result.append(word) else: result = [word] else: # Splits big words result.extend("".join(w) for w in blocks(word, max_width, padval="")) # Apply indentation and finishes return [indent + el for el in result]
[ "def", "small_doc", "(", "obj", ",", "indent", "=", "\"\"", ",", "max_width", "=", "80", ")", ":", "if", "not", "getattr", "(", "obj", ",", "\"__doc__\"", ",", "False", ")", ":", "data", "=", "[", "el", ".", "strip", "(", ")", "for", "el", "in", ...
Finds a useful small doc representation of an object. Parameters ---------- obj : Any object, which the documentation representation should be taken from. indent : Result indentation string to be insert in front of all lines. max_width : Each line of the result may have at most this length. Returns ------- For classes, modules, functions, methods, properties and StrategyDict instances, returns the first paragraph in the doctring of the given object, as a list of strings, stripped at right and with indent at left. For other inputs, it will use themselves cast to string as their docstring.
[ "Finds", "a", "useful", "small", "doc", "representation", "of", "an", "object", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_text.py#L299-L354
train
210,264
danilobellini/audiolazy
audiolazy/lazy_compat.py
meta
def meta(*bases, **kwargs): """ Allows unique syntax similar to Python 3 for working with metaclasses in both Python 2 and Python 3. Examples -------- >>> class BadMeta(type): # An usual metaclass definition ... def __new__(mcls, name, bases, namespace): ... if "bad" not in namespace: # A bad constraint ... raise Exception("Oops, not bad enough") ... value = len(name) # To ensure this metaclass is called again ... def really_bad(self): ... return self.bad() * value ... namespace["really_bad"] = really_bad ... return super(BadMeta, mcls).__new__(mcls, name, bases, namespace) ... >>> class Bady(meta(object, metaclass=BadMeta)): ... def bad(self): ... return "HUA " ... >>> class BadGuy(Bady): ... def bad(self): ... return "R" ... >>> issubclass(BadGuy, Bady) True >>> Bady().really_bad() # Here value = 4 'HUA HUA HUA HUA ' >>> BadGuy().really_bad() # Called metaclass ``__new__`` again, so value = 6 'RRRRRR' """ metaclass = kwargs.get("metaclass", type) if not bases: bases = (object,) class NewMeta(type): def __new__(mcls, name, mbases, namespace): if name: return metaclass.__new__(metaclass, name, bases, namespace) return super(NewMeta, mcls).__new__(mcls, "", mbases, {}) return NewMeta("", tuple(), {})
python
def meta(*bases, **kwargs): """ Allows unique syntax similar to Python 3 for working with metaclasses in both Python 2 and Python 3. Examples -------- >>> class BadMeta(type): # An usual metaclass definition ... def __new__(mcls, name, bases, namespace): ... if "bad" not in namespace: # A bad constraint ... raise Exception("Oops, not bad enough") ... value = len(name) # To ensure this metaclass is called again ... def really_bad(self): ... return self.bad() * value ... namespace["really_bad"] = really_bad ... return super(BadMeta, mcls).__new__(mcls, name, bases, namespace) ... >>> class Bady(meta(object, metaclass=BadMeta)): ... def bad(self): ... return "HUA " ... >>> class BadGuy(Bady): ... def bad(self): ... return "R" ... >>> issubclass(BadGuy, Bady) True >>> Bady().really_bad() # Here value = 4 'HUA HUA HUA HUA ' >>> BadGuy().really_bad() # Called metaclass ``__new__`` again, so value = 6 'RRRRRR' """ metaclass = kwargs.get("metaclass", type) if not bases: bases = (object,) class NewMeta(type): def __new__(mcls, name, mbases, namespace): if name: return metaclass.__new__(metaclass, name, bases, namespace) return super(NewMeta, mcls).__new__(mcls, "", mbases, {}) return NewMeta("", tuple(), {})
[ "def", "meta", "(", "*", "bases", ",", "*", "*", "kwargs", ")", ":", "metaclass", "=", "kwargs", ".", "get", "(", "\"metaclass\"", ",", "type", ")", "if", "not", "bases", ":", "bases", "=", "(", "object", ",", ")", "class", "NewMeta", "(", "type", ...
Allows unique syntax similar to Python 3 for working with metaclasses in both Python 2 and Python 3. Examples -------- >>> class BadMeta(type): # An usual metaclass definition ... def __new__(mcls, name, bases, namespace): ... if "bad" not in namespace: # A bad constraint ... raise Exception("Oops, not bad enough") ... value = len(name) # To ensure this metaclass is called again ... def really_bad(self): ... return self.bad() * value ... namespace["really_bad"] = really_bad ... return super(BadMeta, mcls).__new__(mcls, name, bases, namespace) ... >>> class Bady(meta(object, metaclass=BadMeta)): ... def bad(self): ... return "HUA " ... >>> class BadGuy(Bady): ... def bad(self): ... return "R" ... >>> issubclass(BadGuy, Bady) True >>> Bady().really_bad() # Here value = 4 'HUA HUA HUA HUA ' >>> BadGuy().really_bad() # Called metaclass ``__new__`` again, so value = 6 'RRRRRR'
[ "Allows", "unique", "syntax", "similar", "to", "Python", "3", "for", "working", "with", "metaclasses", "in", "both", "Python", "2", "and", "Python", "3", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_compat.py#L85-L126
train
210,265
danilobellini/audiolazy
audiolazy/lazy_synth.py
attack
def attack(a, d, s): """ Linear ADS fading attack stream generator, useful to be multiplied with a given stream. Parameters ---------- a : "Attack" time, in number of samples. d : "Decay" time, in number of samples. s : "Sustain" amplitude level (should be based on attack amplitude). The sustain can be a Stream, if desired. Returns ------- Stream instance yielding an endless envelope, or a finite envelope if the sustain input is a finite Stream. The attack amplitude is is 1.0. """ # Configure sustain possibilities if isinstance(s, collections.Iterable): it_s = iter(s) s = next(it_s) else: it_s = None # Attack and decay lines m_a = 1. / a m_d = (s - 1.) / d len_a = int(a + .5) len_d = int(d + .5) for sample in xrange(len_a): yield sample * m_a for sample in xrange(len_d): yield 1. + sample * m_d # Sustain! if it_s is None: while True: yield s else: for s in it_s: yield s
python
def attack(a, d, s): """ Linear ADS fading attack stream generator, useful to be multiplied with a given stream. Parameters ---------- a : "Attack" time, in number of samples. d : "Decay" time, in number of samples. s : "Sustain" amplitude level (should be based on attack amplitude). The sustain can be a Stream, if desired. Returns ------- Stream instance yielding an endless envelope, or a finite envelope if the sustain input is a finite Stream. The attack amplitude is is 1.0. """ # Configure sustain possibilities if isinstance(s, collections.Iterable): it_s = iter(s) s = next(it_s) else: it_s = None # Attack and decay lines m_a = 1. / a m_d = (s - 1.) / d len_a = int(a + .5) len_d = int(d + .5) for sample in xrange(len_a): yield sample * m_a for sample in xrange(len_d): yield 1. + sample * m_d # Sustain! if it_s is None: while True: yield s else: for s in it_s: yield s
[ "def", "attack", "(", "a", ",", "d", ",", "s", ")", ":", "# Configure sustain possibilities", "if", "isinstance", "(", "s", ",", "collections", ".", "Iterable", ")", ":", "it_s", "=", "iter", "(", "s", ")", "s", "=", "next", "(", "it_s", ")", "else",...
Linear ADS fading attack stream generator, useful to be multiplied with a given stream. Parameters ---------- a : "Attack" time, in number of samples. d : "Decay" time, in number of samples. s : "Sustain" amplitude level (should be based on attack amplitude). The sustain can be a Stream, if desired. Returns ------- Stream instance yielding an endless envelope, or a finite envelope if the sustain input is a finite Stream. The attack amplitude is is 1.0.
[ "Linear", "ADS", "fading", "attack", "stream", "generator", "useful", "to", "be", "multiplied", "with", "a", "given", "stream", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L253-L297
train
210,266
danilobellini/audiolazy
audiolazy/lazy_synth.py
ones
def ones(dur=None): """ Ones stream generator. You may multiply your endless stream by this to enforce an end to it. Parameters ---------- dur : Duration, in number of samples; endless if not given. Returns ------- Stream that repeats "1.0" during a given time duration (if any) or endlessly. """ if dur is None or (isinf(dur) and dur > 0): while True: yield 1.0 for x in xrange(int(.5 + dur)): yield 1.0
python
def ones(dur=None): """ Ones stream generator. You may multiply your endless stream by this to enforce an end to it. Parameters ---------- dur : Duration, in number of samples; endless if not given. Returns ------- Stream that repeats "1.0" during a given time duration (if any) or endlessly. """ if dur is None or (isinf(dur) and dur > 0): while True: yield 1.0 for x in xrange(int(.5 + dur)): yield 1.0
[ "def", "ones", "(", "dur", "=", "None", ")", ":", "if", "dur", "is", "None", "or", "(", "isinf", "(", "dur", ")", "and", "dur", ">", "0", ")", ":", "while", "True", ":", "yield", "1.0", "for", "x", "in", "xrange", "(", "int", "(", ".5", "+", ...
Ones stream generator. You may multiply your endless stream by this to enforce an end to it. Parameters ---------- dur : Duration, in number of samples; endless if not given. Returns ------- Stream that repeats "1.0" during a given time duration (if any) or endlessly.
[ "Ones", "stream", "generator", ".", "You", "may", "multiply", "your", "endless", "stream", "by", "this", "to", "enforce", "an", "end", "to", "it", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L301-L321
train
210,267
danilobellini/audiolazy
audiolazy/lazy_synth.py
adsr
def adsr(dur, a, d, s, r): """ Linear ADSR envelope. Parameters ---------- dur : Duration, in number of samples, including the release time. a : "Attack" time, in number of samples. d : "Decay" time, in number of samples. s : "Sustain" amplitude level (should be based on attack amplitude). r : "Release" time, in number of samples. Returns ------- Stream instance yielding a finite ADSR envelope, starting and finishing with 0.0, having peak value of 1.0. """ m_a = 1. / a m_d = (s - 1.) / d m_r = - s * 1. / r len_a = int(a + .5) len_d = int(d + .5) len_r = int(r + .5) len_s = int(dur + .5) - len_a - len_d - len_r for sample in xrange(len_a): yield sample * m_a for sample in xrange(len_d): yield 1. + sample * m_d for sample in xrange(len_s): yield s for sample in xrange(len_r): yield s + sample * m_r
python
def adsr(dur, a, d, s, r): """ Linear ADSR envelope. Parameters ---------- dur : Duration, in number of samples, including the release time. a : "Attack" time, in number of samples. d : "Decay" time, in number of samples. s : "Sustain" amplitude level (should be based on attack amplitude). r : "Release" time, in number of samples. Returns ------- Stream instance yielding a finite ADSR envelope, starting and finishing with 0.0, having peak value of 1.0. """ m_a = 1. / a m_d = (s - 1.) / d m_r = - s * 1. / r len_a = int(a + .5) len_d = int(d + .5) len_r = int(r + .5) len_s = int(dur + .5) - len_a - len_d - len_r for sample in xrange(len_a): yield sample * m_a for sample in xrange(len_d): yield 1. + sample * m_d for sample in xrange(len_s): yield s for sample in xrange(len_r): yield s + sample * m_r
[ "def", "adsr", "(", "dur", ",", "a", ",", "d", ",", "s", ",", "r", ")", ":", "m_a", "=", "1.", "/", "a", "m_d", "=", "(", "s", "-", "1.", ")", "/", "d", "m_r", "=", "-", "s", "*", "1.", "/", "r", "len_a", "=", "int", "(", "a", "+", ...
Linear ADSR envelope. Parameters ---------- dur : Duration, in number of samples, including the release time. a : "Attack" time, in number of samples. d : "Decay" time, in number of samples. s : "Sustain" amplitude level (should be based on attack amplitude). r : "Release" time, in number of samples. Returns ------- Stream instance yielding a finite ADSR envelope, starting and finishing with 0.0, having peak value of 1.0.
[ "Linear", "ADSR", "envelope", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L351-L388
train
210,268
danilobellini/audiolazy
audiolazy/lazy_synth.py
white_noise
def white_noise(dur=None, low=-1., high=1.): """ White noise stream generator. Parameters ---------- dur : Duration, in number of samples; endless if not given (or None). low, high : Lower and higher limits. Defaults to the [-1; 1] range. Returns ------- Stream yielding random numbers between -1 and 1. """ if dur is None or (isinf(dur) and dur > 0): while True: yield random.uniform(low, high) for x in xrange(rint(dur)): yield random.uniform(low, high)
python
def white_noise(dur=None, low=-1., high=1.): """ White noise stream generator. Parameters ---------- dur : Duration, in number of samples; endless if not given (or None). low, high : Lower and higher limits. Defaults to the [-1; 1] range. Returns ------- Stream yielding random numbers between -1 and 1. """ if dur is None or (isinf(dur) and dur > 0): while True: yield random.uniform(low, high) for x in xrange(rint(dur)): yield random.uniform(low, high)
[ "def", "white_noise", "(", "dur", "=", "None", ",", "low", "=", "-", "1.", ",", "high", "=", "1.", ")", ":", "if", "dur", "is", "None", "or", "(", "isinf", "(", "dur", ")", "and", "dur", ">", "0", ")", ":", "while", "True", ":", "yield", "ran...
White noise stream generator. Parameters ---------- dur : Duration, in number of samples; endless if not given (or None). low, high : Lower and higher limits. Defaults to the [-1; 1] range. Returns ------- Stream yielding random numbers between -1 and 1.
[ "White", "noise", "stream", "generator", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L392-L412
train
210,269
danilobellini/audiolazy
audiolazy/lazy_synth.py
sinusoid
def sinusoid(freq, phase=0.): """ Sinusoid based on the optimized math.sin """ # When at 44100 samples / sec, 5 seconds of this leads to an error of 8e-14 # peak to peak. That's fairly enough. for n in modulo_counter(start=phase, modulo=2 * pi, step=freq): yield sin(n)
python
def sinusoid(freq, phase=0.): """ Sinusoid based on the optimized math.sin """ # When at 44100 samples / sec, 5 seconds of this leads to an error of 8e-14 # peak to peak. That's fairly enough. for n in modulo_counter(start=phase, modulo=2 * pi, step=freq): yield sin(n)
[ "def", "sinusoid", "(", "freq", ",", "phase", "=", "0.", ")", ":", "# When at 44100 samples / sec, 5 seconds of this leads to an error of 8e-14", "# peak to peak. That's fairly enough.", "for", "n", "in", "modulo_counter", "(", "start", "=", "phase", ",", "modulo", "=", ...
Sinusoid based on the optimized math.sin
[ "Sinusoid", "based", "on", "the", "optimized", "math", ".", "sin" ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L584-L591
train
210,270
danilobellini/audiolazy
audiolazy/lazy_synth.py
impulse
def impulse(dur=None, one=1., zero=0.): """ Impulse stream generator. Parameters ---------- dur : Duration, in number of samples; endless if not given. Returns ------- Stream that repeats "0.0" during a given time duration (if any) or endlessly, but starts with one (and only one) "1.0". """ if dur is None or (isinf(dur) and dur > 0): yield one while True: yield zero elif dur >= .5: num_samples = int(dur - .5) yield one for x in xrange(num_samples): yield zero
python
def impulse(dur=None, one=1., zero=0.): """ Impulse stream generator. Parameters ---------- dur : Duration, in number of samples; endless if not given. Returns ------- Stream that repeats "0.0" during a given time duration (if any) or endlessly, but starts with one (and only one) "1.0". """ if dur is None or (isinf(dur) and dur > 0): yield one while True: yield zero elif dur >= .5: num_samples = int(dur - .5) yield one for x in xrange(num_samples): yield zero
[ "def", "impulse", "(", "dur", "=", "None", ",", "one", "=", "1.", ",", "zero", "=", "0.", ")", ":", "if", "dur", "is", "None", "or", "(", "isinf", "(", "dur", ")", "and", "dur", ">", "0", ")", ":", "yield", "one", "while", "True", ":", "yield...
Impulse stream generator. Parameters ---------- dur : Duration, in number of samples; endless if not given. Returns ------- Stream that repeats "0.0" during a given time duration (if any) or endlessly, but starts with one (and only one) "1.0".
[ "Impulse", "stream", "generator", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L595-L618
train
210,271
danilobellini/audiolazy
audiolazy/lazy_synth.py
karplus_strong
def karplus_strong(freq, tau=2e4, memory=white_noise): """ Karplus-Strong "digitar" synthesis algorithm. Parameters ---------- freq : Frequency, in rad/sample. tau : Time decay (up to ``1/e``, or -8.686 dB), in number of samples. Defaults to 2e4. Be careful: using the default value will make duration different on each sample rate value. Use ``sHz`` if you need that independent from the sample rate and in seconds unit. memory : Memory data for the comb filter (delayed "output" data in memory). Defaults to the ``white_noise`` function. Returns ------- Stream instance with the synthesized data. Note ---- The fractional delays are solved by exponent linearization. See Also -------- sHz : Second and hertz constants from samples/second rate. white_noise : White noise stream generator. """ return comb.tau(2 * pi / freq, tau).linearize()(zeros(), memory=memory)
python
def karplus_strong(freq, tau=2e4, memory=white_noise): """ Karplus-Strong "digitar" synthesis algorithm. Parameters ---------- freq : Frequency, in rad/sample. tau : Time decay (up to ``1/e``, or -8.686 dB), in number of samples. Defaults to 2e4. Be careful: using the default value will make duration different on each sample rate value. Use ``sHz`` if you need that independent from the sample rate and in seconds unit. memory : Memory data for the comb filter (delayed "output" data in memory). Defaults to the ``white_noise`` function. Returns ------- Stream instance with the synthesized data. Note ---- The fractional delays are solved by exponent linearization. See Also -------- sHz : Second and hertz constants from samples/second rate. white_noise : White noise stream generator. """ return comb.tau(2 * pi / freq, tau).linearize()(zeros(), memory=memory)
[ "def", "karplus_strong", "(", "freq", ",", "tau", "=", "2e4", ",", "memory", "=", "white_noise", ")", ":", "return", "comb", ".", "tau", "(", "2", "*", "pi", "/", "freq", ",", "tau", ")", ".", "linearize", "(", ")", "(", "zeros", "(", ")", ",", ...
Karplus-Strong "digitar" synthesis algorithm. Parameters ---------- freq : Frequency, in rad/sample. tau : Time decay (up to ``1/e``, or -8.686 dB), in number of samples. Defaults to 2e4. Be careful: using the default value will make duration different on each sample rate value. Use ``sHz`` if you need that independent from the sample rate and in seconds unit. memory : Memory data for the comb filter (delayed "output" data in memory). Defaults to the ``white_noise`` function. Returns ------- Stream instance with the synthesized data. Note ---- The fractional delays are solved by exponent linearization. See Also -------- sHz : Second and hertz constants from samples/second rate. white_noise : White noise stream generator.
[ "Karplus", "-", "Strong", "digitar", "synthesis", "algorithm", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L621-L654
train
210,272
danilobellini/audiolazy
audiolazy/lazy_synth.py
TableLookup.normalize
def normalize(self): """ Returns a new table with values ranging from -1 to 1, reaching at least one of these, unless there's no data. """ max_abs = max(self.table, key=abs) if max_abs == 0: raise ValueError("Can't normalize zeros") return self / max_abs
python
def normalize(self): """ Returns a new table with values ranging from -1 to 1, reaching at least one of these, unless there's no data. """ max_abs = max(self.table, key=abs) if max_abs == 0: raise ValueError("Can't normalize zeros") return self / max_abs
[ "def", "normalize", "(", "self", ")", ":", "max_abs", "=", "max", "(", "self", ".", "table", ",", "key", "=", "abs", ")", "if", "max_abs", "==", "0", ":", "raise", "ValueError", "(", "\"Can't normalize zeros\"", ")", "return", "self", "/", "max_abs" ]
Returns a new table with values ranging from -1 to 1, reaching at least one of these, unless there's no data.
[ "Returns", "a", "new", "table", "with", "values", "ranging", "from", "-", "1", "to", "1", "reaching", "at", "least", "one", "of", "these", "unless", "there", "s", "no", "data", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L565-L573
train
210,273
danilobellini/audiolazy
audiolazy/lazy_core.py
StrategyDict.strategy
def strategy(self, *names, **kwargs): """ StrategyDict wrapping method for adding a new strategy. Parameters ---------- *names : Positional arguments with all names (strings) that could be used to call the strategy to be added, to be used both as key items and as attribute names. keep_name : Boolean keyword-only parameter for choosing whether the ``__name__`` attribute of the decorated/wrapped function should be changed or kept. Defaults to False (i.e., changes the name by default). Returns ------- A decorator/wrapper function to be used once on the new strategy to be added. Example ------- Let's create a StrategyDict that knows its name: >>> txt_proc = StrategyDict("txt_proc") Add a first strategy ``swapcase``, using this method as a decorator factory: >>> @txt_proc.strategy("swapcase") ... def txt_proc(txt): ... return txt.swapcase() Let's do it again, but wrapping the strategy functions inline. First two strategies have multiple names, the last keeps the function name, which would otherwise be replaced by the first given name: >>> txt_proc.strategy("lower", "low")(lambda txt: txt.lower()) {(...): <function ... at 0x...>, (...): <function ... at 0x...>} >>> txt_proc.strategy("upper", "up")(lambda txt: txt.upper()) {...} >>> txt_proc.strategy("keep", keep_name=True)(lambda txt: txt) {...} We can now iterate through the strategies to call them or see their function names >>> sorted(st("Just a Test") for st in txt_proc) ['JUST A TEST', 'Just a Test', 'jUST A tEST', 'just a test'] >>> sorted(st.__name__ for st in txt_proc) # Just the first name ['<lambda>', 'lower', 'swapcase', 'upper'] Calling a single strategy: >>> txt_proc.low("TeStInG") 'testing' >>> txt_proc["upper"]("TeStInG") 'TESTING' >>> txt_proc("TeStInG") # Default is the first: swapcase 'tEsTiNg' >>> txt_proc.default("TeStInG") 'tEsTiNg' >>> txt_proc.default = txt_proc.up # Manually changing the default >>> txt_proc("TeStInG") 'TESTING' Hint ---- Default strategy is the one stored as the ``default`` attribute, you can change or remove it at any time. When removing all keys that are assigned to the default strategy, the default attribute will be removed from the StrategyDict instance as well. The first strategy added afterwards is the one that will become the new default, unless the attribute is created or changed manually. """ def decorator(func): keep_name = kwargs.pop("keep_name", False) if kwargs: key = next(iter(kwargs)) raise TypeError("Unknown keyword argument '{}'".format(key)) if not keep_name: func.__name__ = str(names[0]) self[names] = func return self return decorator
python
def strategy(self, *names, **kwargs): """ StrategyDict wrapping method for adding a new strategy. Parameters ---------- *names : Positional arguments with all names (strings) that could be used to call the strategy to be added, to be used both as key items and as attribute names. keep_name : Boolean keyword-only parameter for choosing whether the ``__name__`` attribute of the decorated/wrapped function should be changed or kept. Defaults to False (i.e., changes the name by default). Returns ------- A decorator/wrapper function to be used once on the new strategy to be added. Example ------- Let's create a StrategyDict that knows its name: >>> txt_proc = StrategyDict("txt_proc") Add a first strategy ``swapcase``, using this method as a decorator factory: >>> @txt_proc.strategy("swapcase") ... def txt_proc(txt): ... return txt.swapcase() Let's do it again, but wrapping the strategy functions inline. First two strategies have multiple names, the last keeps the function name, which would otherwise be replaced by the first given name: >>> txt_proc.strategy("lower", "low")(lambda txt: txt.lower()) {(...): <function ... at 0x...>, (...): <function ... at 0x...>} >>> txt_proc.strategy("upper", "up")(lambda txt: txt.upper()) {...} >>> txt_proc.strategy("keep", keep_name=True)(lambda txt: txt) {...} We can now iterate through the strategies to call them or see their function names >>> sorted(st("Just a Test") for st in txt_proc) ['JUST A TEST', 'Just a Test', 'jUST A tEST', 'just a test'] >>> sorted(st.__name__ for st in txt_proc) # Just the first name ['<lambda>', 'lower', 'swapcase', 'upper'] Calling a single strategy: >>> txt_proc.low("TeStInG") 'testing' >>> txt_proc["upper"]("TeStInG") 'TESTING' >>> txt_proc("TeStInG") # Default is the first: swapcase 'tEsTiNg' >>> txt_proc.default("TeStInG") 'tEsTiNg' >>> txt_proc.default = txt_proc.up # Manually changing the default >>> txt_proc("TeStInG") 'TESTING' Hint ---- Default strategy is the one stored as the ``default`` attribute, you can change or remove it at any time. When removing all keys that are assigned to the default strategy, the default attribute will be removed from the StrategyDict instance as well. The first strategy added afterwards is the one that will become the new default, unless the attribute is created or changed manually. """ def decorator(func): keep_name = kwargs.pop("keep_name", False) if kwargs: key = next(iter(kwargs)) raise TypeError("Unknown keyword argument '{}'".format(key)) if not keep_name: func.__name__ = str(names[0]) self[names] = func return self return decorator
[ "def", "strategy", "(", "self", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "keep_name", "=", "kwargs", ".", "pop", "(", "\"keep_name\"", ",", "False", ")", "if", "kwargs", ":", "key", "=", "next...
StrategyDict wrapping method for adding a new strategy. Parameters ---------- *names : Positional arguments with all names (strings) that could be used to call the strategy to be added, to be used both as key items and as attribute names. keep_name : Boolean keyword-only parameter for choosing whether the ``__name__`` attribute of the decorated/wrapped function should be changed or kept. Defaults to False (i.e., changes the name by default). Returns ------- A decorator/wrapper function to be used once on the new strategy to be added. Example ------- Let's create a StrategyDict that knows its name: >>> txt_proc = StrategyDict("txt_proc") Add a first strategy ``swapcase``, using this method as a decorator factory: >>> @txt_proc.strategy("swapcase") ... def txt_proc(txt): ... return txt.swapcase() Let's do it again, but wrapping the strategy functions inline. First two strategies have multiple names, the last keeps the function name, which would otherwise be replaced by the first given name: >>> txt_proc.strategy("lower", "low")(lambda txt: txt.lower()) {(...): <function ... at 0x...>, (...): <function ... at 0x...>} >>> txt_proc.strategy("upper", "up")(lambda txt: txt.upper()) {...} >>> txt_proc.strategy("keep", keep_name=True)(lambda txt: txt) {...} We can now iterate through the strategies to call them or see their function names >>> sorted(st("Just a Test") for st in txt_proc) ['JUST A TEST', 'Just a Test', 'jUST A tEST', 'just a test'] >>> sorted(st.__name__ for st in txt_proc) # Just the first name ['<lambda>', 'lower', 'swapcase', 'upper'] Calling a single strategy: >>> txt_proc.low("TeStInG") 'testing' >>> txt_proc["upper"]("TeStInG") 'TESTING' >>> txt_proc("TeStInG") # Default is the first: swapcase 'tEsTiNg' >>> txt_proc.default("TeStInG") 'tEsTiNg' >>> txt_proc.default = txt_proc.up # Manually changing the default >>> txt_proc("TeStInG") 'TESTING' Hint ---- Default strategy is the one stored as the ``default`` attribute, you can change or remove it at any time. When removing all keys that are assigned to the default strategy, the default attribute will be removed from the StrategyDict instance as well. The first strategy added afterwards is the one that will become the new default, unless the attribute is created or changed manually.
[ "StrategyDict", "wrapping", "method", "for", "adding", "a", "new", "strategy", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_core.py#L535-L619
train
210,274
danilobellini/audiolazy
docs/make_all_docs.py
call_sphinx
def call_sphinx(out_type, build_dir = "build"): """ Call the ``sphinx-build`` for the given output type and the ``make`` when the target has this possibility. Parameters ---------- out_type : A builder name for ``sphinx-build``. See the full list at `<http://sphinx-doc.org/invocation.html>`_. build_dir : Directory for storing the output. Defaults to "build". """ sphinx_string = sphinx_template.format(build_dir=build_dir, out_type=out_type) if sphinx.main(shlex.split(sphinx_string)) != 0: raise RuntimeError("Something went wrong while building '{0}'" .format(out_type)) if out_type in make_target: make_string = make_template.format(build_dir=build_dir, out_type=out_type, make_param=make_target[out_type]) call(shlex.split(make_string))
python
def call_sphinx(out_type, build_dir = "build"): """ Call the ``sphinx-build`` for the given output type and the ``make`` when the target has this possibility. Parameters ---------- out_type : A builder name for ``sphinx-build``. See the full list at `<http://sphinx-doc.org/invocation.html>`_. build_dir : Directory for storing the output. Defaults to "build". """ sphinx_string = sphinx_template.format(build_dir=build_dir, out_type=out_type) if sphinx.main(shlex.split(sphinx_string)) != 0: raise RuntimeError("Something went wrong while building '{0}'" .format(out_type)) if out_type in make_target: make_string = make_template.format(build_dir=build_dir, out_type=out_type, make_param=make_target[out_type]) call(shlex.split(make_string))
[ "def", "call_sphinx", "(", "out_type", ",", "build_dir", "=", "\"build\"", ")", ":", "sphinx_string", "=", "sphinx_template", ".", "format", "(", "build_dir", "=", "build_dir", ",", "out_type", "=", "out_type", ")", "if", "sphinx", ".", "main", "(", "shlex",...
Call the ``sphinx-build`` for the given output type and the ``make`` when the target has this possibility. Parameters ---------- out_type : A builder name for ``sphinx-build``. See the full list at `<http://sphinx-doc.org/invocation.html>`_. build_dir : Directory for storing the output. Defaults to "build".
[ "Call", "the", "sphinx", "-", "build", "for", "the", "given", "output", "type", "and", "the", "make", "when", "the", "target", "has", "this", "possibility", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/docs/make_all_docs.py#L37-L60
train
210,275
danilobellini/audiolazy
audiolazy/lazy_lpc.py
levinson_durbin
def levinson_durbin(acdata, order=None): """ Solve the Yule-Walker linear system of equations. They're given by: .. math:: R . a = r where :math:`R` is a simmetric Toeplitz matrix where each element are lags from the given autocorrelation list. :math:`R` and :math:`r` are defined (Python indexing starts with zero and slices don't include the last element): .. math:: R[i][j] = acdata[abs(j - i)] r = acdata[1 : order + 1] Parameters ---------- acdata : Autocorrelation lag list, commonly the ``acorr`` function output. order : The order of the resulting ZFilter object. Defaults to ``len(acdata) - 1``. Returns ------- A FIR filter, as a ZFilter object. The mean squared error over the given data (variance of the white noise) is in its "error" attribute. See Also -------- acorr: Calculate the autocorrelation of a given block. lpc : Calculate the Linear Predictive Coding (LPC) coefficients. parcor : Partial correlation coefficients (PARCOR), or reflection coefficients, relative to the lattice implementation of a filter, obtained by reversing the Levinson-Durbin algorithm. Examples -------- >>> data = [2, 2, 0, 0, -1, -1, 0, 0, 1, 1] >>> acdata = acorr(data) >>> acdata [12, 6, 0, -3, -6, -3, 0, 2, 4, 2] >>> ldfilt = levinson_durbin(acorr(data), 3) >>> ldfilt 1 - 0.625 * z^-1 + 0.25 * z^-2 + 0.125 * z^-3 >>> ldfilt.error # Squared! See lpc for more information about this 7.875 Notes ----- The Levinson-Durbin algorithm used to solve the equations needs :math:`O(order^2)` floating point operations. """ if order is None: order = len(acdata) - 1 elif order >= len(acdata): acdata = Stream(acdata).append(0).take(order + 1) # Inner product for filters based on above statistics def inner(a, b): # Be careful, this depends on acdata !!! return sum(acdata[abs(i-j)] * ai * bj for i, ai in enumerate(a.numlist) for j, bj in enumerate(b.numlist) ) try: A = ZFilter(1) for m in xrange(1, order + 1): B = A(1 / z) * z ** -m A -= inner(A, z ** -m) / inner(B, B) * B except ZeroDivisionError: raise ParCorError("Can't find next PARCOR coefficient") A.error = inner(A, A) return A
python
def levinson_durbin(acdata, order=None): """ Solve the Yule-Walker linear system of equations. They're given by: .. math:: R . a = r where :math:`R` is a simmetric Toeplitz matrix where each element are lags from the given autocorrelation list. :math:`R` and :math:`r` are defined (Python indexing starts with zero and slices don't include the last element): .. math:: R[i][j] = acdata[abs(j - i)] r = acdata[1 : order + 1] Parameters ---------- acdata : Autocorrelation lag list, commonly the ``acorr`` function output. order : The order of the resulting ZFilter object. Defaults to ``len(acdata) - 1``. Returns ------- A FIR filter, as a ZFilter object. The mean squared error over the given data (variance of the white noise) is in its "error" attribute. See Also -------- acorr: Calculate the autocorrelation of a given block. lpc : Calculate the Linear Predictive Coding (LPC) coefficients. parcor : Partial correlation coefficients (PARCOR), or reflection coefficients, relative to the lattice implementation of a filter, obtained by reversing the Levinson-Durbin algorithm. Examples -------- >>> data = [2, 2, 0, 0, -1, -1, 0, 0, 1, 1] >>> acdata = acorr(data) >>> acdata [12, 6, 0, -3, -6, -3, 0, 2, 4, 2] >>> ldfilt = levinson_durbin(acorr(data), 3) >>> ldfilt 1 - 0.625 * z^-1 + 0.25 * z^-2 + 0.125 * z^-3 >>> ldfilt.error # Squared! See lpc for more information about this 7.875 Notes ----- The Levinson-Durbin algorithm used to solve the equations needs :math:`O(order^2)` floating point operations. """ if order is None: order = len(acdata) - 1 elif order >= len(acdata): acdata = Stream(acdata).append(0).take(order + 1) # Inner product for filters based on above statistics def inner(a, b): # Be careful, this depends on acdata !!! return sum(acdata[abs(i-j)] * ai * bj for i, ai in enumerate(a.numlist) for j, bj in enumerate(b.numlist) ) try: A = ZFilter(1) for m in xrange(1, order + 1): B = A(1 / z) * z ** -m A -= inner(A, z ** -m) / inner(B, B) * B except ZeroDivisionError: raise ParCorError("Can't find next PARCOR coefficient") A.error = inner(A, A) return A
[ "def", "levinson_durbin", "(", "acdata", ",", "order", "=", "None", ")", ":", "if", "order", "is", "None", ":", "order", "=", "len", "(", "acdata", ")", "-", "1", "elif", "order", ">=", "len", "(", "acdata", ")", ":", "acdata", "=", "Stream", "(", ...
Solve the Yule-Walker linear system of equations. They're given by: .. math:: R . a = r where :math:`R` is a simmetric Toeplitz matrix where each element are lags from the given autocorrelation list. :math:`R` and :math:`r` are defined (Python indexing starts with zero and slices don't include the last element): .. math:: R[i][j] = acdata[abs(j - i)] r = acdata[1 : order + 1] Parameters ---------- acdata : Autocorrelation lag list, commonly the ``acorr`` function output. order : The order of the resulting ZFilter object. Defaults to ``len(acdata) - 1``. Returns ------- A FIR filter, as a ZFilter object. The mean squared error over the given data (variance of the white noise) is in its "error" attribute. See Also -------- acorr: Calculate the autocorrelation of a given block. lpc : Calculate the Linear Predictive Coding (LPC) coefficients. parcor : Partial correlation coefficients (PARCOR), or reflection coefficients, relative to the lattice implementation of a filter, obtained by reversing the Levinson-Durbin algorithm. Examples -------- >>> data = [2, 2, 0, 0, -1, -1, 0, 0, 1, 1] >>> acdata = acorr(data) >>> acdata [12, 6, 0, -3, -6, -3, 0, 2, 4, 2] >>> ldfilt = levinson_durbin(acorr(data), 3) >>> ldfilt 1 - 0.625 * z^-1 + 0.25 * z^-2 + 0.125 * z^-3 >>> ldfilt.error # Squared! See lpc for more information about this 7.875 Notes ----- The Levinson-Durbin algorithm used to solve the equations needs :math:`O(order^2)` floating point operations.
[ "Solve", "the", "Yule", "-", "Walker", "linear", "system", "of", "equations", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_lpc.py#L52-L136
train
210,276
danilobellini/audiolazy
docs/conf.py
should_skip
def should_skip(app, what, name, obj, skip, options): """ Callback object chooser function for docstring documentation. """ if name in ["__doc__", "__module__", "__dict__", "__weakref__", "__abstractmethods__" ] or name.startswith("_abc_"): return True return False
python
def should_skip(app, what, name, obj, skip, options): """ Callback object chooser function for docstring documentation. """ if name in ["__doc__", "__module__", "__dict__", "__weakref__", "__abstractmethods__" ] or name.startswith("_abc_"): return True return False
[ "def", "should_skip", "(", "app", ",", "what", ",", "name", ",", "obj", ",", "skip", ",", "options", ")", ":", "if", "name", "in", "[", "\"__doc__\"", ",", "\"__module__\"", ",", "\"__dict__\"", ",", "\"__weakref__\"", ",", "\"__abstractmethods__\"", "]", ...
Callback object chooser function for docstring documentation.
[ "Callback", "object", "chooser", "function", "for", "docstring", "documentation", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/docs/conf.py#L212-L221
train
210,277
danilobellini/audiolazy
docs/conf.py
setup
def setup(app): """ Just connects the docstring pre_processor and should_skip functions to be applied on all docstrings. """ app.connect('autodoc-process-docstring', lambda *args: pre_processor(*args, namer=audiolazy_namer)) app.connect('autodoc-skip-member', should_skip)
python
def setup(app): """ Just connects the docstring pre_processor and should_skip functions to be applied on all docstrings. """ app.connect('autodoc-process-docstring', lambda *args: pre_processor(*args, namer=audiolazy_namer)) app.connect('autodoc-skip-member', should_skip)
[ "def", "setup", "(", "app", ")", ":", "app", ".", "connect", "(", "'autodoc-process-docstring'", ",", "lambda", "*", "args", ":", "pre_processor", "(", "*", "args", ",", "namer", "=", "audiolazy_namer", ")", ")", "app", ".", "connect", "(", "'autodoc-skip-...
Just connects the docstring pre_processor and should_skip functions to be applied on all docstrings.
[ "Just", "connects", "the", "docstring", "pre_processor", "and", "should_skip", "functions", "to", "be", "applied", "on", "all", "docstrings", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/docs/conf.py#L224-L232
train
210,278
danilobellini/audiolazy
docs/conf.py
newest_file
def newest_file(file_iterable): """ Returns the name of the newest file given an iterable of file names. """ return max(file_iterable, key=lambda fname: os.path.getmtime(fname))
python
def newest_file(file_iterable): """ Returns the name of the newest file given an iterable of file names. """ return max(file_iterable, key=lambda fname: os.path.getmtime(fname))
[ "def", "newest_file", "(", "file_iterable", ")", ":", "return", "max", "(", "file_iterable", ",", "key", "=", "lambda", "fname", ":", "os", ".", "path", ".", "getmtime", "(", "fname", ")", ")" ]
Returns the name of the newest file given an iterable of file names.
[ "Returns", "the", "name", "of", "the", "newest", "file", "given", "an", "iterable", "of", "file", "names", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/docs/conf.py#L250-L255
train
210,279
danilobellini/audiolazy
examples/window_comparison_harris.py
overlap_correlation
def overlap_correlation(wnd, hop): """ Overlap correlation percent for the given overlap hop in samples. """ return sum(wnd * Stream(wnd).skip(hop)) / sum(el ** 2 for el in wnd)
python
def overlap_correlation(wnd, hop): """ Overlap correlation percent for the given overlap hop in samples. """ return sum(wnd * Stream(wnd).skip(hop)) / sum(el ** 2 for el in wnd)
[ "def", "overlap_correlation", "(", "wnd", ",", "hop", ")", ":", "return", "sum", "(", "wnd", "*", "Stream", "(", "wnd", ")", ".", "skip", "(", "hop", ")", ")", "/", "sum", "(", "el", "**", "2", "for", "el", "in", "wnd", ")" ]
Overlap correlation percent for the given overlap hop in samples.
[ "Overlap", "correlation", "percent", "for", "the", "given", "overlap", "hop", "in", "samples", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/window_comparison_harris.py#L47-L49
train
210,280
danilobellini/audiolazy
examples/window_comparison_harris.py
scalloping_loss
def scalloping_loss(wnd): """ Positive number with the scalloping loss in dB. """ return -dB20(abs(sum(wnd * cexp(line(len(wnd), 0, -1j * pi)))) / sum(wnd))
python
def scalloping_loss(wnd): """ Positive number with the scalloping loss in dB. """ return -dB20(abs(sum(wnd * cexp(line(len(wnd), 0, -1j * pi)))) / sum(wnd))
[ "def", "scalloping_loss", "(", "wnd", ")", ":", "return", "-", "dB20", "(", "abs", "(", "sum", "(", "wnd", "*", "cexp", "(", "line", "(", "len", "(", "wnd", ")", ",", "0", ",", "-", "1j", "*", "pi", ")", ")", ")", ")", "/", "sum", "(", "wnd...
Positive number with the scalloping loss in dB.
[ "Positive", "number", "with", "the", "scalloping", "loss", "in", "dB", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/window_comparison_harris.py#L51-L53
train
210,281
danilobellini/audiolazy
examples/window_comparison_harris.py
find_xdb_bin
def find_xdb_bin(wnd, power=.5, res=1500): """ A not so fast way to find the x-dB cutoff frequency "bin" index. Parameters ---------- wnd: The window itself as an iterable. power: The power value (squared amplitude) where the x-dB value should lie, using ``x = dB10(power)``. res : Zero-padding factor. 1 for no zero-padding, 2 for twice the length, etc.. """ spectrum = dB20(rfft(wnd, res * len(wnd))) root_at_xdb = spectrum - spectrum[0] - dB10(power) return next(i for i, el in enumerate(zcross(root_at_xdb)) if el) / res
python
def find_xdb_bin(wnd, power=.5, res=1500): """ A not so fast way to find the x-dB cutoff frequency "bin" index. Parameters ---------- wnd: The window itself as an iterable. power: The power value (squared amplitude) where the x-dB value should lie, using ``x = dB10(power)``. res : Zero-padding factor. 1 for no zero-padding, 2 for twice the length, etc.. """ spectrum = dB20(rfft(wnd, res * len(wnd))) root_at_xdb = spectrum - spectrum[0] - dB10(power) return next(i for i, el in enumerate(zcross(root_at_xdb)) if el) / res
[ "def", "find_xdb_bin", "(", "wnd", ",", "power", "=", ".5", ",", "res", "=", "1500", ")", ":", "spectrum", "=", "dB20", "(", "rfft", "(", "wnd", ",", "res", "*", "len", "(", "wnd", ")", ")", ")", "root_at_xdb", "=", "spectrum", "-", "spectrum", "...
A not so fast way to find the x-dB cutoff frequency "bin" index. Parameters ---------- wnd: The window itself as an iterable. power: The power value (squared amplitude) where the x-dB value should lie, using ``x = dB10(power)``. res : Zero-padding factor. 1 for no zero-padding, 2 for twice the length, etc..
[ "A", "not", "so", "fast", "way", "to", "find", "the", "x", "-", "dB", "cutoff", "frequency", "bin", "index", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/window_comparison_harris.py#L63-L79
train
210,282
danilobellini/audiolazy
audiolazy/lazy_misc.py
rint
def rint(x, step=1): """ Round to integer. Parameters ---------- x : Input number (integer or float) to be rounded. step : Quantization level (defaults to 1). If set to 2, the output will be the "best" even number. Result ------ The step multiple nearest to x. When x is exactly halfway between two possible outputs, it'll result the one farthest to zero. """ div, mod = divmod(x, step) err = min(step / 10., .1) result = div * step if x > 0: result += err elif x < 0: result -= err if (operator.ge if x >= 0 else operator.gt)(2 * mod, step): result += step return int(result)
python
def rint(x, step=1): """ Round to integer. Parameters ---------- x : Input number (integer or float) to be rounded. step : Quantization level (defaults to 1). If set to 2, the output will be the "best" even number. Result ------ The step multiple nearest to x. When x is exactly halfway between two possible outputs, it'll result the one farthest to zero. """ div, mod = divmod(x, step) err = min(step / 10., .1) result = div * step if x > 0: result += err elif x < 0: result -= err if (operator.ge if x >= 0 else operator.gt)(2 * mod, step): result += step return int(result)
[ "def", "rint", "(", "x", ",", "step", "=", "1", ")", ":", "div", ",", "mod", "=", "divmod", "(", "x", ",", "step", ")", "err", "=", "min", "(", "step", "/", "10.", ",", ".1", ")", "result", "=", "div", "*", "step", "if", "x", ">", "0", ":...
Round to integer. Parameters ---------- x : Input number (integer or float) to be rounded. step : Quantization level (defaults to 1). If set to 2, the output will be the "best" even number. Result ------ The step multiple nearest to x. When x is exactly halfway between two possible outputs, it'll result the one farthest to zero.
[ "Round", "to", "integer", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_misc.py#L40-L67
train
210,283
danilobellini/audiolazy
audiolazy/lazy_misc.py
blocks
def blocks(seq, size=None, hop=None, padval=0.): """ General iterable blockenizer. Generator that gets ``size`` elements from ``seq``, and outputs them in a collections.deque (mutable circular queue) sequence container. Next output starts ``hop`` elements after the first element in last output block. Last block may be appended with ``padval``, if needed to get the desired size. The ``seq`` can have hybrid / hetherogeneous data, it just need to be an iterable. You can use other type content as padval (e.g. None) to help segregate the padding at the end, if desired. Note ---- When hop is less than size, changing the returned contents will keep the new changed value in the next yielded container. """ # Initialization res = deque(maxlen=size) # Circular queue idx = 0 last_idx = size - 1 if hop is None: hop = size reinit_idx = size - hop # Yields each block, keeping last values when needed if hop <= size: for el in seq: res.append(el) if idx == last_idx: yield res idx = reinit_idx else: idx += 1 # Yields each block and skips (loses) data due to hop > size else: for el in seq: if idx < 0: # Skips data idx += 1 else: res.append(el) if idx == last_idx: yield res #res = dtype() idx = size-hop else: idx += 1 # Padding to finish if idx > max(size-hop, 0): for _ in xrange(idx,size): res.append(padval) yield res
python
def blocks(seq, size=None, hop=None, padval=0.): """ General iterable blockenizer. Generator that gets ``size`` elements from ``seq``, and outputs them in a collections.deque (mutable circular queue) sequence container. Next output starts ``hop`` elements after the first element in last output block. Last block may be appended with ``padval``, if needed to get the desired size. The ``seq`` can have hybrid / hetherogeneous data, it just need to be an iterable. You can use other type content as padval (e.g. None) to help segregate the padding at the end, if desired. Note ---- When hop is less than size, changing the returned contents will keep the new changed value in the next yielded container. """ # Initialization res = deque(maxlen=size) # Circular queue idx = 0 last_idx = size - 1 if hop is None: hop = size reinit_idx = size - hop # Yields each block, keeping last values when needed if hop <= size: for el in seq: res.append(el) if idx == last_idx: yield res idx = reinit_idx else: idx += 1 # Yields each block and skips (loses) data due to hop > size else: for el in seq: if idx < 0: # Skips data idx += 1 else: res.append(el) if idx == last_idx: yield res #res = dtype() idx = size-hop else: idx += 1 # Padding to finish if idx > max(size-hop, 0): for _ in xrange(idx,size): res.append(padval) yield res
[ "def", "blocks", "(", "seq", ",", "size", "=", "None", ",", "hop", "=", "None", ",", "padval", "=", "0.", ")", ":", "# Initialization", "res", "=", "deque", "(", "maxlen", "=", "size", ")", "# Circular queue", "idx", "=", "0", "last_idx", "=", "size"...
General iterable blockenizer. Generator that gets ``size`` elements from ``seq``, and outputs them in a collections.deque (mutable circular queue) sequence container. Next output starts ``hop`` elements after the first element in last output block. Last block may be appended with ``padval``, if needed to get the desired size. The ``seq`` can have hybrid / hetherogeneous data, it just need to be an iterable. You can use other type content as padval (e.g. None) to help segregate the padding at the end, if desired. Note ---- When hop is less than size, changing the returned contents will keep the new changed value in the next yielded container.
[ "General", "iterable", "blockenizer", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_misc.py#L70-L125
train
210,284
danilobellini/audiolazy
audiolazy/lazy_misc.py
elementwise
def elementwise(name="", pos=None): """ Function auto-map decorator broadcaster. Creates an "elementwise" decorator for one input parameter. To create such, it should know the name (for use as a keyword argument and the position "pos" (input as a positional argument). Without a name, only the positional argument will be used. Without both name and position, the first positional argument will be used. """ if (name == "") and (pos is None): pos = 0 def elementwise_decorator(func): """ Element-wise decorator for functions known to have 1 input and 1 output be applied directly on iterables. When made to work with more than 1 input, all "secondary" parameters will the same in all function calls (i.e., they will not even be a copy). """ @wraps(func) def wrapper(*args, **kwargs): # Find the possibly Iterable argument positional = (pos is not None) and (pos < len(args)) arg = args[pos] if positional else kwargs[name] if isinstance(arg, Iterable) and not isinstance(arg, STR_TYPES): if positional: data = (func(*(args[:pos] + (x,) + args[pos+1:]), **kwargs) for x in arg) else: data = (func(*args, **dict(it.chain(iteritems(kwargs), [(name, x)]))) for x in arg) # Generators should still return generators if isinstance(arg, SOME_GEN_TYPES): return data # Cast to numpy array or matrix, if needed, without actually # importing its package type_arg = type(arg) try: is_numpy = type_arg.__module__ == "numpy" except AttributeError: is_numpy = False if is_numpy: np_type = {"ndarray": sys.modules["numpy"].array, "matrix": sys.modules["numpy"].mat }[type_arg.__name__] return np_type(list(data)) # If it's a Stream, let's use the Stream constructor from .lazy_stream import Stream if issubclass(type_arg, Stream): return Stream(data) # Tuple, list, set, dict, deque, etc.. all falls here return type_arg(data) return func(*args, **kwargs) # wrapper returned value return wrapper # elementwise_decorator returned value return elementwise_decorator
python
def elementwise(name="", pos=None): """ Function auto-map decorator broadcaster. Creates an "elementwise" decorator for one input parameter. To create such, it should know the name (for use as a keyword argument and the position "pos" (input as a positional argument). Without a name, only the positional argument will be used. Without both name and position, the first positional argument will be used. """ if (name == "") and (pos is None): pos = 0 def elementwise_decorator(func): """ Element-wise decorator for functions known to have 1 input and 1 output be applied directly on iterables. When made to work with more than 1 input, all "secondary" parameters will the same in all function calls (i.e., they will not even be a copy). """ @wraps(func) def wrapper(*args, **kwargs): # Find the possibly Iterable argument positional = (pos is not None) and (pos < len(args)) arg = args[pos] if positional else kwargs[name] if isinstance(arg, Iterable) and not isinstance(arg, STR_TYPES): if positional: data = (func(*(args[:pos] + (x,) + args[pos+1:]), **kwargs) for x in arg) else: data = (func(*args, **dict(it.chain(iteritems(kwargs), [(name, x)]))) for x in arg) # Generators should still return generators if isinstance(arg, SOME_GEN_TYPES): return data # Cast to numpy array or matrix, if needed, without actually # importing its package type_arg = type(arg) try: is_numpy = type_arg.__module__ == "numpy" except AttributeError: is_numpy = False if is_numpy: np_type = {"ndarray": sys.modules["numpy"].array, "matrix": sys.modules["numpy"].mat }[type_arg.__name__] return np_type(list(data)) # If it's a Stream, let's use the Stream constructor from .lazy_stream import Stream if issubclass(type_arg, Stream): return Stream(data) # Tuple, list, set, dict, deque, etc.. all falls here return type_arg(data) return func(*args, **kwargs) # wrapper returned value return wrapper # elementwise_decorator returned value return elementwise_decorator
[ "def", "elementwise", "(", "name", "=", "\"\"", ",", "pos", "=", "None", ")", ":", "if", "(", "name", "==", "\"\"", ")", "and", "(", "pos", "is", "None", ")", ":", "pos", "=", "0", "def", "elementwise_decorator", "(", "func", ")", ":", "\"\"\"\n ...
Function auto-map decorator broadcaster. Creates an "elementwise" decorator for one input parameter. To create such, it should know the name (for use as a keyword argument and the position "pos" (input as a positional argument). Without a name, only the positional argument will be used. Without both name and position, the first positional argument will be used.
[ "Function", "auto", "-", "map", "decorator", "broadcaster", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_misc.py#L159-L224
train
210,285
danilobellini/audiolazy
audiolazy/lazy_misc.py
almost_eq
def almost_eq(a, b, bits=32, tol=1, ignore_type=True, pad=0.): """ Almost equal, based on the amount of floating point significand bits. Alternative to "a == b" for float numbers and iterables with float numbers, and tests for sequence contents (i.e., an elementwise a == b, that also works with generators, nested lists, nested generators, etc.). If the type of both the contents and the containers should be tested too, set the ignore_type keyword arg to False. Default version is based on 32 bits IEEE 754 format (23 bits significand). Could use 64 bits (52 bits significand) but needs a native float type with at least that size in bits. If a and b sizes differ, at least one will be padded with the pad input value to keep going with the comparison. Note ---- Be careful with endless generators! """ if not (ignore_type or type(a) == type(b)): return False is_it_a = isinstance(a, Iterable) is_it_b = isinstance(b, Iterable) if is_it_a != is_it_b: return False if is_it_a: return all(almost_eq.bits(ai, bi, bits, tol, ignore_type) for ai, bi in xzip_longest(a, b, fillvalue=pad)) significand = {32: 23, 64: 52, 80: 63, 128: 112 }[bits] # That doesn't include the sign bit power = tol - significand - 1 return abs(a - b) <= 2 ** power * abs(a + b)
python
def almost_eq(a, b, bits=32, tol=1, ignore_type=True, pad=0.): """ Almost equal, based on the amount of floating point significand bits. Alternative to "a == b" for float numbers and iterables with float numbers, and tests for sequence contents (i.e., an elementwise a == b, that also works with generators, nested lists, nested generators, etc.). If the type of both the contents and the containers should be tested too, set the ignore_type keyword arg to False. Default version is based on 32 bits IEEE 754 format (23 bits significand). Could use 64 bits (52 bits significand) but needs a native float type with at least that size in bits. If a and b sizes differ, at least one will be padded with the pad input value to keep going with the comparison. Note ---- Be careful with endless generators! """ if not (ignore_type or type(a) == type(b)): return False is_it_a = isinstance(a, Iterable) is_it_b = isinstance(b, Iterable) if is_it_a != is_it_b: return False if is_it_a: return all(almost_eq.bits(ai, bi, bits, tol, ignore_type) for ai, bi in xzip_longest(a, b, fillvalue=pad)) significand = {32: 23, 64: 52, 80: 63, 128: 112 }[bits] # That doesn't include the sign bit power = tol - significand - 1 return abs(a - b) <= 2 ** power * abs(a + b)
[ "def", "almost_eq", "(", "a", ",", "b", ",", "bits", "=", "32", ",", "tol", "=", "1", ",", "ignore_type", "=", "True", ",", "pad", "=", "0.", ")", ":", "if", "not", "(", "ignore_type", "or", "type", "(", "a", ")", "==", "type", "(", "b", ")",...
Almost equal, based on the amount of floating point significand bits. Alternative to "a == b" for float numbers and iterables with float numbers, and tests for sequence contents (i.e., an elementwise a == b, that also works with generators, nested lists, nested generators, etc.). If the type of both the contents and the containers should be tested too, set the ignore_type keyword arg to False. Default version is based on 32 bits IEEE 754 format (23 bits significand). Could use 64 bits (52 bits significand) but needs a native float type with at least that size in bits. If a and b sizes differ, at least one will be padded with the pad input value to keep going with the comparison. Note ---- Be careful with endless generators!
[ "Almost", "equal", "based", "on", "the", "amount", "of", "floating", "point", "significand", "bits", "." ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_misc.py#L231-L263
train
210,286
danilobellini/audiolazy
audiolazy/lazy_misc.py
cached
def cached(func): """ Cache decorator for a function without keyword arguments You can access the cache contents using the ``cache`` attribute in the resulting function, which is a dictionary mapping the arguments tuple to the previously returned function result. """ class Cache(dict): def __missing__(self, key): result = self[key] = func(*key) return result cache = Cache() f = wraps(func)(lambda *key: cache[key]) f.cache = cache return f
python
def cached(func): """ Cache decorator for a function without keyword arguments You can access the cache contents using the ``cache`` attribute in the resulting function, which is a dictionary mapping the arguments tuple to the previously returned function result. """ class Cache(dict): def __missing__(self, key): result = self[key] = func(*key) return result cache = Cache() f = wraps(func)(lambda *key: cache[key]) f.cache = cache return f
[ "def", "cached", "(", "func", ")", ":", "class", "Cache", "(", "dict", ")", ":", "def", "__missing__", "(", "self", ",", "key", ")", ":", "result", "=", "self", "[", "key", "]", "=", "func", "(", "*", "key", ")", "return", "result", "cache", "=",...
Cache decorator for a function without keyword arguments You can access the cache contents using the ``cache`` attribute in the resulting function, which is a dictionary mapping the arguments tuple to the previously returned function result.
[ "Cache", "decorator", "for", "a", "function", "without", "keyword", "arguments" ]
dba0a278937909980ed40b976d866b8e97c35dee
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_misc.py#L331-L346
train
210,287
akoumjian/datefinder
datefinder/__init__.py
find_dates
def find_dates(text, source=False, index=False, strict=False, base_date=None): """ Extract datetime strings from text :param text: A string that contains one or more natural language or literal datetime strings :type text: str|unicode :param source: Return the original string segment :type source: boolean :param index: Return the indices where the datetime string was located in text :type index: boolean :param strict: Only return datetimes with complete date information. For example: `July 2016` of `Monday` will not return datetimes. `May 16, 2015` will return datetimes. :type strict: boolean :param base_date: Set a default base datetime when parsing incomplete dates :type base_date: datetime :return: Returns a generator that produces :mod:`datetime.datetime` objects, or a tuple with the source text and index, if requested """ date_finder = DateFinder(base_date=base_date) return date_finder.find_dates(text, source=source, index=index, strict=strict)
python
def find_dates(text, source=False, index=False, strict=False, base_date=None): """ Extract datetime strings from text :param text: A string that contains one or more natural language or literal datetime strings :type text: str|unicode :param source: Return the original string segment :type source: boolean :param index: Return the indices where the datetime string was located in text :type index: boolean :param strict: Only return datetimes with complete date information. For example: `July 2016` of `Monday` will not return datetimes. `May 16, 2015` will return datetimes. :type strict: boolean :param base_date: Set a default base datetime when parsing incomplete dates :type base_date: datetime :return: Returns a generator that produces :mod:`datetime.datetime` objects, or a tuple with the source text and index, if requested """ date_finder = DateFinder(base_date=base_date) return date_finder.find_dates(text, source=source, index=index, strict=strict)
[ "def", "find_dates", "(", "text", ",", "source", "=", "False", ",", "index", "=", "False", ",", "strict", "=", "False", ",", "base_date", "=", "None", ")", ":", "date_finder", "=", "DateFinder", "(", "base_date", "=", "base_date", ")", "return", "date_fi...
Extract datetime strings from text :param text: A string that contains one or more natural language or literal datetime strings :type text: str|unicode :param source: Return the original string segment :type source: boolean :param index: Return the indices where the datetime string was located in text :type index: boolean :param strict: Only return datetimes with complete date information. For example: `July 2016` of `Monday` will not return datetimes. `May 16, 2015` will return datetimes. :type strict: boolean :param base_date: Set a default base datetime when parsing incomplete dates :type base_date: datetime :return: Returns a generator that produces :mod:`datetime.datetime` objects, or a tuple with the source text and index, if requested
[ "Extract", "datetime", "strings", "from", "text" ]
612e8b71e57b1083e1224412ba8fb8bce3810bdd
https://github.com/akoumjian/datefinder/blob/612e8b71e57b1083e1224412ba8fb8bce3810bdd/datefinder/__init__.py#L188-L215
train
210,288
akoumjian/datefinder
datefinder/__init__.py
DateFinder._add_tzinfo
def _add_tzinfo(self, datetime_obj, tz_string): """ take a naive datetime and add dateutil.tz.tzinfo object :param datetime_obj: naive datetime object :return: datetime object with tzinfo """ if datetime_obj is None: return None tzinfo_match = tz.gettz(tz_string) return datetime_obj.replace(tzinfo=tzinfo_match)
python
def _add_tzinfo(self, datetime_obj, tz_string): """ take a naive datetime and add dateutil.tz.tzinfo object :param datetime_obj: naive datetime object :return: datetime object with tzinfo """ if datetime_obj is None: return None tzinfo_match = tz.gettz(tz_string) return datetime_obj.replace(tzinfo=tzinfo_match)
[ "def", "_add_tzinfo", "(", "self", ",", "datetime_obj", ",", "tz_string", ")", ":", "if", "datetime_obj", "is", "None", ":", "return", "None", "tzinfo_match", "=", "tz", ".", "gettz", "(", "tz_string", ")", "return", "datetime_obj", ".", "replace", "(", "t...
take a naive datetime and add dateutil.tz.tzinfo object :param datetime_obj: naive datetime object :return: datetime object with tzinfo
[ "take", "a", "naive", "datetime", "and", "add", "dateutil", ".", "tz", ".", "tzinfo", "object" ]
612e8b71e57b1083e1224412ba8fb8bce3810bdd
https://github.com/akoumjian/datefinder/blob/612e8b71e57b1083e1224412ba8fb8bce3810bdd/datefinder/__init__.py#L84-L95
train
210,289
xolox/python-coloredlogs
coloredlogs/__init__.py
check_style
def check_style(value): """ Validate a logging format style. :param value: The logging format style to validate (any value). :returns: The logging format character (a string of one character). :raises: :exc:`~exceptions.ValueError` when the given style isn't supported. On Python 3.2+ this function accepts the logging format styles ``%``, ``{`` and ``$`` while on older versions only ``%`` is accepted (because older Python versions don't support alternative logging format styles). """ if sys.version_info[:2] >= (3, 2): if value not in FORMAT_STYLE_PATTERNS: msg = "Unsupported logging format style! (%r)" raise ValueError(format(msg, value)) elif value != DEFAULT_FORMAT_STYLE: msg = "Format string styles other than %r require Python 3.2+!" raise ValueError(msg, DEFAULT_FORMAT_STYLE) return value
python
def check_style(value): """ Validate a logging format style. :param value: The logging format style to validate (any value). :returns: The logging format character (a string of one character). :raises: :exc:`~exceptions.ValueError` when the given style isn't supported. On Python 3.2+ this function accepts the logging format styles ``%``, ``{`` and ``$`` while on older versions only ``%`` is accepted (because older Python versions don't support alternative logging format styles). """ if sys.version_info[:2] >= (3, 2): if value not in FORMAT_STYLE_PATTERNS: msg = "Unsupported logging format style! (%r)" raise ValueError(format(msg, value)) elif value != DEFAULT_FORMAT_STYLE: msg = "Format string styles other than %r require Python 3.2+!" raise ValueError(msg, DEFAULT_FORMAT_STYLE) return value
[ "def", "check_style", "(", "value", ")", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">=", "(", "3", ",", "2", ")", ":", "if", "value", "not", "in", "FORMAT_STYLE_PATTERNS", ":", "msg", "=", "\"Unsupported logging format style! (%r)\"", "rai...
Validate a logging format style. :param value: The logging format style to validate (any value). :returns: The logging format character (a string of one character). :raises: :exc:`~exceptions.ValueError` when the given style isn't supported. On Python 3.2+ this function accepts the logging format styles ``%``, ``{`` and ``$`` while on older versions only ``%`` is accepted (because older Python versions don't support alternative logging format styles).
[ "Validate", "a", "logging", "format", "style", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L530-L549
train
210,290
xolox/python-coloredlogs
coloredlogs/__init__.py
increase_verbosity
def increase_verbosity(): """ Increase the verbosity of the root handler by one defined level. Understands custom logging levels like defined by my ``verboselogs`` module. """ defined_levels = sorted(set(find_defined_levels().values())) current_index = defined_levels.index(get_level()) selected_index = max(0, current_index - 1) set_level(defined_levels[selected_index])
python
def increase_verbosity(): """ Increase the verbosity of the root handler by one defined level. Understands custom logging levels like defined by my ``verboselogs`` module. """ defined_levels = sorted(set(find_defined_levels().values())) current_index = defined_levels.index(get_level()) selected_index = max(0, current_index - 1) set_level(defined_levels[selected_index])
[ "def", "increase_verbosity", "(", ")", ":", "defined_levels", "=", "sorted", "(", "set", "(", "find_defined_levels", "(", ")", ".", "values", "(", ")", ")", ")", "current_index", "=", "defined_levels", ".", "index", "(", "get_level", "(", ")", ")", "select...
Increase the verbosity of the root handler by one defined level. Understands custom logging levels like defined by my ``verboselogs`` module.
[ "Increase", "the", "verbosity", "of", "the", "root", "handler", "by", "one", "defined", "level", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L552-L562
train
210,291
xolox/python-coloredlogs
coloredlogs/__init__.py
decrease_verbosity
def decrease_verbosity(): """ Decrease the verbosity of the root handler by one defined level. Understands custom logging levels like defined by my ``verboselogs`` module. """ defined_levels = sorted(set(find_defined_levels().values())) current_index = defined_levels.index(get_level()) selected_index = min(current_index + 1, len(defined_levels) - 1) set_level(defined_levels[selected_index])
python
def decrease_verbosity(): """ Decrease the verbosity of the root handler by one defined level. Understands custom logging levels like defined by my ``verboselogs`` module. """ defined_levels = sorted(set(find_defined_levels().values())) current_index = defined_levels.index(get_level()) selected_index = min(current_index + 1, len(defined_levels) - 1) set_level(defined_levels[selected_index])
[ "def", "decrease_verbosity", "(", ")", ":", "defined_levels", "=", "sorted", "(", "set", "(", "find_defined_levels", "(", ")", ".", "values", "(", ")", ")", ")", "current_index", "=", "defined_levels", ".", "index", "(", "get_level", "(", ")", ")", "select...
Decrease the verbosity of the root handler by one defined level. Understands custom logging levels like defined by my ``verboselogs`` module.
[ "Decrease", "the", "verbosity", "of", "the", "root", "handler", "by", "one", "defined", "level", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L565-L575
train
210,292
xolox/python-coloredlogs
coloredlogs/__init__.py
get_level
def get_level(): """ Get the logging level of the root handler. :returns: The logging level of the root handler (an integer) or :data:`DEFAULT_LOG_LEVEL` (if no root handler exists). """ handler, logger = find_handler(logging.getLogger(), match_stream_handler) return handler.level if handler else DEFAULT_LOG_LEVEL
python
def get_level(): """ Get the logging level of the root handler. :returns: The logging level of the root handler (an integer) or :data:`DEFAULT_LOG_LEVEL` (if no root handler exists). """ handler, logger = find_handler(logging.getLogger(), match_stream_handler) return handler.level if handler else DEFAULT_LOG_LEVEL
[ "def", "get_level", "(", ")", ":", "handler", ",", "logger", "=", "find_handler", "(", "logging", ".", "getLogger", "(", ")", ",", "match_stream_handler", ")", "return", "handler", ".", "level", "if", "handler", "else", "DEFAULT_LOG_LEVEL" ]
Get the logging level of the root handler. :returns: The logging level of the root handler (an integer) or :data:`DEFAULT_LOG_LEVEL` (if no root handler exists).
[ "Get", "the", "logging", "level", "of", "the", "root", "handler", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L587-L595
train
210,293
xolox/python-coloredlogs
coloredlogs/__init__.py
set_level
def set_level(level): """ Set the logging level of the root handler. :param level: The logging level to filter on (an integer or string). If no root handler exists yet this automatically calls :func:`install()`. """ handler, logger = find_handler(logging.getLogger(), match_stream_handler) if handler and logger: # Change the level of the existing handler. handler.setLevel(level_to_number(level)) # Adjust the level of the selected logger. adjust_level(logger, level) else: # Create a new handler with the given level. install(level=level)
python
def set_level(level): """ Set the logging level of the root handler. :param level: The logging level to filter on (an integer or string). If no root handler exists yet this automatically calls :func:`install()`. """ handler, logger = find_handler(logging.getLogger(), match_stream_handler) if handler and logger: # Change the level of the existing handler. handler.setLevel(level_to_number(level)) # Adjust the level of the selected logger. adjust_level(logger, level) else: # Create a new handler with the given level. install(level=level)
[ "def", "set_level", "(", "level", ")", ":", "handler", ",", "logger", "=", "find_handler", "(", "logging", ".", "getLogger", "(", ")", ",", "match_stream_handler", ")", "if", "handler", "and", "logger", ":", "# Change the level of the existing handler.", "handler"...
Set the logging level of the root handler. :param level: The logging level to filter on (an integer or string). If no root handler exists yet this automatically calls :func:`install()`.
[ "Set", "the", "logging", "level", "of", "the", "root", "handler", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L598-L614
train
210,294
xolox/python-coloredlogs
coloredlogs/__init__.py
adjust_level
def adjust_level(logger, level): """ Increase a logger's verbosity up to the requested level. :param logger: The logger to change (a :class:`~logging.Logger` object). :param level: The log level to enable (a string or number). This function is used by functions like :func:`install()`, :func:`increase_verbosity()` and :func:`.enable_system_logging()` to adjust a logger's level so that log messages up to the requested log level are propagated to the configured output handler(s). It uses :func:`logging.Logger.getEffectiveLevel()` to check whether `logger` propagates or swallows log messages of the requested `level` and sets the logger's level to the requested level if it would otherwise swallow log messages. Effectively this function will "widen the scope of logging" when asked to do so but it will never "narrow the scope of logging". This is because I am convinced that filtering of log messages should (primarily) be decided by handlers. """ level = level_to_number(level) if logger.getEffectiveLevel() > level: logger.setLevel(level)
python
def adjust_level(logger, level): """ Increase a logger's verbosity up to the requested level. :param logger: The logger to change (a :class:`~logging.Logger` object). :param level: The log level to enable (a string or number). This function is used by functions like :func:`install()`, :func:`increase_verbosity()` and :func:`.enable_system_logging()` to adjust a logger's level so that log messages up to the requested log level are propagated to the configured output handler(s). It uses :func:`logging.Logger.getEffectiveLevel()` to check whether `logger` propagates or swallows log messages of the requested `level` and sets the logger's level to the requested level if it would otherwise swallow log messages. Effectively this function will "widen the scope of logging" when asked to do so but it will never "narrow the scope of logging". This is because I am convinced that filtering of log messages should (primarily) be decided by handlers. """ level = level_to_number(level) if logger.getEffectiveLevel() > level: logger.setLevel(level)
[ "def", "adjust_level", "(", "logger", ",", "level", ")", ":", "level", "=", "level_to_number", "(", "level", ")", "if", "logger", ".", "getEffectiveLevel", "(", ")", ">", "level", ":", "logger", ".", "setLevel", "(", "level", ")" ]
Increase a logger's verbosity up to the requested level. :param logger: The logger to change (a :class:`~logging.Logger` object). :param level: The log level to enable (a string or number). This function is used by functions like :func:`install()`, :func:`increase_verbosity()` and :func:`.enable_system_logging()` to adjust a logger's level so that log messages up to the requested log level are propagated to the configured output handler(s). It uses :func:`logging.Logger.getEffectiveLevel()` to check whether `logger` propagates or swallows log messages of the requested `level` and sets the logger's level to the requested level if it would otherwise swallow log messages. Effectively this function will "widen the scope of logging" when asked to do so but it will never "narrow the scope of logging". This is because I am convinced that filtering of log messages should (primarily) be decided by handlers.
[ "Increase", "a", "logger", "s", "verbosity", "up", "to", "the", "requested", "level", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L617-L641
train
210,295
xolox/python-coloredlogs
coloredlogs/__init__.py
find_defined_levels
def find_defined_levels(): """ Find the defined logging levels. :returns: A dictionary with level names as keys and integers as values. Here's what the result looks like by default (when no custom levels or level names have been defined): >>> find_defined_levels() {'NOTSET': 0, 'DEBUG': 10, 'INFO': 20, 'WARN': 30, 'WARNING': 30, 'ERROR': 40, 'FATAL': 50, 'CRITICAL': 50} """ defined_levels = {} for name in dir(logging): if name.isupper(): value = getattr(logging, name) if isinstance(value, int): defined_levels[name] = value return defined_levels
python
def find_defined_levels(): """ Find the defined logging levels. :returns: A dictionary with level names as keys and integers as values. Here's what the result looks like by default (when no custom levels or level names have been defined): >>> find_defined_levels() {'NOTSET': 0, 'DEBUG': 10, 'INFO': 20, 'WARN': 30, 'WARNING': 30, 'ERROR': 40, 'FATAL': 50, 'CRITICAL': 50} """ defined_levels = {} for name in dir(logging): if name.isupper(): value = getattr(logging, name) if isinstance(value, int): defined_levels[name] = value return defined_levels
[ "def", "find_defined_levels", "(", ")", ":", "defined_levels", "=", "{", "}", "for", "name", "in", "dir", "(", "logging", ")", ":", "if", "name", ".", "isupper", "(", ")", ":", "value", "=", "getattr", "(", "logging", ",", "name", ")", "if", "isinsta...
Find the defined logging levels. :returns: A dictionary with level names as keys and integers as values. Here's what the result looks like by default (when no custom levels or level names have been defined): >>> find_defined_levels() {'NOTSET': 0, 'DEBUG': 10, 'INFO': 20, 'WARN': 30, 'WARNING': 30, 'ERROR': 40, 'FATAL': 50, 'CRITICAL': 50}
[ "Find", "the", "defined", "logging", "levels", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L644-L669
train
210,296
xolox/python-coloredlogs
coloredlogs/__init__.py
level_to_number
def level_to_number(value): """ Coerce a logging level name to a number. :param value: A logging level (integer or string). :returns: The number of the log level (an integer). This function translates log level names into their numeric values. The :mod:`logging` module does this for us on Python 2.7 and 3.4 but fails to do so on Python 2.6 which :mod:`coloredlogs` still supports. """ if is_string(value): try: defined_levels = find_defined_levels() value = defined_levels[value.upper()] except KeyError: # Don't fail on unsupported log levels. value = DEFAULT_LOG_LEVEL return value
python
def level_to_number(value): """ Coerce a logging level name to a number. :param value: A logging level (integer or string). :returns: The number of the log level (an integer). This function translates log level names into their numeric values. The :mod:`logging` module does this for us on Python 2.7 and 3.4 but fails to do so on Python 2.6 which :mod:`coloredlogs` still supports. """ if is_string(value): try: defined_levels = find_defined_levels() value = defined_levels[value.upper()] except KeyError: # Don't fail on unsupported log levels. value = DEFAULT_LOG_LEVEL return value
[ "def", "level_to_number", "(", "value", ")", ":", "if", "is_string", "(", "value", ")", ":", "try", ":", "defined_levels", "=", "find_defined_levels", "(", ")", "value", "=", "defined_levels", "[", "value", ".", "upper", "(", ")", "]", "except", "KeyError"...
Coerce a logging level name to a number. :param value: A logging level (integer or string). :returns: The number of the log level (an integer). This function translates log level names into their numeric values. The :mod:`logging` module does this for us on Python 2.7 and 3.4 but fails to do so on Python 2.6 which :mod:`coloredlogs` still supports.
[ "Coerce", "a", "logging", "level", "name", "to", "a", "number", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L672-L690
train
210,297
xolox/python-coloredlogs
coloredlogs/__init__.py
find_level_aliases
def find_level_aliases(): """ Find log level names which are aliases of each other. :returns: A dictionary that maps aliases to their canonical name. .. note:: Canonical names are chosen to be the alias with the longest string length so that e.g. ``WARN`` is an alias for ``WARNING`` instead of the other way around. Here's what the result looks like by default (when no custom levels or level names have been defined): >>> from coloredlogs import find_level_aliases >>> find_level_aliases() {'WARN': 'WARNING', 'FATAL': 'CRITICAL'} """ mapping = collections.defaultdict(list) for name, value in find_defined_levels().items(): mapping[value].append(name) aliases = {} for value, names in mapping.items(): if len(names) > 1: names = sorted(names, key=lambda n: len(n)) canonical_name = names.pop() for alias in names: aliases[alias] = canonical_name return aliases
python
def find_level_aliases(): """ Find log level names which are aliases of each other. :returns: A dictionary that maps aliases to their canonical name. .. note:: Canonical names are chosen to be the alias with the longest string length so that e.g. ``WARN`` is an alias for ``WARNING`` instead of the other way around. Here's what the result looks like by default (when no custom levels or level names have been defined): >>> from coloredlogs import find_level_aliases >>> find_level_aliases() {'WARN': 'WARNING', 'FATAL': 'CRITICAL'} """ mapping = collections.defaultdict(list) for name, value in find_defined_levels().items(): mapping[value].append(name) aliases = {} for value, names in mapping.items(): if len(names) > 1: names = sorted(names, key=lambda n: len(n)) canonical_name = names.pop() for alias in names: aliases[alias] = canonical_name return aliases
[ "def", "find_level_aliases", "(", ")", ":", "mapping", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "name", ",", "value", "in", "find_defined_levels", "(", ")", ".", "items", "(", ")", ":", "mapping", "[", "value", "]", ".", "append",...
Find log level names which are aliases of each other. :returns: A dictionary that maps aliases to their canonical name. .. note:: Canonical names are chosen to be the alias with the longest string length so that e.g. ``WARN`` is an alias for ``WARNING`` instead of the other way around. Here's what the result looks like by default (when no custom levels or level names have been defined): >>> from coloredlogs import find_level_aliases >>> find_level_aliases() {'WARN': 'WARNING', 'FATAL': 'CRITICAL'}
[ "Find", "log", "level", "names", "which", "are", "aliases", "of", "each", "other", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L693-L720
train
210,298
xolox/python-coloredlogs
coloredlogs/__init__.py
parse_encoded_styles
def parse_encoded_styles(text, normalize_key=None): """ Parse text styles encoded in a string into a nested data structure. :param text: The encoded styles (a string). :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES` and :data:`DEFAULT_LEVEL_STYLES` dictionaries. Here's an example of how this function works: >>> from coloredlogs import parse_encoded_styles >>> from pprint import pprint >>> encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold' >>> pprint(parse_encoded_styles(encoded_styles)) {'debug': {'color': 'green'}, 'warning': {'color': 'yellow'}, 'error': {'color': 'red'}, 'critical': {'bold': True, 'color': 'red'}} """ parsed_styles = {} for assignment in split(text, ';'): name, _, styles = assignment.partition('=') target = parsed_styles.setdefault(name, {}) for token in split(styles, ','): # When this code was originally written, setting background colors # wasn't supported yet, so there was no need to disambiguate # between the text color and background color. This explains why # a color name or number implies setting the text color (for # backwards compatibility). if token.isdigit(): target['color'] = int(token) elif token in ANSI_COLOR_CODES: target['color'] = token elif '=' in token: name, _, value = token.partition('=') if name in ('color', 'background'): if value.isdigit(): target[name] = int(value) elif value in ANSI_COLOR_CODES: target[name] = value else: target[token] = True return parsed_styles
python
def parse_encoded_styles(text, normalize_key=None): """ Parse text styles encoded in a string into a nested data structure. :param text: The encoded styles (a string). :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES` and :data:`DEFAULT_LEVEL_STYLES` dictionaries. Here's an example of how this function works: >>> from coloredlogs import parse_encoded_styles >>> from pprint import pprint >>> encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold' >>> pprint(parse_encoded_styles(encoded_styles)) {'debug': {'color': 'green'}, 'warning': {'color': 'yellow'}, 'error': {'color': 'red'}, 'critical': {'bold': True, 'color': 'red'}} """ parsed_styles = {} for assignment in split(text, ';'): name, _, styles = assignment.partition('=') target = parsed_styles.setdefault(name, {}) for token in split(styles, ','): # When this code was originally written, setting background colors # wasn't supported yet, so there was no need to disambiguate # between the text color and background color. This explains why # a color name or number implies setting the text color (for # backwards compatibility). if token.isdigit(): target['color'] = int(token) elif token in ANSI_COLOR_CODES: target['color'] = token elif '=' in token: name, _, value = token.partition('=') if name in ('color', 'background'): if value.isdigit(): target[name] = int(value) elif value in ANSI_COLOR_CODES: target[name] = value else: target[token] = True return parsed_styles
[ "def", "parse_encoded_styles", "(", "text", ",", "normalize_key", "=", "None", ")", ":", "parsed_styles", "=", "{", "}", "for", "assignment", "in", "split", "(", "text", ",", "';'", ")", ":", "name", ",", "_", ",", "styles", "=", "assignment", ".", "pa...
Parse text styles encoded in a string into a nested data structure. :param text: The encoded styles (a string). :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES` and :data:`DEFAULT_LEVEL_STYLES` dictionaries. Here's an example of how this function works: >>> from coloredlogs import parse_encoded_styles >>> from pprint import pprint >>> encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold' >>> pprint(parse_encoded_styles(encoded_styles)) {'debug': {'color': 'green'}, 'warning': {'color': 'yellow'}, 'error': {'color': 'red'}, 'critical': {'bold': True, 'color': 'red'}}
[ "Parse", "text", "styles", "encoded", "in", "a", "string", "into", "a", "nested", "data", "structure", "." ]
1cbf0c6bbee400c6ddbc43008143809934ec3e79
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L723-L765
train
210,299