text stringlengths 81 112k |
|---|
Empirical generalized multi-part Guinier-Porod scattering
Inputs:
-------
``q``: independent variable
``factor``: factor for the first branch
other arguments (*args): the defining arguments of the consecutive
parts: radius of gyration (``Rg``) and dimensionality
... |
Scattering form-factor intensity of a Gaussian chain (Debye)
Inputs:
-------
``q``: independent variable
``Rg``: radius of gyration
Formula:
--------
``2*(exp(-a)-1+a)/a^2`` where ``a=(q*Rg)^2``
def DebyeChain(q, Rg):
"""Scattering form-factor intensity of a Gaussian chain... |
Scattering intensity of a generalized excluded-volume Gaussian chain
Inputs:
-------
``q``: independent variable
``Rg``: radius of gyration
``nu``: excluded volume exponent
Formula:
--------
``(u^(1/nu)*gamma(0.5/nu)*gammainc_lower(0.5/nu,u)-
gamma(1/nu)*gam... |
Borue-Erukhimovich model of microphase separation in polyelectrolytes
Inputs:
-------
``q``: independent variable
``C``: scaling factor
``r0``: typical el.stat. screening length
``s``: dimensionless charge concentration
``t``: dimensionless temperature
Formula:
... |
Borue-Erukhimovich model ending in a power-law.
Inputs:
-------
``q``: independent variable
``C``: scaling factor
``r0``: typical el.stat. screening length
``s``: dimensionless charge concentration
``t``: dimensionless temperature
``nu``: excluded volume paramete... |
Sample a patch from the data object
Parameters
----------
data : dict
A data dict as produced by pumpp.Pump.transform
interval : slice
The time interval to sample
Returns
-------
data_slice : dict
`data` restricted to `interv... |
Generate patch indices
Parameters
----------
data : dict of np.ndarray
As produced by pumpp.transform
Yields
------
start : int >= 0
The start index of a sample patch
def indices(self, data):
'''Generate patch indices
Parameters... |
Generate patch start indices
Parameters
----------
data : dict of np.ndarray
As produced by pumpp.transform
Yields
------
start : int >= 0
The start index of a sample patch
def indices(self, data):
'''Generate patch start indices
... |
Generate patch indices
Parameters
----------
data : dict of np.ndarray
As produced by pumpp.transform
Yields
------
start : int >= 0
The start index of a sample patch
def indices(self, data):
'''Generate patch indices
Parameters... |
Apply the name scope to a key
Parameters
----------
key : string
Returns
-------
`name/key` if `name` is not `None`;
otherwise, `key`.
def scope(self, key):
'''Apply the name scope to a key
Parameters
----------
key : string
... |
Register a field as a tensor with specified shape and type.
A `Tensor` of the given shape and type will be registered in this
object's `fields` dict.
Parameters
----------
field : str
The name of the field
shape : iterable of `int` or `None`
The... |
Merge an array of output dictionaries into a single dictionary
with properly scoped names.
Parameters
----------
data : list of dict
Output dicts as produced by `pumpp.task.BaseTaskTransformer.transform`
or `pumpp.feature.FeatureExtractor.transform`.
Ret... |
Add an operator to the Slicer
Parameters
----------
operator : Scope (TaskTransformer or FeatureExtractor)
The new operator to add
def add(self, operator):
'''Add an operator to the Slicer
Parameters
----------
operator : Scope (TaskTransformer or F... |
Compute the valid data duration of a dict
Parameters
----------
data : dict
As produced by pumpp.transform
Returns
-------
length : int
The minimum temporal extent of a dynamic observation in data
def data_duration(self, data):
'''Comput... |
Crop a data dictionary down to its common time
Parameters
----------
data : dict
As produced by pumpp.transform
Returns
-------
data_cropped : dict
Like `data` but with all time-like axes truncated to the
minimum common duration
def ... |
Compute the Mel spectrogram
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_mels)
The Mel spectrogram
def transform_audio(self, y):
'''Compute... |
Empty vector annotations.
This returns an annotation with a single observation
vector consisting of all-zeroes.
Parameters
----------
duration : number >0
Length of the track
Returns
-------
ann : jams.Annotation
The empty annota... |
Apply the vector transformation.
Parameters
----------
ann : jams.Annotation
The input annotation
duration : number > 0
The duration of the track
Returns
-------
data : dict
data['vector'] : np.ndarray, shape=(dimension,)
... |
Inverse vector transformer
def inverse(self, vector, duration=None):
'''Inverse vector transformer'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
if duration is None:
duration = 0
ann.append(time=0, duration=duration, value=vector)
return an... |
Set the transition matrix according to self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(n_labels,)]
Optional self-loop probability(ies), used for Viterbi decoding
def set_transition(self, p_self):
'''Set the transition mat... |
Empty label annotations.
Constructs a single observation with an empty value (None).
Parameters
----------
duration : number > 0
The duration of the annotation
def empty(self, duration):
'''Empty label annotations.
Constructs a single observation with an e... |
Transform an annotation to dynamic label encoding.
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
data : dict
data['tags'] : np.ndarray, s... |
Inverse transformation
def inverse(self, encoded, duration=None):
'''Inverse transformation'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
for start, end, value in self.decode_intervals(encoded,
duration=duration,
... |
Transform an annotation to static label encoding.
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
data : dict
data['tags'] : np.ndarray, sh... |
Inverse static tag transformation
def inverse(self, encoded, duration=None):
'''Inverse static tag transformation'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
if np.isrealobj(encoded):
detected = (encoded >= 0.5)
else:
detected = encode... |
Compute the time position encoding
Parameters
----------
y : np.ndarray
Audio buffer
Returns
-------
data : dict
data['relative'] = np.ndarray, shape=(n_frames, 2)
data['absolute'] = np.ndarray, shape=(n_frames, 2)
Re... |
Add an operation to this pump.
Parameters
----------
operator : BaseTaskTransformer, FeatureExtractor
The operation to add
Raises
------
ParameterError
if `op` is not of a correct type
def add(self, operator):
'''Add an operation to this... |
Apply the transformations to an audio file, and optionally JAMS object.
Parameters
----------
audio_f : str
Path to audio file
jam : optional, `jams.JAMS`, str or file-like
Optional JAMS object/path to JAMS file/open file descriptor.
If provided, th... |
Construct a sampler object for this pump's operators.
Parameters
----------
n_samples : None or int > 0
The number of samples to generate
duration : int > 0
The duration (in frames) of each sample patch
random_state : None, int, or np.random.RandomState... |
A dictionary of fields constructed by this pump
def fields(self):
'''A dictionary of fields constructed by this pump'''
out = dict()
for operator in self.ops:
out.update(**operator.fields)
return out |
Construct Keras input layers for all feature transformers
in the pump.
Returns
-------
layers : {field: keras.layers.Input}
A dictionary of keras input layers, keyed by the corresponding
fields.
def layers(self):
'''Construct Keras input layers for all f... |
Set the beat-tracking transition matrix according to
self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(2,)]
Optional self-loop probability(ies), used for Viterbi decoding
def set_transition_beat(self, p_self):
'''Se... |
Set the downbeat-tracking transition matrix according to
self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(2,)]
Optional self-loop probability(ies), used for Viterbi decoding
def set_transition_down(self, p_self):
'... |
Apply the beat transformer
Parameters
----------
ann : jams.Annotation
The input annotation
duration : number > 0
The duration of the audio
Returns
-------
data : dict
data['beat'] : np.ndarray, shape=(n, 1)
B... |
Inverse transformation for beats and optional downbeats
def inverse(self, encoded, downbeat=None, duration=None):
'''Inverse transformation for beats and optional downbeats'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
beat_times = np.asarray([t for t, _ in self.decode... |
Transform an annotation to the beat-position encoding
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
data : dict
data['position'] : np.nda... |
Compute the tempogram
Parameters
----------
y : np.ndarray
Audio buffer
Returns
-------
data : dict
data['tempogram'] : np.ndarray, shape=(n_frames, win_length)
The tempogram
def transform_audio(self, y):
'''Compute the t... |
Apply the scale transform to the tempogram
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['temposcale'] : np.ndarray, shape=(n_frames, n_fmt)
The scale transform magnitude coefficients
def ... |
Apply the structure agreement transformation.
Parameters
----------
ann : jams.Annotation
The segment annotation
duration : number > 0
The target duration
Returns
-------
data : dict
data['agree'] : np.ndarray, shape=(n, n), ... |
Compute the STFT magnitude and phase.
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, 1 + n_fft//2)
STFT magnitude
data['phase'] : np.ndarra... |
Compute the STFT with phase differentials.
Parameters
----------
y : np.ndarray
the audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, 1 + n_fft//2)
The STFT magnitude
data['dphase'] :... |
Compute the STFT
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, 1 + n_fft//2)
The STFT magnitude
def transform_audio(self, y):
'''Compute the S... |
Pad a chord annotation with no-chord flags.
Parameters
----------
target : np.ndarray
the input data
axis : int
the axis along which to pad
Returns
-------
target_pad
`target` expanded by 1 along the specified `axis`.
The expanded dimension will be 0 when `... |
Empty chord annotations
Parameters
----------
duration : number
The length (in seconds) of the empty annotation
Returns
-------
ann : jams.Annotation
A chord annotation consisting of a single `no-chord` observation.
def empty(self, duration):
... |
Apply the chord transformation.
Parameters
----------
ann : jams.Annotation
The chord annotation
duration : number > 0
The target duration
Returns
-------
data : dict
data['pitch'] : np.ndarray, shape=(n, 12)
data... |
Apply the chord transformation.
Parameters
----------
ann : jams.Annotation
The chord annotation
duration : number > 0
The target duration
Returns
-------
data : dict
data['pitch'] : np.ndarray, shape=(n, 12)
`pi... |
Set the transition matrix according to self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(n_labels,)]
Optional self-loop probability(ies), used for Viterbi decoding
def set_transition(self, p_self):
'''Set the transition mat... |
Simplify a chord string down to the vocabulary space
def simplify(self, chord):
'''Simplify a chord string down to the vocabulary space'''
# Drop inversions
chord = re.sub(r'/.*$', r'', chord)
# Drop any additional or suppressed tones
chord = re.sub(r'\(.*?\)', r'', chord)
... |
Transform an annotation to chord-tag encoding
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
data : dict
data['chord'] : np.ndarray, shape... |
Compute the CQT
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape = (n_frames, n_bins)
The CQT magnitude
data['phase']: np.ndarray, shape = mag.shape
... |
Compute CQT magnitude.
Parameters
----------
y : np.ndarray
the audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_bins)
The CQT magnitude
def transform_audio(self, y):
'''Compute CQT ma... |
Compute the CQT with unwrapped phase
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_bins)
CQT magnitude
data['dphase'] : np.ndarray, shap... |
Compute the HCQT
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape = (n_frames, n_bins, n_harmonics)
The CQT magnitude
data['phase']: np.ndarray, shape =... |
Rearrange a tensor according to the convolution mode
Input is assumed to be in (channels, bins, time) format.
def _index(self, value):
'''Rearrange a tensor according to the convolution mode
Input is assumed to be in (channels, bins, time) format.
'''
if self.conv in ('channe... |
Compute HCQT magnitude.
Parameters
----------
y : np.ndarray
the audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_bins)
The CQT magnitude
def transform_audio(self, y):
'''Compute HCQT ... |
Compute the HCQT with unwrapped phase
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_bins)
CQT magnitude
data['dphase'] : np.ndarray, sha... |
Get a fill-value for a given dtype
Parameters
----------
dtype : type
Returns
-------
`np.nan` if `dtype` is real or complex
0 otherwise
def fill_value(dtype):
'''Get a fill-value for a given dtype
Parameters
----------
dtype : type
Returns
-------
`np.nan` ... |
Create an empty jams.Annotation for this task.
This method should be overridden by derived classes.
Parameters
----------
duration : int >= 0
Duration of the annotation
def empty(self, duration):
'''Create an empty jams.Annotation for this task.
This metho... |
Transform jam object to make data for this task
Parameters
----------
jam : jams.JAMS
The jams container object
query : string, dict, or callable [optional]
An optional query to narrow the elements of `jam.annotations`
to be considered.
... |
Encode labeled events as a time-series matrix.
Parameters
----------
duration : number
The duration of the track
events : ndarray, shape=(n,)
Time index of the events
values : ndarray, shape=(n, m)
Values array. Must have the same first ind... |
Encode labeled intervals as a time-series matrix.
Parameters
----------
duration : number
The duration (in frames) of the track
intervals : np.ndarray, shape=(n, 2)
The list of intervals
values : np.ndarray, shape=(n, m)
The (encoded) values... |
Decode labeled events into (time, value) pairs
Real-valued inputs are thresholded at 0.5.
Optionally, viterbi decoding can be applied to each event class.
Parameters
----------
encoded : np.ndarray, shape=(n_frames, m)
Frame-level annotation encodings as produced b... |
Decode labeled intervals into (start, end, value) triples
Parameters
----------
encoded : np.ndarray, shape=(n_frames, m)
Frame-level annotation encodings as produced by
``encode_intervals``
duration : None or float > 0
The max duration of the annota... |
Transform an audio signal
Parameters
----------
y : np.ndarray
The audio signal
sr : number > 0
The native sampling rate of y
Returns
-------
dict
Data dictionary containing features extracted from y
See Also
... |
Compute the phase differential along a given axis
Parameters
----------
phase : np.ndarray
Input phase (in radians)
Returns
-------
dphase : np.ndarray like `phase`
The phase differential.
def phase_diff(self, phase):
'''Compute the phas... |
Construct Keras input layers for the given transformer
Returns
-------
layers : {field: keras.layers.Input}
A dictionary of keras input layers, keyed by the corresponding
field keys.
def layers(self):
'''Construct Keras input layers for the given transformer
... |
Get the number of frames for a given duration
Parameters
----------
duration : number >= 0
The duration, in seconds
Returns
-------
n_frames : int >= 0
The number of frames at this extractor's sampling rate and
hop length
def n_frame... |
Create a new release branch.
Args:
component (str):
Version component to bump when creating the release. Can be *major*,
*minor* or *patch*.
exact (str):
The exact version to set for the release. Overrides the component
argument. This allows to re-rel... |
Tag the current commit with the current version.
def tag(message):
# type: () -> None
""" Tag the current commit with the current version. """
release_ver = versioning.current()
message = message or 'v{} release'.format(release_ver)
with conf.within_proj_dir():
log.info("Creating release t... |
Lint python files.
Args:
exclude (list[str]):
A list of glob string patterns to test against. If the file/path
matches any of those patters, it will be filtered out.
skip_untracked (bool):
If set to **True** it will skip all files not tracked by git.
comm... |
Decorator for defining lint tools.
Args:
name (str):
The name of the tool. This name will be used to identify the tool
in `pelconf.yaml`.
def tool(name):
# type: (str) -> FunctionType
""" Decorator for defining lint tools.
Args:
name (str):
The name... |
Run code checks using pep8.
Args:
files (list[str]):
A list of files to check
Returns:
bool: **True** if all files passed the checks, **False** otherwise.
pep8 tool is **very** fast. Especially compared to pylint and the bigger the
code base the bigger the difference. If y... |
Run code checks using pylint.
Args:
files (list[str]):
A list of files to check
Returns:
bool: **True** if all files passed the checks, **False** otherwise.
def pylint_check(files):
# type: (List[str]) -> int
""" Run code checks using pylint.
Args:
files (list... |
Run all linters and report results.
Returns:
bool: **True** if all checks were successful, **False** otherwise.
def run(self):
# type: () -> bool
""" Run all linters and report results.
Returns:
bool: **True** if all checks were successful, **False** otherwise.... |
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...]
}
def send_to_azure(instance, data,... |
Returns a standard python Dict with computed values
from the DynDict
:param source: (DynDict) input
:return: (dict) Containing computed values
def getdict(source):
"""Returns a standard python Dict with computed values
from the DynDict
:param source: (DynDict) input
:return: (dict) Containi... |
Add a new property to the app (with setattr)
Args:
name (str): the name of the new property
value (any): the value of the new property
def enrich_app(self, name, value):
'''
Add a new property to the app (with setattr)
Args:
name (str): the name of ... |
Least squares linear fit.
Fit a straight line `f(x_true) = a + bx` to points `(x_true, y)`. Returns
coefficients `a` and `b` that minimize the squared error.
Parameters
----------
x_true : array_like
one dimensional array of `x_true` data with `n`>2 data points.
y : array_li... |
Set Isogeo base URLs according to platform.
:param str platform: platform to use. Options:
* prod [DEFAULT]
* qa
* int
def set_base_url(self, platform: str = "prod"):
"""Set Isogeo base URLs according to platform.
:param str platform: platform to use. Options:
... |
Convert a metadata UUID to its URI equivalent. And conversely.
:param str in_uuid: UUID or URI to convert
:param int mode: conversion direction. Options:
* 0 to HEX
* 1 to URN (RFC4122)
* 2 to URN (Isogeo specific style)
def convert_uuid(self, in_uuid: str = str, mode: b... |
Pull out the character set, encoding, and encoded text from the input
encoded words. Next, it decodes the encoded words into a byte string,
using either the quopri module or base64 module as determined by the
encoding. Finally, it decodes the byte string using the
character set and retur... |
Get Isogeo components versions. Authentication not required.
:param str component: which platform component. Options:
* api [default]
* db
* app
def get_isogeo_version(self, component: str = "api", prot: str = "https"):
"""Get Isogeo components versions. Authentication n... |
Constructs the edition URL of a metadata.
:param str md_id: metadata/resource UUID
:param str owner_id: owner UUID
:param str tab: target tab in the web form
def get_edit_url(
self,
md_id: str = None,
md_type: str = None,
owner_id: str = None,
tab: str =... |
Constructs the view URL of a metadata.
:param str webapp: web app destination
:param dict kwargs: web app specific parameters. For example see WEBAPPS
def get_view_url(self, webapp: str = "oc", **kwargs):
"""Constructs the view URL of a metadata.
:param str webapp: web app destination... |
Register a new WEBAPP to use with the view URL builder.
:param str webapp_name: name of the web app to register
:param list webapp_args: dynamic arguments to complete the URL.
Typically 'md_id'.
:param str webapp_url: URL of the web app to register with
args tags to replace. E... |
Returns the Isogeo API root URL (which is not included into
credentials file) from the token URL (which is always included).
:param url_api_token str: url to Isogeo API ID token generator
def get_url_base_from_url_token(
self, url_api_token: str = "https://id.api.isogeo.com/oauth/token"
):... |
Simple helper to handle pagination. Returns the number of pages for a
given number of results.
:param int total: count of metadata in a search request
:param int page_size: count of metadata to display in each page
def pages_counter(self, total: int, page_size: int = 100) -> int:
"""Si... |
Reverse search tags dictionary to values as keys.
Useful to populate filters comboboxes for example.
:param dict tags: tags dictionary from a search request
:param dict prev_query: query parameters returned after a search request. Typically `search.get("query")`.
:param str duplicated: ... |
Extend share model with additional informations.
:param dict share: share returned by API
:param dict results_filtered: filtered search result
def share_extender(self, share: dict, results_filtered: dict):
"""Extend share model with additional informations.
:param dict share: share re... |
Loads API credentials from a file, JSON or INI.
:param str in_credentials: path to the credentials file. By default,
look for a client_secrets.json file.
def credentials_loader(self, in_credentials: str = "client_secrets.json") -> dict:
"""Loads API credentials from a file, JSON or INI.
... |
Generate .pypirc config with the given credentials.
Example:
$ peltak pypi configure my_pypi_user my_pypi_pass
def configure(username, password):
# type: (str, str) -> None
"""
Generate .pypirc config with the given credentials.
Example:
$ peltak pypi configure my_pypi_user my_p... |
Returns translation of string passed.
:param str subdomain: subpart of strings dictionary.
Must be one of self.translations.keys() i.e. 'restrictions'
:param str string_to_translate: string you want to translate
def tr(self, subdomain: str, string_to_translate: str = "") -> str:
"""Re... |
This is a duplicte of the view code for DRF to stop future
internal Django implementations breaking.
def optout_saved(sender, instance, **kwargs):
"""
This is a duplicte of the view code for DRF to stop future
internal Django implementations breaking.
"""
if instance.identity is None:
#... |
Gets an EC2 client
:return: boto3.client object
:raises: AWSAPIError
def get_ec2_client(region_name=None, aws_access_key_id=None, aws_secret_access_key=None):
"""Gets an EC2 client
:return: boto3.client object
:raises: AWSAPIError
"""
log = logging.getLogger(mod_logger + '.get_ec2_client'... |
Gets the VPC ID for this EC2 instance
:return: String instance ID or None
def get_vpc_id(self):
"""Gets the VPC ID for this EC2 instance
:return: String instance ID or None
"""
log = logging.getLogger(self.cls_logger + '.get_vpc_id')
# Exit if not running on AWS
... |
Given an interface number, gets the AWS elastic network
interface associated with the interface.
:param interface: Integer associated to the interface/device number
:return: String Elastic Network Interface ID or None if not found
:raises OSError, AWSAPIError, EC2UtilError
def get_eni_... |
Adds an IP address as a secondary IP address
:param ip_address: String IP address to add as a secondary IP
:param interface: Integer associated to the interface/device number
:return: None
:raises: AWSAPIError, EC2UtilError
def add_secondary_ip(self, ip_address, interface=1):
"... |
Given an elastic IP address and an interface number, associates the
elastic IP to the interface number on this host.
:param allocation_id: String ID for the elastic IP
:param interface: Integer associated to the interface/device number
:param private_ip: String IP address of the private... |
Allocates an elastic IP address
:return: Dict with allocation ID and Public IP that were created
:raises: AWSAPIError, EC2UtilError
def allocate_elastic_ip(self):
"""Allocates an elastic IP address
:return: Dict with allocation ID and Public IP that were created
:raises: AWSAP... |
Creates a new Elastic Network Interface on the Subnet
matching the subnet_name, with Security Group identified by
the security_group_name, then attaches an Elastic IP address
if specified in the allocation_id parameter, and finally
attaches the new ENI to the EC2 instance instance_id at
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.