repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
salu133445/pypianoroll
pypianoroll/multitrack.py
Multitrack.transpose
def transpose(self, semitone): """ Transpose the pianorolls of all tracks by a number of semitones, where positive values are for higher key, while negative values are for lower key. The drum tracks are ignored. Parameters ---------- semitone : int The number of semitones to transpose the pianorolls. """ for track in self.tracks: if not track.is_drum: track.transpose(semitone)
python
def transpose(self, semitone): """ Transpose the pianorolls of all tracks by a number of semitones, where positive values are for higher key, while negative values are for lower key. The drum tracks are ignored. Parameters ---------- semitone : int The number of semitones to transpose the pianorolls. """ for track in self.tracks: if not track.is_drum: track.transpose(semitone)
Transpose the pianorolls of all tracks by a number of semitones, where positive values are for higher key, while negative values are for lower key. The drum tracks are ignored. Parameters ---------- semitone : int The number of semitones to transpose the pianorolls.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L954-L968
salu133445/pypianoroll
pypianoroll/multitrack.py
Multitrack.trim_trailing_silence
def trim_trailing_silence(self): """Trim the trailing silences of the pianorolls of all tracks. Trailing silences are considered globally.""" active_length = self.get_active_length() for track in self.tracks: track.pianoroll = track.pianoroll[:active_length]
python
def trim_trailing_silence(self): """Trim the trailing silences of the pianorolls of all tracks. Trailing silences are considered globally.""" active_length = self.get_active_length() for track in self.tracks: track.pianoroll = track.pianoroll[:active_length]
Trim the trailing silences of the pianorolls of all tracks. Trailing silences are considered globally.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L970-L975
salu133445/pypianoroll
pypianoroll/multitrack.py
Multitrack.write
def write(self, filename): """ Write the multitrack pianoroll to a MIDI file. Parameters ---------- filename : str The name of the MIDI file to which the multitrack pianoroll is written. """ if not filename.endswith(('.mid', '.midi', '.MID', '.MIDI')): filename = filename + '.mid' pm = self.to_pretty_midi() pm.write(filename)
python
def write(self, filename): """ Write the multitrack pianoroll to a MIDI file. Parameters ---------- filename : str The name of the MIDI file to which the multitrack pianoroll is written. """ if not filename.endswith(('.mid', '.midi', '.MID', '.MIDI')): filename = filename + '.mid' pm = self.to_pretty_midi() pm.write(filename)
Write the multitrack pianoroll to a MIDI file. Parameters ---------- filename : str The name of the MIDI file to which the multitrack pianoroll is written.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L977-L991
salu133445/pypianoroll
pypianoroll/utilities.py
check_pianoroll
def check_pianoroll(arr): """ Return True if the array is a standard piano-roll matrix. Otherwise, return False. Raise TypeError if the input object is not a numpy array. """ if not isinstance(arr, np.ndarray): raise TypeError("`arr` must be of np.ndarray type") if not (np.issubdtype(arr.dtype, np.bool_) or np.issubdtype(arr.dtype, np.number)): return False if arr.ndim != 2: return False if arr.shape[1] != 128: return False return True
python
def check_pianoroll(arr): """ Return True if the array is a standard piano-roll matrix. Otherwise, return False. Raise TypeError if the input object is not a numpy array. """ if not isinstance(arr, np.ndarray): raise TypeError("`arr` must be of np.ndarray type") if not (np.issubdtype(arr.dtype, np.bool_) or np.issubdtype(arr.dtype, np.number)): return False if arr.ndim != 2: return False if arr.shape[1] != 128: return False return True
Return True if the array is a standard piano-roll matrix. Otherwise, return False. Raise TypeError if the input object is not a numpy array.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L20-L35
salu133445/pypianoroll
pypianoroll/utilities.py
binarize
def binarize(obj, threshold=0): """ Return a copy of the object with binarized piano-roll(s). Parameters ---------- threshold : int or float Threshold to binarize the piano-roll(s). Default to zero. """ _check_supported(obj) copied = deepcopy(obj) copied.binarize(threshold) return copied
python
def binarize(obj, threshold=0): """ Return a copy of the object with binarized piano-roll(s). Parameters ---------- threshold : int or float Threshold to binarize the piano-roll(s). Default to zero. """ _check_supported(obj) copied = deepcopy(obj) copied.binarize(threshold) return copied
Return a copy of the object with binarized piano-roll(s). Parameters ---------- threshold : int or float Threshold to binarize the piano-roll(s). Default to zero.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L53-L66
salu133445/pypianoroll
pypianoroll/utilities.py
clip
def clip(obj, lower=0, upper=127): """ Return a copy of the object with piano-roll(s) clipped by a lower bound and an upper bound specified by `lower` and `upper`, respectively. Parameters ---------- lower : int or float The lower bound to clip the piano-roll. Default to 0. upper : int or float The upper bound to clip the piano-roll. Default to 127. """ _check_supported(obj) copied = deepcopy(obj) copied.clip(lower, upper) return copied
python
def clip(obj, lower=0, upper=127): """ Return a copy of the object with piano-roll(s) clipped by a lower bound and an upper bound specified by `lower` and `upper`, respectively. Parameters ---------- lower : int or float The lower bound to clip the piano-roll. Default to 0. upper : int or float The upper bound to clip the piano-roll. Default to 127. """ _check_supported(obj) copied = deepcopy(obj) copied.clip(lower, upper) return copied
Return a copy of the object with piano-roll(s) clipped by a lower bound and an upper bound specified by `lower` and `upper`, respectively. Parameters ---------- lower : int or float The lower bound to clip the piano-roll. Default to 0. upper : int or float The upper bound to clip the piano-roll. Default to 127.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L68-L84
salu133445/pypianoroll
pypianoroll/utilities.py
pad
def pad(obj, pad_length): """ Return a copy of the object with piano-roll padded with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad along the time axis with zeros. """ _check_supported(obj) copied = deepcopy(obj) copied.pad(pad_length) return copied
python
def pad(obj, pad_length): """ Return a copy of the object with piano-roll padded with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad along the time axis with zeros. """ _check_supported(obj) copied = deepcopy(obj) copied.pad(pad_length) return copied
Return a copy of the object with piano-roll padded with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad along the time axis with zeros.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L107-L121
salu133445/pypianoroll
pypianoroll/utilities.py
pad_to_multiple
def pad_to_multiple(obj, factor): """ Return a copy of the object with its piano-roll padded with zeros at the end along the time axis with the minimal length that make the length of the resulting piano-roll a multiple of `factor`. Parameters ---------- factor : int The value which the length of the resulting piano-roll will be a multiple of. """ _check_supported(obj) copied = deepcopy(obj) copied.pad_to_multiple(factor) return copied
python
def pad_to_multiple(obj, factor): """ Return a copy of the object with its piano-roll padded with zeros at the end along the time axis with the minimal length that make the length of the resulting piano-roll a multiple of `factor`. Parameters ---------- factor : int The value which the length of the resulting piano-roll will be a multiple of. """ _check_supported(obj) copied = deepcopy(obj) copied.pad_to_multiple(factor) return copied
Return a copy of the object with its piano-roll padded with zeros at the end along the time axis with the minimal length that make the length of the resulting piano-roll a multiple of `factor`. Parameters ---------- factor : int The value which the length of the resulting piano-roll will be a multiple of.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L123-L139
salu133445/pypianoroll
pypianoroll/utilities.py
pad_to_same
def pad_to_same(obj): """ Return a copy of the object with shorter piano-rolls padded with zeros at the end along the time axis to the length of the piano-roll with the maximal length. """ if not isinstance(obj, Multitrack): raise TypeError("Support only `pypianoroll.Multitrack` class objects") copied = deepcopy(obj) copied.pad_to_same() return copied
python
def pad_to_same(obj): """ Return a copy of the object with shorter piano-rolls padded with zeros at the end along the time axis to the length of the piano-roll with the maximal length. """ if not isinstance(obj, Multitrack): raise TypeError("Support only `pypianoroll.Multitrack` class objects") copied = deepcopy(obj) copied.pad_to_same() return copied
Return a copy of the object with shorter piano-rolls padded with zeros at the end along the time axis to the length of the piano-roll with the maximal length.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L141-L152
salu133445/pypianoroll
pypianoroll/utilities.py
parse
def parse(filepath, beat_resolution=24, name='unknown'): """ Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI (.mid, .midi, .MID, .MIDI) file. Parameters ---------- filepath : str The file path to the MIDI file. """ if not filepath.endswith(('.mid', '.midi', '.MID', '.MIDI')): raise ValueError("Only MIDI files are supported") return Multitrack(filepath, beat_resolution=beat_resolution, name=name)
python
def parse(filepath, beat_resolution=24, name='unknown'): """ Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI (.mid, .midi, .MID, .MIDI) file. Parameters ---------- filepath : str The file path to the MIDI file. """ if not filepath.endswith(('.mid', '.midi', '.MID', '.MIDI')): raise ValueError("Only MIDI files are supported") return Multitrack(filepath, beat_resolution=beat_resolution, name=name)
Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI (.mid, .midi, .MID, .MIDI) file. Parameters ---------- filepath : str The file path to the MIDI file.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L154-L167
salu133445/pypianoroll
pypianoroll/utilities.py
save
def save(filepath, obj, compressed=True): """ Save the object to a .npz file. Parameters ---------- filepath : str The path to save the file. obj: `pypianoroll.Multitrack` objects The object to be saved. """ if not isinstance(obj, Multitrack): raise TypeError("Support only `pypianoroll.Multitrack` class objects") obj.save(filepath, compressed)
python
def save(filepath, obj, compressed=True): """ Save the object to a .npz file. Parameters ---------- filepath : str The path to save the file. obj: `pypianoroll.Multitrack` objects The object to be saved. """ if not isinstance(obj, Multitrack): raise TypeError("Support only `pypianoroll.Multitrack` class objects") obj.save(filepath, compressed)
Save the object to a .npz file. Parameters ---------- filepath : str The path to save the file. obj: `pypianoroll.Multitrack` objects The object to be saved.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L178-L192
salu133445/pypianoroll
pypianoroll/utilities.py
transpose
def transpose(obj, semitone): """ Return a copy of the object with piano-roll(s) transposed by `semitones` semitones. Parameters ---------- semitone : int Number of semitones to transpose the piano-roll(s). """ _check_supported(obj) copied = deepcopy(obj) copied.transpose(semitone) return copied
python
def transpose(obj, semitone): """ Return a copy of the object with piano-roll(s) transposed by `semitones` semitones. Parameters ---------- semitone : int Number of semitones to transpose the piano-roll(s). """ _check_supported(obj) copied = deepcopy(obj) copied.transpose(semitone) return copied
Return a copy of the object with piano-roll(s) transposed by `semitones` semitones. Parameters ---------- semitone : int Number of semitones to transpose the piano-roll(s).
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L194-L208
salu133445/pypianoroll
pypianoroll/utilities.py
trim_trailing_silence
def trim_trailing_silence(obj): """ Return a copy of the object with trimmed trailing silence of the piano-roll(s). """ _check_supported(obj) copied = deepcopy(obj) length = copied.get_active_length() copied.pianoroll = copied.pianoroll[:length] return copied
python
def trim_trailing_silence(obj): """ Return a copy of the object with trimmed trailing silence of the piano-roll(s). """ _check_supported(obj) copied = deepcopy(obj) length = copied.get_active_length() copied.pianoroll = copied.pianoroll[:length] return copied
Return a copy of the object with trimmed trailing silence of the piano-roll(s).
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L210-L220
salu133445/pypianoroll
pypianoroll/utilities.py
write
def write(obj, filepath): """ Write the object to a MIDI file. Parameters ---------- filepath : str The path to write the MIDI file. """ if not isinstance(obj, Multitrack): raise TypeError("Support only `pypianoroll.Multitrack` class objects") obj.write(filepath)
python
def write(obj, filepath): """ Write the object to a MIDI file. Parameters ---------- filepath : str The path to write the MIDI file. """ if not isinstance(obj, Multitrack): raise TypeError("Support only `pypianoroll.Multitrack` class objects") obj.write(filepath)
Write the object to a MIDI file. Parameters ---------- filepath : str The path to write the MIDI file.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L222-L234
salu133445/pypianoroll
pypianoroll/metrics.py
_validate_pianoroll
def _validate_pianoroll(pianoroll): """Raise an error if the input array is not a standard pianoroll.""" if not isinstance(pianoroll, np.ndarray): raise TypeError("`pianoroll` must be of np.ndarray type.") if not (np.issubdtype(pianoroll.dtype, np.bool_) or np.issubdtype(pianoroll.dtype, np.number)): raise TypeError("The data type of `pianoroll` must be np.bool_ or a " "subdtype of np.number.") if pianoroll.ndim != 2: raise ValueError("`pianoroll` must have exactly two dimensions.") if pianoroll.shape[1] != 128: raise ValueError("The length of the second axis of `pianoroll` must be " "128.")
python
def _validate_pianoroll(pianoroll): """Raise an error if the input array is not a standard pianoroll.""" if not isinstance(pianoroll, np.ndarray): raise TypeError("`pianoroll` must be of np.ndarray type.") if not (np.issubdtype(pianoroll.dtype, np.bool_) or np.issubdtype(pianoroll.dtype, np.number)): raise TypeError("The data type of `pianoroll` must be np.bool_ or a " "subdtype of np.number.") if pianoroll.ndim != 2: raise ValueError("`pianoroll` must have exactly two dimensions.") if pianoroll.shape[1] != 128: raise ValueError("The length of the second axis of `pianoroll` must be " "128.")
Raise an error if the input array is not a standard pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L7-L19
salu133445/pypianoroll
pypianoroll/metrics.py
_to_chroma
def _to_chroma(pianoroll): """Return the unnormalized chroma features of a pianoroll.""" _validate_pianoroll(pianoroll) reshaped = pianoroll[:, :120].reshape(-1, 12, 10) reshaped[..., :8] += pianoroll[:, 120:].reshape(-1, 1, 8) return np.sum(reshaped, 1)
python
def _to_chroma(pianoroll): """Return the unnormalized chroma features of a pianoroll.""" _validate_pianoroll(pianoroll) reshaped = pianoroll[:, :120].reshape(-1, 12, 10) reshaped[..., :8] += pianoroll[:, 120:].reshape(-1, 1, 8) return np.sum(reshaped, 1)
Return the unnormalized chroma features of a pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L21-L26
salu133445/pypianoroll
pypianoroll/metrics.py
empty_beat_rate
def empty_beat_rate(pianoroll, beat_resolution): """Return the ratio of empty beats to the total number of beats in a pianoroll.""" _validate_pianoroll(pianoroll) reshaped = pianoroll.reshape(-1, beat_resolution * pianoroll.shape[1]) n_empty_beats = np.count_nonzero(reshaped.any(1)) return n_empty_beats / len(reshaped)
python
def empty_beat_rate(pianoroll, beat_resolution): """Return the ratio of empty beats to the total number of beats in a pianoroll.""" _validate_pianoroll(pianoroll) reshaped = pianoroll.reshape(-1, beat_resolution * pianoroll.shape[1]) n_empty_beats = np.count_nonzero(reshaped.any(1)) return n_empty_beats / len(reshaped)
Return the ratio of empty beats to the total number of beats in a pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L28-L34
salu133445/pypianoroll
pypianoroll/metrics.py
n_pitche_classes_used
def n_pitche_classes_used(pianoroll): """Return the number of unique pitch classes used in a pianoroll.""" _validate_pianoroll(pianoroll) chroma = _to_chroma(pianoroll) return np.count_nonzero(np.any(chroma, 0))
python
def n_pitche_classes_used(pianoroll): """Return the number of unique pitch classes used in a pianoroll.""" _validate_pianoroll(pianoroll) chroma = _to_chroma(pianoroll) return np.count_nonzero(np.any(chroma, 0))
Return the number of unique pitch classes used in a pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L41-L45
salu133445/pypianoroll
pypianoroll/metrics.py
qualified_note_rate
def qualified_note_rate(pianoroll, threshold=2): """Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a pianoroll.""" _validate_pianoroll(pianoroll) if np.issubdtype(pianoroll.dtype, np.bool_): pianoroll = pianoroll.astype(np.uint8) padded = np.pad(pianoroll, ((1, 1), (0, 0)), 'constant') diff = np.diff(padded, axis=0).reshape(-1) onsets = (diff > 0).nonzero()[0] offsets = (diff < 0).nonzero()[0] n_qualified_notes = np.count_nonzero(offsets - onsets >= threshold) return n_qualified_notes / len(onsets)
python
def qualified_note_rate(pianoroll, threshold=2): """Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a pianoroll.""" _validate_pianoroll(pianoroll) if np.issubdtype(pianoroll.dtype, np.bool_): pianoroll = pianoroll.astype(np.uint8) padded = np.pad(pianoroll, ((1, 1), (0, 0)), 'constant') diff = np.diff(padded, axis=0).reshape(-1) onsets = (diff > 0).nonzero()[0] offsets = (diff < 0).nonzero()[0] n_qualified_notes = np.count_nonzero(offsets - onsets >= threshold) return n_qualified_notes / len(onsets)
Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L47-L58
salu133445/pypianoroll
pypianoroll/metrics.py
polyphonic_rate
def polyphonic_rate(pianoroll, threshold=2): """Return the ratio of the number of time steps where the number of pitches being played is larger than `threshold` to the total number of time steps in a pianoroll.""" _validate_pianoroll(pianoroll) n_poly = np.count_nonzero(np.count_nonzero(pianoroll, 1) > threshold) return n_poly / len(pianoroll)
python
def polyphonic_rate(pianoroll, threshold=2): """Return the ratio of the number of time steps where the number of pitches being played is larger than `threshold` to the total number of time steps in a pianoroll.""" _validate_pianoroll(pianoroll) n_poly = np.count_nonzero(np.count_nonzero(pianoroll, 1) > threshold) return n_poly / len(pianoroll)
Return the ratio of the number of time steps where the number of pitches being played is larger than `threshold` to the total number of time steps in a pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L60-L66
salu133445/pypianoroll
pypianoroll/metrics.py
drum_in_pattern_rate
def drum_in_pattern_rate(pianoroll, beat_resolution, tolerance=0.1): """Return the ratio of the number of drum notes that lie on the drum pattern (i.e., at certain time steps) to the total number of drum notes.""" if beat_resolution not in (4, 6, 8, 9, 12, 16, 18, 24): raise ValueError("Unsupported beat resolution. Only 4, 6, 8 ,9, 12, " "16, 18, 42 are supported.") _validate_pianoroll(pianoroll) def _drum_pattern_mask(res, tol): """Return a drum pattern mask with the given tolerance.""" if res == 24: drum_pattern_mask = np.tile([1., tol, 0., 0., 0., tol], 4) elif res == 12: drum_pattern_mask = np.tile([1., tol, tol], 4) elif res == 6: drum_pattern_mask = np.tile([1., tol, tol], 2) elif res == 18: drum_pattern_mask = np.tile([1., tol, 0., 0., 0., tol], 3) elif res == 9: drum_pattern_mask = np.tile([1., tol, tol], 3) elif res == 16: drum_pattern_mask = np.tile([1., tol, 0., tol], 4) elif res == 8: drum_pattern_mask = np.tile([1., tol], 4) elif res == 4: drum_pattern_mask = np.tile([1., tol], 2) return drum_pattern_mask drum_pattern_mask = _drum_pattern_mask(beat_resolution, tolerance) n_in_pattern = np.sum(drum_pattern_mask * np.count_nonzero(pianoroll, 1)) return n_in_pattern / np.count_nonzero(pianoroll)
python
def drum_in_pattern_rate(pianoroll, beat_resolution, tolerance=0.1): """Return the ratio of the number of drum notes that lie on the drum pattern (i.e., at certain time steps) to the total number of drum notes.""" if beat_resolution not in (4, 6, 8, 9, 12, 16, 18, 24): raise ValueError("Unsupported beat resolution. Only 4, 6, 8 ,9, 12, " "16, 18, 42 are supported.") _validate_pianoroll(pianoroll) def _drum_pattern_mask(res, tol): """Return a drum pattern mask with the given tolerance.""" if res == 24: drum_pattern_mask = np.tile([1., tol, 0., 0., 0., tol], 4) elif res == 12: drum_pattern_mask = np.tile([1., tol, tol], 4) elif res == 6: drum_pattern_mask = np.tile([1., tol, tol], 2) elif res == 18: drum_pattern_mask = np.tile([1., tol, 0., 0., 0., tol], 3) elif res == 9: drum_pattern_mask = np.tile([1., tol, tol], 3) elif res == 16: drum_pattern_mask = np.tile([1., tol, 0., tol], 4) elif res == 8: drum_pattern_mask = np.tile([1., tol], 4) elif res == 4: drum_pattern_mask = np.tile([1., tol], 2) return drum_pattern_mask drum_pattern_mask = _drum_pattern_mask(beat_resolution, tolerance) n_in_pattern = np.sum(drum_pattern_mask * np.count_nonzero(pianoroll, 1)) return n_in_pattern / np.count_nonzero(pianoroll)
Return the ratio of the number of drum notes that lie on the drum pattern (i.e., at certain time steps) to the total number of drum notes.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L68-L98
salu133445/pypianoroll
pypianoroll/metrics.py
in_scale_rate
def in_scale_rate(pianoroll, key=3, kind='major'): """Return the ratio of the number of nonzero entries that lie in a specific scale to the total number of nonzero entries in a pianoroll. Default to C major scale.""" if not isinstance(key, int): raise TypeError("`key` must an integer.") if key > 11 or key < 0: raise ValueError("`key` must be in an integer in between 0 and 11.") if kind not in ('major', 'minor'): raise ValueError("`kind` must be one of 'major' or 'minor'.") _validate_pianoroll(pianoroll) def _scale_mask(key, kind): """Return a scale mask for the given key. Default to C major scale.""" if kind == 'major': a_scale_mask = np.array([0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1], bool) else: a_scale_mask = np.array([1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1], bool) return np.roll(a_scale_mask, key) chroma = _to_chroma(pianoroll) scale_mask = _scale_mask(key, kind) n_in_scale = np.sum(scale_mask.reshape(-1, 12) * chroma) return n_in_scale / np.count_nonzero(pianoroll)
python
def in_scale_rate(pianoroll, key=3, kind='major'): """Return the ratio of the number of nonzero entries that lie in a specific scale to the total number of nonzero entries in a pianoroll. Default to C major scale.""" if not isinstance(key, int): raise TypeError("`key` must an integer.") if key > 11 or key < 0: raise ValueError("`key` must be in an integer in between 0 and 11.") if kind not in ('major', 'minor'): raise ValueError("`kind` must be one of 'major' or 'minor'.") _validate_pianoroll(pianoroll) def _scale_mask(key, kind): """Return a scale mask for the given key. Default to C major scale.""" if kind == 'major': a_scale_mask = np.array([0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1], bool) else: a_scale_mask = np.array([1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1], bool) return np.roll(a_scale_mask, key) chroma = _to_chroma(pianoroll) scale_mask = _scale_mask(key, kind) n_in_scale = np.sum(scale_mask.reshape(-1, 12) * chroma) return n_in_scale / np.count_nonzero(pianoroll)
Return the ratio of the number of nonzero entries that lie in a specific scale to the total number of nonzero entries in a pianoroll. Default to C major scale.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L100-L123
salu133445/pypianoroll
pypianoroll/metrics.py
tonal_distance
def tonal_distance(pianoroll_1, pianoroll_2, beat_resolution, r1=1.0, r2=1.0, r3=0.5): """Return the tonal distance [1] between the two input pianorolls. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM Workshop on Audio and Music Computing Multimedia, 2006. """ _validate_pianoroll(pianoroll_1) _validate_pianoroll(pianoroll_2) assert len(pianoroll_1) == len(pianoroll_2), ( "Input pianorolls must have the same length.") def _tonal_matrix(r1, r2, r3): """Return a tonal matrix for computing the tonal distance.""" tonal_matrix = np.empty((6, 12)) tonal_matrix[0] = r1 * np.sin(np.arange(12) * (7. / 6.) * np.pi) tonal_matrix[1] = r1 * np.cos(np.arange(12) * (7. / 6.) * np.pi) tonal_matrix[2] = r2 * np.sin(np.arange(12) * (3. / 2.) * np.pi) tonal_matrix[3] = r2 * np.cos(np.arange(12) * (3. / 2.) * np.pi) tonal_matrix[4] = r3 * np.sin(np.arange(12) * (2. / 3.) * np.pi) tonal_matrix[5] = r3 * np.cos(np.arange(12) * (2. / 3.) * np.pi) return tonal_matrix def _to_tonal_space(pianoroll, tonal_matrix): """Return the tensor in tonal space where chroma features are normalized per beat.""" beat_chroma = _to_chroma(pianoroll).reshape(-1, beat_resolution, 12) beat_chroma = beat_chroma / np.sum(beat_chroma, 2, keepdims=True) return np.matmul(tonal_matrix, beat_chroma.T).T tonal_matrix = _tonal_matrix(r1, r2, r3) mapped_1 = _to_tonal_space(pianoroll_1, tonal_matrix) mapped_2 = _to_tonal_space(pianoroll_2, tonal_matrix) return np.linalg.norm(mapped_1 - mapped_2)
python
def tonal_distance(pianoroll_1, pianoroll_2, beat_resolution, r1=1.0, r2=1.0, r3=0.5): """Return the tonal distance [1] between the two input pianorolls. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM Workshop on Audio and Music Computing Multimedia, 2006. """ _validate_pianoroll(pianoroll_1) _validate_pianoroll(pianoroll_2) assert len(pianoroll_1) == len(pianoroll_2), ( "Input pianorolls must have the same length.") def _tonal_matrix(r1, r2, r3): """Return a tonal matrix for computing the tonal distance.""" tonal_matrix = np.empty((6, 12)) tonal_matrix[0] = r1 * np.sin(np.arange(12) * (7. / 6.) * np.pi) tonal_matrix[1] = r1 * np.cos(np.arange(12) * (7. / 6.) * np.pi) tonal_matrix[2] = r2 * np.sin(np.arange(12) * (3. / 2.) * np.pi) tonal_matrix[3] = r2 * np.cos(np.arange(12) * (3. / 2.) * np.pi) tonal_matrix[4] = r3 * np.sin(np.arange(12) * (2. / 3.) * np.pi) tonal_matrix[5] = r3 * np.cos(np.arange(12) * (2. / 3.) * np.pi) return tonal_matrix def _to_tonal_space(pianoroll, tonal_matrix): """Return the tensor in tonal space where chroma features are normalized per beat.""" beat_chroma = _to_chroma(pianoroll).reshape(-1, beat_resolution, 12) beat_chroma = beat_chroma / np.sum(beat_chroma, 2, keepdims=True) return np.matmul(tonal_matrix, beat_chroma.T).T tonal_matrix = _tonal_matrix(r1, r2, r3) mapped_1 = _to_tonal_space(pianoroll_1, tonal_matrix) mapped_2 = _to_tonal_space(pianoroll_2, tonal_matrix) return np.linalg.norm(mapped_1 - mapped_2)
Return the tonal distance [1] between the two input pianorolls. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM Workshop on Audio and Music Computing Multimedia, 2006.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L125-L160
salu133445/pypianoroll
pypianoroll/track.py
Track.assign_constant
def assign_constant(self, value, dtype=None): """ Assign a constant value to all nonzeros in the pianoroll. If the pianoroll is not binarized, its data type will be preserved. If the pianoroll is binarized, it will be casted to the type of `value`. Arguments --------- value : int or float The constant value to be assigned to all the nonzeros in the pianoroll. """ if not self.is_binarized(): self.pianoroll[self.pianoroll.nonzero()] = value return if dtype is None: if isinstance(value, int): dtype = int elif isinstance(value, float): dtype = float nonzero = self.pianoroll.nonzero() self.pianoroll = np.zeros(self.pianoroll.shape, dtype) self.pianoroll[nonzero] = value
python
def assign_constant(self, value, dtype=None): """ Assign a constant value to all nonzeros in the pianoroll. If the pianoroll is not binarized, its data type will be preserved. If the pianoroll is binarized, it will be casted to the type of `value`. Arguments --------- value : int or float The constant value to be assigned to all the nonzeros in the pianoroll. """ if not self.is_binarized(): self.pianoroll[self.pianoroll.nonzero()] = value return if dtype is None: if isinstance(value, int): dtype = int elif isinstance(value, float): dtype = float nonzero = self.pianoroll.nonzero() self.pianoroll = np.zeros(self.pianoroll.shape, dtype) self.pianoroll[nonzero] = value
Assign a constant value to all nonzeros in the pianoroll. If the pianoroll is not binarized, its data type will be preserved. If the pianoroll is binarized, it will be casted to the type of `value`. Arguments --------- value : int or float The constant value to be assigned to all the nonzeros in the pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L76-L99
salu133445/pypianoroll
pypianoroll/track.py
Track.binarize
def binarize(self, threshold=0): """ Binarize the pianoroll. Parameters ---------- threshold : int or float A threshold used to binarize the pianorolls. Defaults to zero. """ if not self.is_binarized(): self.pianoroll = (self.pianoroll > threshold)
python
def binarize(self, threshold=0): """ Binarize the pianoroll. Parameters ---------- threshold : int or float A threshold used to binarize the pianorolls. Defaults to zero. """ if not self.is_binarized(): self.pianoroll = (self.pianoroll > threshold)
Binarize the pianoroll. Parameters ---------- threshold : int or float A threshold used to binarize the pianorolls. Defaults to zero.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L101-L112
salu133445/pypianoroll
pypianoroll/track.py
Track.check_validity
def check_validity(self): """"Raise error if any invalid attribute found.""" # pianoroll if not isinstance(self.pianoroll, np.ndarray): raise TypeError("`pianoroll` must be a numpy array.") if not (np.issubdtype(self.pianoroll.dtype, np.bool_) or np.issubdtype(self.pianoroll.dtype, np.number)): raise TypeError("The data type of `pianoroll` must be np.bool_ or " "a subdtype of np.number.") if self.pianoroll.ndim != 2: raise ValueError("`pianoroll` must have exactly two dimensions.") if self.pianoroll.shape[1] != 128: raise ValueError("The length of the second axis of `pianoroll` " "must be 128.") # program if not isinstance(self.program, int): raise TypeError("`program` must be int.") if self.program < 0 or self.program > 127: raise ValueError("`program` must be in between 0 to 127.") # is_drum if not isinstance(self.is_drum, bool): raise TypeError("`is_drum` must be bool.") # name if not isinstance(self.name, string_types): raise TypeError("`name` must be a string.")
python
def check_validity(self): """"Raise error if any invalid attribute found.""" # pianoroll if not isinstance(self.pianoroll, np.ndarray): raise TypeError("`pianoroll` must be a numpy array.") if not (np.issubdtype(self.pianoroll.dtype, np.bool_) or np.issubdtype(self.pianoroll.dtype, np.number)): raise TypeError("The data type of `pianoroll` must be np.bool_ or " "a subdtype of np.number.") if self.pianoroll.ndim != 2: raise ValueError("`pianoroll` must have exactly two dimensions.") if self.pianoroll.shape[1] != 128: raise ValueError("The length of the second axis of `pianoroll` " "must be 128.") # program if not isinstance(self.program, int): raise TypeError("`program` must be int.") if self.program < 0 or self.program > 127: raise ValueError("`program` must be in between 0 to 127.") # is_drum if not isinstance(self.is_drum, bool): raise TypeError("`is_drum` must be bool.") # name if not isinstance(self.name, string_types): raise TypeError("`name` must be a string.")
Raise error if any invalid attribute found.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L114-L138
salu133445/pypianoroll
pypianoroll/track.py
Track.clip
def clip(self, lower=0, upper=127): """ Clip the pianoroll by the given lower and upper bounds. Parameters ---------- lower : int or float The lower bound to clip the pianoroll. Defaults to 0. upper : int or float The upper bound to clip the pianoroll. Defaults to 127. """ self.pianoroll = self.pianoroll.clip(lower, upper)
python
def clip(self, lower=0, upper=127): """ Clip the pianoroll by the given lower and upper bounds. Parameters ---------- lower : int or float The lower bound to clip the pianoroll. Defaults to 0. upper : int or float The upper bound to clip the pianoroll. Defaults to 127. """ self.pianoroll = self.pianoroll.clip(lower, upper)
Clip the pianoroll by the given lower and upper bounds. Parameters ---------- lower : int or float The lower bound to clip the pianoroll. Defaults to 0. upper : int or float The upper bound to clip the pianoroll. Defaults to 127.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L140-L152
salu133445/pypianoroll
pypianoroll/track.py
Track.get_active_length
def get_active_length(self): """ Return the active length (i.e., without trailing silence) of the pianoroll. The unit is time step. Returns ------- active_length : int The active length (i.e., without trailing silence) of the pianoroll. """ nonzero_steps = np.any(self.pianoroll, axis=1) inv_last_nonzero_step = np.argmax(np.flip(nonzero_steps, axis=0)) active_length = self.pianoroll.shape[0] - inv_last_nonzero_step return active_length
python
def get_active_length(self): """ Return the active length (i.e., without trailing silence) of the pianoroll. The unit is time step. Returns ------- active_length : int The active length (i.e., without trailing silence) of the pianoroll. """ nonzero_steps = np.any(self.pianoroll, axis=1) inv_last_nonzero_step = np.argmax(np.flip(nonzero_steps, axis=0)) active_length = self.pianoroll.shape[0] - inv_last_nonzero_step return active_length
Return the active length (i.e., without trailing silence) of the pianoroll. The unit is time step. Returns ------- active_length : int The active length (i.e., without trailing silence) of the pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L167-L181
salu133445/pypianoroll
pypianoroll/track.py
Track.get_active_pitch_range
def get_active_pitch_range(self): """ Return the active pitch range as a tuple (lowest, highest). Returns ------- lowest : int The lowest active pitch in the pianoroll. highest : int The highest active pitch in the pianoroll. """ if self.pianoroll.shape[1] < 1: raise ValueError("Cannot compute the active pitch range for an " "empty pianoroll") lowest = 0 highest = 127 while lowest < highest: if np.any(self.pianoroll[:, lowest]): break lowest += 1 if lowest == highest: raise ValueError("Cannot compute the active pitch range for an " "empty pianoroll") while not np.any(self.pianoroll[:, highest]): highest -= 1 return lowest, highest
python
def get_active_pitch_range(self): """ Return the active pitch range as a tuple (lowest, highest). Returns ------- lowest : int The lowest active pitch in the pianoroll. highest : int The highest active pitch in the pianoroll. """ if self.pianoroll.shape[1] < 1: raise ValueError("Cannot compute the active pitch range for an " "empty pianoroll") lowest = 0 highest = 127 while lowest < highest: if np.any(self.pianoroll[:, lowest]): break lowest += 1 if lowest == highest: raise ValueError("Cannot compute the active pitch range for an " "empty pianoroll") while not np.any(self.pianoroll[:, highest]): highest -= 1 return lowest, highest
Return the active pitch range as a tuple (lowest, highest). Returns ------- lowest : int The lowest active pitch in the pianoroll. highest : int The highest active pitch in the pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L183-L210
salu133445/pypianoroll
pypianoroll/track.py
Track.is_binarized
def is_binarized(self): """ Return True if the pianoroll is already binarized. Otherwise, return False. Returns ------- is_binarized : bool True if the pianoroll is already binarized; otherwise, False. """ is_binarized = np.issubdtype(self.pianoroll.dtype, np.bool_) return is_binarized
python
def is_binarized(self): """ Return True if the pianoroll is already binarized. Otherwise, return False. Returns ------- is_binarized : bool True if the pianoroll is already binarized; otherwise, False. """ is_binarized = np.issubdtype(self.pianoroll.dtype, np.bool_) return is_binarized
Return True if the pianoroll is already binarized. Otherwise, return False. Returns ------- is_binarized : bool True if the pianoroll is already binarized; otherwise, False.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L225-L237
salu133445/pypianoroll
pypianoroll/track.py
Track.pad
def pad(self, pad_length): """ Pad the pianoroll with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad with zeros along the time axis. """ self.pianoroll = np.pad( self.pianoroll, ((0, pad_length), (0, 0)), 'constant')
python
def pad(self, pad_length): """ Pad the pianoroll with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad with zeros along the time axis. """ self.pianoroll = np.pad( self.pianoroll, ((0, pad_length), (0, 0)), 'constant')
Pad the pianoroll with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad with zeros along the time axis.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L239-L250
salu133445/pypianoroll
pypianoroll/track.py
Track.pad_to_multiple
def pad_to_multiple(self, factor): """ Pad the pianoroll with zeros at the end along the time axis with the minimum length that makes the resulting pianoroll length a multiple of `factor`. Parameters ---------- factor : int The value which the length of the resulting pianoroll will be a multiple of. """ remainder = self.pianoroll.shape[0] % factor if remainder: pad_width = ((0, (factor - remainder)), (0, 0)) self.pianoroll = np.pad(self.pianoroll, pad_width, 'constant')
python
def pad_to_multiple(self, factor): """ Pad the pianoroll with zeros at the end along the time axis with the minimum length that makes the resulting pianoroll length a multiple of `factor`. Parameters ---------- factor : int The value which the length of the resulting pianoroll will be a multiple of. """ remainder = self.pianoroll.shape[0] % factor if remainder: pad_width = ((0, (factor - remainder)), (0, 0)) self.pianoroll = np.pad(self.pianoroll, pad_width, 'constant')
Pad the pianoroll with zeros at the end along the time axis with the minimum length that makes the resulting pianoroll length a multiple of `factor`. Parameters ---------- factor : int The value which the length of the resulting pianoroll will be a multiple of.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L252-L268
salu133445/pypianoroll
pypianoroll/track.py
Track.transpose
def transpose(self, semitone): """ Transpose the pianoroll by a number of semitones, where positive values are for higher key, while negative values are for lower key. Parameters ---------- semitone : int The number of semitones to transpose the pianoroll. """ if semitone > 0 and semitone < 128: self.pianoroll[:, semitone:] = self.pianoroll[:, :(128 - semitone)] self.pianoroll[:, :semitone] = 0 elif semitone < 0 and semitone > -128: self.pianoroll[:, :(128 + semitone)] = self.pianoroll[:, -semitone:] self.pianoroll[:, (128 + semitone):] = 0
python
def transpose(self, semitone): """ Transpose the pianoroll by a number of semitones, where positive values are for higher key, while negative values are for lower key. Parameters ---------- semitone : int The number of semitones to transpose the pianoroll. """ if semitone > 0 and semitone < 128: self.pianoroll[:, semitone:] = self.pianoroll[:, :(128 - semitone)] self.pianoroll[:, :semitone] = 0 elif semitone < 0 and semitone > -128: self.pianoroll[:, :(128 + semitone)] = self.pianoroll[:, -semitone:] self.pianoroll[:, (128 + semitone):] = 0
Transpose the pianoroll by a number of semitones, where positive values are for higher key, while negative values are for lower key. Parameters ---------- semitone : int The number of semitones to transpose the pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L275-L291
salu133445/pypianoroll
pypianoroll/track.py
Track.trim_trailing_silence
def trim_trailing_silence(self): """Trim the trailing silence of the pianoroll.""" length = self.get_active_length() self.pianoroll = self.pianoroll[:length]
python
def trim_trailing_silence(self): """Trim the trailing silence of the pianoroll.""" length = self.get_active_length() self.pianoroll = self.pianoroll[:length]
Trim the trailing silence of the pianoroll.
https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L293-L296
dnouri/nolearn
nolearn/lasagne/visualize.py
plot_conv_weights
def plot_conv_weights(layer, figsize=(6, 6)): """Plot the weights of a specific layer. Only really makes sense with convolutional layers. Parameters ---------- layer : lasagne.layers.Layer """ W = layer.W.get_value() shape = W.shape nrows = np.ceil(np.sqrt(shape[0])).astype(int) ncols = nrows for feature_map in range(shape[1]): figs, axes = plt.subplots(nrows, ncols, figsize=figsize, squeeze=False) for ax in axes.flatten(): ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') for i, (r, c) in enumerate(product(range(nrows), range(ncols))): if i >= shape[0]: break axes[r, c].imshow(W[i, feature_map], cmap='gray', interpolation='none') return plt
python
def plot_conv_weights(layer, figsize=(6, 6)): """Plot the weights of a specific layer. Only really makes sense with convolutional layers. Parameters ---------- layer : lasagne.layers.Layer """ W = layer.W.get_value() shape = W.shape nrows = np.ceil(np.sqrt(shape[0])).astype(int) ncols = nrows for feature_map in range(shape[1]): figs, axes = plt.subplots(nrows, ncols, figsize=figsize, squeeze=False) for ax in axes.flatten(): ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') for i, (r, c) in enumerate(product(range(nrows), range(ncols))): if i >= shape[0]: break axes[r, c].imshow(W[i, feature_map], cmap='gray', interpolation='none') return plt
Plot the weights of a specific layer. Only really makes sense with convolutional layers. Parameters ---------- layer : lasagne.layers.Layer
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L26-L54
dnouri/nolearn
nolearn/lasagne/visualize.py
plot_conv_activity
def plot_conv_activity(layer, x, figsize=(6, 8)): """Plot the acitivities of a specific layer. Only really makes sense with layers that work 2D data (2D convolutional layers, 2D pooling layers ...). Parameters ---------- layer : lasagne.layers.Layer x : numpy.ndarray Only takes one sample at a time, i.e. x.shape[0] == 1. """ if x.shape[0] != 1: raise ValueError("Only one sample can be plotted at a time.") # compile theano function xs = T.tensor4('xs').astype(theano.config.floatX) get_activity = theano.function([xs], get_output(layer, xs)) activity = get_activity(x) shape = activity.shape nrows = np.ceil(np.sqrt(shape[1])).astype(int) ncols = nrows figs, axes = plt.subplots(nrows + 1, ncols, figsize=figsize, squeeze=False) axes[0, ncols // 2].imshow(1 - x[0][0], cmap='gray', interpolation='none') axes[0, ncols // 2].set_title('original') for ax in axes.flatten(): ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') for i, (r, c) in enumerate(product(range(nrows), range(ncols))): if i >= shape[1]: break ndim = activity[0][i].ndim if ndim != 2: raise ValueError("Wrong number of dimensions, image data should " "have 2, instead got {}".format(ndim)) axes[r + 1, c].imshow(-activity[0][i], cmap='gray', interpolation='none') return plt
python
def plot_conv_activity(layer, x, figsize=(6, 8)): """Plot the acitivities of a specific layer. Only really makes sense with layers that work 2D data (2D convolutional layers, 2D pooling layers ...). Parameters ---------- layer : lasagne.layers.Layer x : numpy.ndarray Only takes one sample at a time, i.e. x.shape[0] == 1. """ if x.shape[0] != 1: raise ValueError("Only one sample can be plotted at a time.") # compile theano function xs = T.tensor4('xs').astype(theano.config.floatX) get_activity = theano.function([xs], get_output(layer, xs)) activity = get_activity(x) shape = activity.shape nrows = np.ceil(np.sqrt(shape[1])).astype(int) ncols = nrows figs, axes = plt.subplots(nrows + 1, ncols, figsize=figsize, squeeze=False) axes[0, ncols // 2].imshow(1 - x[0][0], cmap='gray', interpolation='none') axes[0, ncols // 2].set_title('original') for ax in axes.flatten(): ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') for i, (r, c) in enumerate(product(range(nrows), range(ncols))): if i >= shape[1]: break ndim = activity[0][i].ndim if ndim != 2: raise ValueError("Wrong number of dimensions, image data should " "have 2, instead got {}".format(ndim)) axes[r + 1, c].imshow(-activity[0][i], cmap='gray', interpolation='none') return plt
Plot the acitivities of a specific layer. Only really makes sense with layers that work 2D data (2D convolutional layers, 2D pooling layers ...). Parameters ---------- layer : lasagne.layers.Layer x : numpy.ndarray Only takes one sample at a time, i.e. x.shape[0] == 1.
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L57-L102
dnouri/nolearn
nolearn/lasagne/visualize.py
occlusion_heatmap
def occlusion_heatmap(net, x, target, square_length=7): """An occlusion test that checks an image for its critical parts. In this function, a square part of the image is occluded (i.e. set to 0) and then the net is tested for its propensity to predict the correct label. One should expect that this propensity shrinks of critical parts of the image are occluded. If not, this indicates overfitting. Depending on the depth of the net and the size of the image, this function may take awhile to finish, since one prediction for each pixel of the image is made. Currently, all color channels are occluded at the same time. Also, this does not really work if images are randomly distorted by the batch iterator. See paper: Zeiler, Fergus 2013 Parameters ---------- net : NeuralNet instance The neural net to test. x : np.array The input data, should be of shape (1, c, x, y). Only makes sense with image data. target : int The true value of the image. If the net makes several predictions, say 10 classes, this indicates which one to look at. square_length : int (default=7) The length of the side of the square that occludes the image. Must be an odd number. Results ------- heat_array : np.array (with same size as image) An 2D np.array that at each point (i, j) contains the predicted probability of the correct class if the image is occluded by a square with center (i, j). """ if (x.ndim != 4) or x.shape[0] != 1: raise ValueError("This function requires the input data to be of " "shape (1, c, x, y), instead got {}".format(x.shape)) if square_length % 2 == 0: raise ValueError("Square length has to be an odd number, instead " "got {}.".format(square_length)) num_classes = get_output_shape(net.layers_[-1])[1] img = x[0].copy() bs, col, s0, s1 = x.shape heat_array = np.zeros((s0, s1)) pad = square_length // 2 + 1 x_occluded = np.zeros((s1, col, s0, s1), dtype=img.dtype) probs = np.zeros((s0, s1, num_classes)) # generate occluded images for i in range(s0): # batch s1 occluded images for faster prediction for j in range(s1): x_pad = np.pad(img, ((0, 0), (pad, pad), (pad, pad)), 'constant') x_pad[:, i:i + square_length, j:j + square_length] = 0. x_occluded[j] = x_pad[:, pad:-pad, pad:-pad] y_proba = net.predict_proba(x_occluded) probs[i] = y_proba.reshape(s1, num_classes) # from predicted probabilities, pick only those of target class for i in range(s0): for j in range(s1): heat_array[i, j] = probs[i, j, target] return heat_array
python
def occlusion_heatmap(net, x, target, square_length=7): """An occlusion test that checks an image for its critical parts. In this function, a square part of the image is occluded (i.e. set to 0) and then the net is tested for its propensity to predict the correct label. One should expect that this propensity shrinks of critical parts of the image are occluded. If not, this indicates overfitting. Depending on the depth of the net and the size of the image, this function may take awhile to finish, since one prediction for each pixel of the image is made. Currently, all color channels are occluded at the same time. Also, this does not really work if images are randomly distorted by the batch iterator. See paper: Zeiler, Fergus 2013 Parameters ---------- net : NeuralNet instance The neural net to test. x : np.array The input data, should be of shape (1, c, x, y). Only makes sense with image data. target : int The true value of the image. If the net makes several predictions, say 10 classes, this indicates which one to look at. square_length : int (default=7) The length of the side of the square that occludes the image. Must be an odd number. Results ------- heat_array : np.array (with same size as image) An 2D np.array that at each point (i, j) contains the predicted probability of the correct class if the image is occluded by a square with center (i, j). """ if (x.ndim != 4) or x.shape[0] != 1: raise ValueError("This function requires the input data to be of " "shape (1, c, x, y), instead got {}".format(x.shape)) if square_length % 2 == 0: raise ValueError("Square length has to be an odd number, instead " "got {}.".format(square_length)) num_classes = get_output_shape(net.layers_[-1])[1] img = x[0].copy() bs, col, s0, s1 = x.shape heat_array = np.zeros((s0, s1)) pad = square_length // 2 + 1 x_occluded = np.zeros((s1, col, s0, s1), dtype=img.dtype) probs = np.zeros((s0, s1, num_classes)) # generate occluded images for i in range(s0): # batch s1 occluded images for faster prediction for j in range(s1): x_pad = np.pad(img, ((0, 0), (pad, pad), (pad, pad)), 'constant') x_pad[:, i:i + square_length, j:j + square_length] = 0. x_occluded[j] = x_pad[:, pad:-pad, pad:-pad] y_proba = net.predict_proba(x_occluded) probs[i] = y_proba.reshape(s1, num_classes) # from predicted probabilities, pick only those of target class for i in range(s0): for j in range(s1): heat_array[i, j] = probs[i, j, target] return heat_array
An occlusion test that checks an image for its critical parts. In this function, a square part of the image is occluded (i.e. set to 0) and then the net is tested for its propensity to predict the correct label. One should expect that this propensity shrinks of critical parts of the image are occluded. If not, this indicates overfitting. Depending on the depth of the net and the size of the image, this function may take awhile to finish, since one prediction for each pixel of the image is made. Currently, all color channels are occluded at the same time. Also, this does not really work if images are randomly distorted by the batch iterator. See paper: Zeiler, Fergus 2013 Parameters ---------- net : NeuralNet instance The neural net to test. x : np.array The input data, should be of shape (1, c, x, y). Only makes sense with image data. target : int The true value of the image. If the net makes several predictions, say 10 classes, this indicates which one to look at. square_length : int (default=7) The length of the side of the square that occludes the image. Must be an odd number. Results ------- heat_array : np.array (with same size as image) An 2D np.array that at each point (i, j) contains the predicted probability of the correct class if the image is occluded by a square with center (i, j).
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L105-L180
dnouri/nolearn
nolearn/lasagne/visualize.py
plot_occlusion
def plot_occlusion(net, X, target, square_length=7, figsize=(9, None)): """Plot which parts of an image are particularly import for the net to classify the image correctly. See paper: Zeiler, Fergus 2013 Parameters ---------- net : NeuralNet instance The neural net to test. X : numpy.array The input data, should be of shape (b, c, 0, 1). Only makes sense with image data. target : list or numpy.array of ints The true values of the image. If the net makes several predictions, say 10 classes, this indicates which one to look at. If more than one sample is passed to X, each of them needs its own target. square_length : int (default=7) The length of the side of the square that occludes the image. Must be an odd number. figsize : tuple (int, int) Size of the figure. Plots ----- Figure with 3 subplots: the original image, the occlusion heatmap, and both images super-imposed. """ return _plot_heat_map( net, X, figsize, lambda net, X, n: occlusion_heatmap( net, X, target[n], square_length))
python
def plot_occlusion(net, X, target, square_length=7, figsize=(9, None)): """Plot which parts of an image are particularly import for the net to classify the image correctly. See paper: Zeiler, Fergus 2013 Parameters ---------- net : NeuralNet instance The neural net to test. X : numpy.array The input data, should be of shape (b, c, 0, 1). Only makes sense with image data. target : list or numpy.array of ints The true values of the image. If the net makes several predictions, say 10 classes, this indicates which one to look at. If more than one sample is passed to X, each of them needs its own target. square_length : int (default=7) The length of the side of the square that occludes the image. Must be an odd number. figsize : tuple (int, int) Size of the figure. Plots ----- Figure with 3 subplots: the original image, the occlusion heatmap, and both images super-imposed. """ return _plot_heat_map( net, X, figsize, lambda net, X, n: occlusion_heatmap( net, X, target[n], square_length))
Plot which parts of an image are particularly import for the net to classify the image correctly. See paper: Zeiler, Fergus 2013 Parameters ---------- net : NeuralNet instance The neural net to test. X : numpy.array The input data, should be of shape (b, c, 0, 1). Only makes sense with image data. target : list or numpy.array of ints The true values of the image. If the net makes several predictions, say 10 classes, this indicates which one to look at. If more than one sample is passed to X, each of them needs its own target. square_length : int (default=7) The length of the side of the square that occludes the image. Must be an odd number. figsize : tuple (int, int) Size of the figure. Plots ----- Figure with 3 subplots: the original image, the occlusion heatmap, and both images super-imposed.
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L214-L250
dnouri/nolearn
nolearn/lasagne/visualize.py
get_hex_color
def get_hex_color(layer_type): """ Determines the hex color for a layer. :parameters: - layer_type : string Class name of the layer :returns: - color : string containing a hex color for filling block. """ COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', '#3173A2', '#17649B', '#FFBB60', '#FFDAA9', '#FFC981', '#FCAC41', '#F29416', '#C54AAA', '#E698D4', '#D56CBE', '#B72F99', '#B0108D', '#75DF54', '#B3F1A0', '#91E875', '#5DD637', '#3FCD12'] hashed = int(hash(layer_type)) % 5 if "conv" in layer_type.lower(): return COLORS[:5][hashed] if layer_type in lasagne.layers.pool.__all__: return COLORS[5:10][hashed] if layer_type in lasagne.layers.recurrent.__all__: return COLORS[10:15][hashed] else: return COLORS[15:20][hashed]
python
def get_hex_color(layer_type): """ Determines the hex color for a layer. :parameters: - layer_type : string Class name of the layer :returns: - color : string containing a hex color for filling block. """ COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', '#3173A2', '#17649B', '#FFBB60', '#FFDAA9', '#FFC981', '#FCAC41', '#F29416', '#C54AAA', '#E698D4', '#D56CBE', '#B72F99', '#B0108D', '#75DF54', '#B3F1A0', '#91E875', '#5DD637', '#3FCD12'] hashed = int(hash(layer_type)) % 5 if "conv" in layer_type.lower(): return COLORS[:5][hashed] if layer_type in lasagne.layers.pool.__all__: return COLORS[5:10][hashed] if layer_type in lasagne.layers.recurrent.__all__: return COLORS[10:15][hashed] else: return COLORS[15:20][hashed]
Determines the hex color for a layer. :parameters: - layer_type : string Class name of the layer :returns: - color : string containing a hex color for filling block.
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L270-L293
dnouri/nolearn
nolearn/lasagne/visualize.py
make_pydot_graph
def make_pydot_graph(layers, output_shape=True, verbose=False): """ :parameters: - layers : list List of the layers, as obtained from lasagne.layers.get_all_layers - output_shape: (default `True`) If `True`, the output shape of each layer will be displayed. - verbose: (default `False`) If `True`, layer attributes like filter shape, stride, etc. will be displayed. :returns: - pydot_graph : PyDot object containing the graph """ import pydotplus as pydot pydot_graph = pydot.Dot('Network', graph_type='digraph') pydot_nodes = {} pydot_edges = [] for i, layer in enumerate(layers): layer_name = getattr(layer, 'name', None) if layer_name is None: layer_name = layer.__class__.__name__ layer_type = '{0}'.format(layer_name) key = repr(layer) label = layer_type color = get_hex_color(layer_type) if verbose: for attr in ['num_filters', 'num_units', 'ds', 'filter_shape', 'stride', 'strides', 'p']: if hasattr(layer, attr): label += '\n{0}: {1}'.format(attr, getattr(layer, attr)) if hasattr(layer, 'nonlinearity'): try: nonlinearity = layer.nonlinearity.__name__ except AttributeError: nonlinearity = layer.nonlinearity.__class__.__name__ label += '\nnonlinearity: {0}'.format(nonlinearity) if output_shape: label += '\nOutput shape: {0}'.format(layer.output_shape) pydot_nodes[key] = pydot.Node( key, label=label, shape='record', fillcolor=color, style='filled') if hasattr(layer, 'input_layers'): for input_layer in layer.input_layers: pydot_edges.append([repr(input_layer), key]) if hasattr(layer, 'input_layer'): pydot_edges.append([repr(layer.input_layer), key]) for node in pydot_nodes.values(): pydot_graph.add_node(node) for edges in pydot_edges: pydot_graph.add_edge( pydot.Edge(pydot_nodes[edges[0]], pydot_nodes[edges[1]])) return pydot_graph
python
def make_pydot_graph(layers, output_shape=True, verbose=False): """ :parameters: - layers : list List of the layers, as obtained from lasagne.layers.get_all_layers - output_shape: (default `True`) If `True`, the output shape of each layer will be displayed. - verbose: (default `False`) If `True`, layer attributes like filter shape, stride, etc. will be displayed. :returns: - pydot_graph : PyDot object containing the graph """ import pydotplus as pydot pydot_graph = pydot.Dot('Network', graph_type='digraph') pydot_nodes = {} pydot_edges = [] for i, layer in enumerate(layers): layer_name = getattr(layer, 'name', None) if layer_name is None: layer_name = layer.__class__.__name__ layer_type = '{0}'.format(layer_name) key = repr(layer) label = layer_type color = get_hex_color(layer_type) if verbose: for attr in ['num_filters', 'num_units', 'ds', 'filter_shape', 'stride', 'strides', 'p']: if hasattr(layer, attr): label += '\n{0}: {1}'.format(attr, getattr(layer, attr)) if hasattr(layer, 'nonlinearity'): try: nonlinearity = layer.nonlinearity.__name__ except AttributeError: nonlinearity = layer.nonlinearity.__class__.__name__ label += '\nnonlinearity: {0}'.format(nonlinearity) if output_shape: label += '\nOutput shape: {0}'.format(layer.output_shape) pydot_nodes[key] = pydot.Node( key, label=label, shape='record', fillcolor=color, style='filled') if hasattr(layer, 'input_layers'): for input_layer in layer.input_layers: pydot_edges.append([repr(input_layer), key]) if hasattr(layer, 'input_layer'): pydot_edges.append([repr(layer.input_layer), key]) for node in pydot_nodes.values(): pydot_graph.add_node(node) for edges in pydot_edges: pydot_graph.add_edge( pydot.Edge(pydot_nodes[edges[0]], pydot_nodes[edges[1]])) return pydot_graph
:parameters: - layers : list List of the layers, as obtained from lasagne.layers.get_all_layers - output_shape: (default `True`) If `True`, the output shape of each layer will be displayed. - verbose: (default `False`) If `True`, layer attributes like filter shape, stride, etc. will be displayed. :returns: - pydot_graph : PyDot object containing the graph
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L296-L352
dnouri/nolearn
nolearn/lasagne/visualize.py
draw_to_file
def draw_to_file(layers, filename, **kwargs): """ Draws a network diagram to a file :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - filename : string The filename to save output to - **kwargs: see docstring of make_pydot_graph for other options """ layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers) dot = make_pydot_graph(layers, **kwargs) ext = filename[filename.rfind('.') + 1:] with io.open(filename, 'wb') as fid: fid.write(dot.create(format=ext))
python
def draw_to_file(layers, filename, **kwargs): """ Draws a network diagram to a file :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - filename : string The filename to save output to - **kwargs: see docstring of make_pydot_graph for other options """ layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers) dot = make_pydot_graph(layers, **kwargs) ext = filename[filename.rfind('.') + 1:] with io.open(filename, 'wb') as fid: fid.write(dot.create(format=ext))
Draws a network diagram to a file :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - filename : string The filename to save output to - **kwargs: see docstring of make_pydot_graph for other options
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L355-L370
dnouri/nolearn
nolearn/lasagne/visualize.py
draw_to_notebook
def draw_to_notebook(layers, **kwargs): """ Draws a network diagram in an IPython notebook :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - **kwargs : see the docstring of make_pydot_graph for other options """ from IPython.display import Image layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers) dot = make_pydot_graph(layers, **kwargs) return Image(dot.create_png())
python
def draw_to_notebook(layers, **kwargs): """ Draws a network diagram in an IPython notebook :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - **kwargs : see the docstring of make_pydot_graph for other options """ from IPython.display import Image layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers) dot = make_pydot_graph(layers, **kwargs) return Image(dot.create_png())
Draws a network diagram in an IPython notebook :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - **kwargs : see the docstring of make_pydot_graph for other options
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L373-L385
dnouri/nolearn
nolearn/lasagne/util.py
get_real_filter
def get_real_filter(layers, img_size): """Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks. """ real_filter = np.zeros((len(layers), 2)) conv_mode = True first_conv_layer = True expon = np.ones((1, 2)) for i, layer in enumerate(layers[1:]): j = i + 1 if not conv_mode: real_filter[j] = img_size continue if is_conv2d(layer): if not first_conv_layer: new_filter = np.array(layer.filter_size) * expon real_filter[j] = new_filter else: new_filter = np.array(layer.filter_size) * expon real_filter[j] = new_filter first_conv_layer = False elif is_maxpool2d(layer): real_filter[j] = real_filter[i] expon *= np.array(layer.pool_size) else: conv_mode = False real_filter[j] = img_size real_filter[0] = img_size return real_filter
python
def get_real_filter(layers, img_size): """Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks. """ real_filter = np.zeros((len(layers), 2)) conv_mode = True first_conv_layer = True expon = np.ones((1, 2)) for i, layer in enumerate(layers[1:]): j = i + 1 if not conv_mode: real_filter[j] = img_size continue if is_conv2d(layer): if not first_conv_layer: new_filter = np.array(layer.filter_size) * expon real_filter[j] = new_filter else: new_filter = np.array(layer.filter_size) * expon real_filter[j] = new_filter first_conv_layer = False elif is_maxpool2d(layer): real_filter[j] = real_filter[i] expon *= np.array(layer.pool_size) else: conv_mode = False real_filter[j] = img_size real_filter[0] = img_size return real_filter
Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks.
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/util.py#L57-L91
dnouri/nolearn
nolearn/lasagne/util.py
get_receptive_field
def get_receptive_field(layers, img_size): """Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks. """ receptive_field = np.zeros((len(layers), 2)) conv_mode = True first_conv_layer = True expon = np.ones((1, 2)) for i, layer in enumerate(layers[1:]): j = i + 1 if not conv_mode: receptive_field[j] = img_size continue if is_conv2d(layer): if not first_conv_layer: last_field = receptive_field[i] new_field = (last_field + expon * (np.array(layer.filter_size) - 1)) receptive_field[j] = new_field else: receptive_field[j] = layer.filter_size first_conv_layer = False elif is_maxpool2d(layer): receptive_field[j] = receptive_field[i] expon *= np.array(layer.pool_size) else: conv_mode = False receptive_field[j] = img_size receptive_field[0] = img_size return receptive_field
python
def get_receptive_field(layers, img_size): """Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks. """ receptive_field = np.zeros((len(layers), 2)) conv_mode = True first_conv_layer = True expon = np.ones((1, 2)) for i, layer in enumerate(layers[1:]): j = i + 1 if not conv_mode: receptive_field[j] = img_size continue if is_conv2d(layer): if not first_conv_layer: last_field = receptive_field[i] new_field = (last_field + expon * (np.array(layer.filter_size) - 1)) receptive_field[j] = new_field else: receptive_field[j] = layer.filter_size first_conv_layer = False elif is_maxpool2d(layer): receptive_field[j] = receptive_field[i] expon *= np.array(layer.pool_size) else: conv_mode = False receptive_field[j] = img_size receptive_field[0] = img_size return receptive_field
Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks.
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/util.py#L94-L129
dnouri/nolearn
nolearn/decaf.py
ConvNetFeatures.prepare_image
def prepare_image(self, image): """Returns image of shape `(256, 256, 3)`, as expected by `transform` when `classify_direct = True`. """ from decaf.util import transform # soft dep _JEFFNET_FLIP = True # first, extract the 256x256 center. image = transform.scale_and_extract(transform.as_rgb(image), 256) # convert to [0,255] float32 image = image.astype(np.float32) * 255. if _JEFFNET_FLIP: # Flip the image if necessary, maintaining the c_contiguous order image = image[::-1, :].copy() # subtract the mean image -= self.net_._data_mean return image
python
def prepare_image(self, image): """Returns image of shape `(256, 256, 3)`, as expected by `transform` when `classify_direct = True`. """ from decaf.util import transform # soft dep _JEFFNET_FLIP = True # first, extract the 256x256 center. image = transform.scale_and_extract(transform.as_rgb(image), 256) # convert to [0,255] float32 image = image.astype(np.float32) * 255. if _JEFFNET_FLIP: # Flip the image if necessary, maintaining the c_contiguous order image = image[::-1, :].copy() # subtract the mean image -= self.net_._data_mean return image
Returns image of shape `(256, 256, 3)`, as expected by `transform` when `classify_direct = True`.
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/decaf.py#L138-L154
dnouri/nolearn
nolearn/metrics.py
multiclass_logloss
def multiclass_logloss(actual, predicted, eps=1e-15): """Multi class version of Logarithmic Loss metric. :param actual: Array containing the actual target classes :param predicted: Matrix with class predictions, one probability per class """ # Convert 'actual' to a binary array if it's not already: if len(actual.shape) == 1: actual2 = np.zeros((actual.shape[0], predicted.shape[1])) for i, val in enumerate(actual): actual2[i, val] = 1 actual = actual2 clip = np.clip(predicted, eps, 1 - eps) rows = actual.shape[0] vsota = np.sum(actual * np.log(clip)) return -1.0 / rows * vsota
python
def multiclass_logloss(actual, predicted, eps=1e-15): """Multi class version of Logarithmic Loss metric. :param actual: Array containing the actual target classes :param predicted: Matrix with class predictions, one probability per class """ # Convert 'actual' to a binary array if it's not already: if len(actual.shape) == 1: actual2 = np.zeros((actual.shape[0], predicted.shape[1])) for i, val in enumerate(actual): actual2[i, val] = 1 actual = actual2 clip = np.clip(predicted, eps, 1 - eps) rows = actual.shape[0] vsota = np.sum(actual * np.log(clip)) return -1.0 / rows * vsota
Multi class version of Logarithmic Loss metric. :param actual: Array containing the actual target classes :param predicted: Matrix with class predictions, one probability per class
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/metrics.py#L8-L24
dnouri/nolearn
nolearn/lasagne/base.py
objective
def objective(layers, loss_function, target, aggregate=aggregate, deterministic=False, l1=0, l2=0, get_output_kw=None): """ Default implementation of the NeuralNet objective. :param layers: The underlying layers of the NeuralNetwork :param loss_function: The callable loss function to use :param target: the expected output :param aggregate: the aggregation function to use :param deterministic: Whether or not to get a deterministic output :param l1: Optional l1 regularization parameter :param l2: Optional l2 regularization parameter :param get_output_kw: optional kwargs to pass to :meth:`NeuralNetwork.get_output` :return: The total calculated loss """ if get_output_kw is None: get_output_kw = {} output_layer = layers[-1] network_output = get_output( output_layer, deterministic=deterministic, **get_output_kw) loss = aggregate(loss_function(network_output, target)) if l1: loss += regularization.regularize_layer_params( layers.values(), regularization.l1) * l1 if l2: loss += regularization.regularize_layer_params( layers.values(), regularization.l2) * l2 return loss
python
def objective(layers, loss_function, target, aggregate=aggregate, deterministic=False, l1=0, l2=0, get_output_kw=None): """ Default implementation of the NeuralNet objective. :param layers: The underlying layers of the NeuralNetwork :param loss_function: The callable loss function to use :param target: the expected output :param aggregate: the aggregation function to use :param deterministic: Whether or not to get a deterministic output :param l1: Optional l1 regularization parameter :param l2: Optional l2 regularization parameter :param get_output_kw: optional kwargs to pass to :meth:`NeuralNetwork.get_output` :return: The total calculated loss """ if get_output_kw is None: get_output_kw = {} output_layer = layers[-1] network_output = get_output( output_layer, deterministic=deterministic, **get_output_kw) loss = aggregate(loss_function(network_output, target)) if l1: loss += regularization.regularize_layer_params( layers.values(), regularization.l1) * l1 if l2: loss += regularization.regularize_layer_params( layers.values(), regularization.l2) * l2 return loss
Default implementation of the NeuralNet objective. :param layers: The underlying layers of the NeuralNetwork :param loss_function: The callable loss function to use :param target: the expected output :param aggregate: the aggregation function to use :param deterministic: Whether or not to get a deterministic output :param l1: Optional l1 regularization parameter :param l2: Optional l2 regularization parameter :param get_output_kw: optional kwargs to pass to :meth:`NeuralNetwork.get_output` :return: The total calculated loss
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L166-L202
dnouri/nolearn
nolearn/lasagne/base.py
NeuralNet.initialize
def initialize(self): """Initializes the network. Checks that no extra kwargs were passed to the constructor, and compiles the train, predict, and evaluation functions. Subsequent calls to this function will return without any action. """ if getattr(self, '_initialized', False): return out = getattr(self, '_output_layers', None) if out is None: self.initialize_layers() self._check_for_unused_kwargs() iter_funcs = self._create_iter_funcs( self.layers_, self.objective, self.update, self.y_tensor_type, ) self.train_iter_, self.eval_iter_, self.predict_iter_ = iter_funcs self._initialized = True
python
def initialize(self): """Initializes the network. Checks that no extra kwargs were passed to the constructor, and compiles the train, predict, and evaluation functions. Subsequent calls to this function will return without any action. """ if getattr(self, '_initialized', False): return out = getattr(self, '_output_layers', None) if out is None: self.initialize_layers() self._check_for_unused_kwargs() iter_funcs = self._create_iter_funcs( self.layers_, self.objective, self.update, self.y_tensor_type, ) self.train_iter_, self.eval_iter_, self.predict_iter_ = iter_funcs self._initialized = True
Initializes the network. Checks that no extra kwargs were passed to the constructor, and compiles the train, predict, and evaluation functions. Subsequent calls to this function will return without any action.
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L473-L493
dnouri/nolearn
nolearn/lasagne/base.py
NeuralNet.initialize_layers
def initialize_layers(self, layers=None): """Sets up the Lasagne layers :param layers: The dictionary of layers, or a :class:`lasagne.Layers` instance, describing the underlying network :return: the output layer of the underlying lasagne network. :seealso: :ref:`layer-def` """ if layers is not None: self.layers = layers self.layers_ = Layers() #If a Layer, or a list of Layers was passed in if isinstance(self.layers[0], Layer): for out_layer in self.layers: for i, layer in enumerate(get_all_layers(out_layer)): if layer not in self.layers_.values(): name = layer.name or self._layer_name(layer.__class__, i) self.layers_[name] = layer if self._get_params_for(name) != {}: raise ValueError( "You can't use keyword params when passing a Lasagne " "instance object as the 'layers' parameter of " "'NeuralNet'." ) self._output_layers = self.layers return self.layers # 'self.layers' are a list of '(Layer class, kwargs)', so # we'll have to actually instantiate the layers given the # arguments: layer = None for i, layer_def in enumerate(self.layers): if isinstance(layer_def[1], dict): # Newer format: (Layer, {'layer': 'kwargs'}) layer_factory, layer_kw = layer_def layer_kw = layer_kw.copy() else: # The legacy format: ('name', Layer) layer_name, layer_factory = layer_def layer_kw = {'name': layer_name} if isinstance(layer_factory, str): layer_factory = locate(layer_factory) assert layer_factory is not None if 'name' not in layer_kw: layer_kw['name'] = self._layer_name(layer_factory, i) more_params = self._get_params_for(layer_kw['name']) layer_kw.update(more_params) if layer_kw['name'] in self.layers_: raise ValueError( "Two layers with name {}.".format(layer_kw['name'])) # Any layers that aren't subclasses of InputLayer are # assumed to require an 'incoming' paramter. By default, # we'll use the previous layer as input: try: is_input_layer = issubclass(layer_factory, InputLayer) except TypeError: is_input_layer = False if not is_input_layer: if 'incoming' in layer_kw: layer_kw['incoming'] = self.layers_[ layer_kw['incoming']] elif 'incomings' in layer_kw: layer_kw['incomings'] = [ self.layers_[name] for name in layer_kw['incomings']] else: layer_kw['incoming'] = layer # Deal with additional string parameters that may # reference other layers; currently only 'mask_input'. for param in self.layer_reference_params: if param in layer_kw: val = layer_kw[param] if isinstance(val, basestring): layer_kw[param] = self.layers_[val] for attr in ('W', 'b'): if isinstance(layer_kw.get(attr), str): name = layer_kw[attr] layer_kw[attr] = getattr(self.layers_[name], attr, None) try: layer_wrapper = layer_kw.pop('layer_wrapper', None) layer = layer_factory(**layer_kw) except TypeError as e: msg = ("Failed to instantiate {} with args {}.\n" "Maybe parameter names have changed?".format( layer_factory, layer_kw)) chain_exception(TypeError(msg), e) self.layers_[layer_kw['name']] = layer if layer_wrapper is not None: layer = layer_wrapper(layer) self.layers_["LW_%s" % layer_kw['name']] = layer self._output_layers = [layer] return [layer]
python
def initialize_layers(self, layers=None): """Sets up the Lasagne layers :param layers: The dictionary of layers, or a :class:`lasagne.Layers` instance, describing the underlying network :return: the output layer of the underlying lasagne network. :seealso: :ref:`layer-def` """ if layers is not None: self.layers = layers self.layers_ = Layers() #If a Layer, or a list of Layers was passed in if isinstance(self.layers[0], Layer): for out_layer in self.layers: for i, layer in enumerate(get_all_layers(out_layer)): if layer not in self.layers_.values(): name = layer.name or self._layer_name(layer.__class__, i) self.layers_[name] = layer if self._get_params_for(name) != {}: raise ValueError( "You can't use keyword params when passing a Lasagne " "instance object as the 'layers' parameter of " "'NeuralNet'." ) self._output_layers = self.layers return self.layers # 'self.layers' are a list of '(Layer class, kwargs)', so # we'll have to actually instantiate the layers given the # arguments: layer = None for i, layer_def in enumerate(self.layers): if isinstance(layer_def[1], dict): # Newer format: (Layer, {'layer': 'kwargs'}) layer_factory, layer_kw = layer_def layer_kw = layer_kw.copy() else: # The legacy format: ('name', Layer) layer_name, layer_factory = layer_def layer_kw = {'name': layer_name} if isinstance(layer_factory, str): layer_factory = locate(layer_factory) assert layer_factory is not None if 'name' not in layer_kw: layer_kw['name'] = self._layer_name(layer_factory, i) more_params = self._get_params_for(layer_kw['name']) layer_kw.update(more_params) if layer_kw['name'] in self.layers_: raise ValueError( "Two layers with name {}.".format(layer_kw['name'])) # Any layers that aren't subclasses of InputLayer are # assumed to require an 'incoming' paramter. By default, # we'll use the previous layer as input: try: is_input_layer = issubclass(layer_factory, InputLayer) except TypeError: is_input_layer = False if not is_input_layer: if 'incoming' in layer_kw: layer_kw['incoming'] = self.layers_[ layer_kw['incoming']] elif 'incomings' in layer_kw: layer_kw['incomings'] = [ self.layers_[name] for name in layer_kw['incomings']] else: layer_kw['incoming'] = layer # Deal with additional string parameters that may # reference other layers; currently only 'mask_input'. for param in self.layer_reference_params: if param in layer_kw: val = layer_kw[param] if isinstance(val, basestring): layer_kw[param] = self.layers_[val] for attr in ('W', 'b'): if isinstance(layer_kw.get(attr), str): name = layer_kw[attr] layer_kw[attr] = getattr(self.layers_[name], attr, None) try: layer_wrapper = layer_kw.pop('layer_wrapper', None) layer = layer_factory(**layer_kw) except TypeError as e: msg = ("Failed to instantiate {} with args {}.\n" "Maybe parameter names have changed?".format( layer_factory, layer_kw)) chain_exception(TypeError(msg), e) self.layers_[layer_kw['name']] = layer if layer_wrapper is not None: layer = layer_wrapper(layer) self.layers_["LW_%s" % layer_kw['name']] = layer self._output_layers = [layer] return [layer]
Sets up the Lasagne layers :param layers: The dictionary of layers, or a :class:`lasagne.Layers` instance, describing the underlying network :return: the output layer of the underlying lasagne network. :seealso: :ref:`layer-def`
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L512-L616
dnouri/nolearn
nolearn/lasagne/base.py
NeuralNet.fit
def fit(self, X, y, epochs=None): """ Runs the training loop for a given number of epochs :param X: The input data :param y: The ground truth :param epochs: The number of epochs to run, if `None` runs for the network's :attr:`max_epochs` :return: This instance """ if self.check_input: X, y = self._check_good_input(X, y) if self.use_label_encoder: self.enc_ = LabelEncoder() y = self.enc_.fit_transform(y).astype(np.int32) self.classes_ = self.enc_.classes_ self.initialize() try: self.train_loop(X, y, epochs=epochs) except KeyboardInterrupt: pass return self
python
def fit(self, X, y, epochs=None): """ Runs the training loop for a given number of epochs :param X: The input data :param y: The ground truth :param epochs: The number of epochs to run, if `None` runs for the network's :attr:`max_epochs` :return: This instance """ if self.check_input: X, y = self._check_good_input(X, y) if self.use_label_encoder: self.enc_ = LabelEncoder() y = self.enc_.fit_transform(y).astype(np.int32) self.classes_ = self.enc_.classes_ self.initialize() try: self.train_loop(X, y, epochs=epochs) except KeyboardInterrupt: pass return self
Runs the training loop for a given number of epochs :param X: The input data :param y: The ground truth :param epochs: The number of epochs to run, if `None` runs for the network's :attr:`max_epochs` :return: This instance
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L680-L703
dnouri/nolearn
nolearn/lasagne/base.py
NeuralNet.partial_fit
def partial_fit(self, X, y, classes=None): """ Runs a single epoch using the provided data :return: This instance """ return self.fit(X, y, epochs=1)
python
def partial_fit(self, X, y, classes=None): """ Runs a single epoch using the provided data :return: This instance """ return self.fit(X, y, epochs=1)
Runs a single epoch using the provided data :return: This instance
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L705-L711
pennersr/django-trackstats
trackstats/models.py
RegisterLazilyManagerMixin._register
def _register(self, defaults=None, **kwargs): """Fetch (update or create) an instance, lazily. We're doing this lazily, so that it becomes possible to define custom enums in your code, even before the Django ORM is fully initialized. Domain.objects.SHOPPING = Domain.objects.register( ref='shopping', name='Webshop') Domain.objects.USERS = Domain.objects.register( ref='users', name='User Accounts') """ f = lambda: self.update_or_create(defaults=defaults, **kwargs)[0] ret = SimpleLazyObject(f) self._lazy_entries.append(ret) return ret
python
def _register(self, defaults=None, **kwargs): """Fetch (update or create) an instance, lazily. We're doing this lazily, so that it becomes possible to define custom enums in your code, even before the Django ORM is fully initialized. Domain.objects.SHOPPING = Domain.objects.register( ref='shopping', name='Webshop') Domain.objects.USERS = Domain.objects.register( ref='users', name='User Accounts') """ f = lambda: self.update_or_create(defaults=defaults, **kwargs)[0] ret = SimpleLazyObject(f) self._lazy_entries.append(ret) return ret
Fetch (update or create) an instance, lazily. We're doing this lazily, so that it becomes possible to define custom enums in your code, even before the Django ORM is fully initialized. Domain.objects.SHOPPING = Domain.objects.register( ref='shopping', name='Webshop') Domain.objects.USERS = Domain.objects.register( ref='users', name='User Accounts')
https://github.com/pennersr/django-trackstats/blob/4c36e769cb02017675a86de405afcd4e10ed3356/trackstats/models.py#L28-L45
pennersr/django-trackstats
trackstats/models.py
ByDateQuerySetMixin.narrow
def narrow(self, **kwargs): """Up-to including""" from_date = kwargs.pop('from_date', None) to_date = kwargs.pop('to_date', None) date = kwargs.pop('date', None) qs = self if from_date: qs = qs.filter(date__gte=from_date) if to_date: qs = qs.filter(date__lte=to_date) if date: qs = qs.filter(date=date) return super(ByDateQuerySetMixin, qs).narrow(**kwargs)
python
def narrow(self, **kwargs): """Up-to including""" from_date = kwargs.pop('from_date', None) to_date = kwargs.pop('to_date', None) date = kwargs.pop('date', None) qs = self if from_date: qs = qs.filter(date__gte=from_date) if to_date: qs = qs.filter(date__lte=to_date) if date: qs = qs.filter(date=date) return super(ByDateQuerySetMixin, qs).narrow(**kwargs)
Up-to including
https://github.com/pennersr/django-trackstats/blob/4c36e769cb02017675a86de405afcd4e10ed3356/trackstats/models.py#L230-L242
HDE/python-lambda-local
lambda_local/environment_variables.py
set_environment_variables
def set_environment_variables(json_file_path): """ Read and set environment variables from a flat json file. Bear in mind that env vars set this way and later on read using `os.getenv` function will be strings since after all env vars are just that - plain strings. Json file example: ``` { "FOO": "bar", "BAZ": true } ``` :param json_file_path: path to flat json file :type json_file_path: str """ if json_file_path: with open(json_file_path) as json_file: env_vars = json.loads(json_file.read()) export_variables(env_vars)
python
def set_environment_variables(json_file_path): """ Read and set environment variables from a flat json file. Bear in mind that env vars set this way and later on read using `os.getenv` function will be strings since after all env vars are just that - plain strings. Json file example: ``` { "FOO": "bar", "BAZ": true } ``` :param json_file_path: path to flat json file :type json_file_path: str """ if json_file_path: with open(json_file_path) as json_file: env_vars = json.loads(json_file.read()) export_variables(env_vars)
Read and set environment variables from a flat json file. Bear in mind that env vars set this way and later on read using `os.getenv` function will be strings since after all env vars are just that - plain strings. Json file example: ``` { "FOO": "bar", "BAZ": true } ``` :param json_file_path: path to flat json file :type json_file_path: str
https://github.com/HDE/python-lambda-local/blob/49ad011a039974f1d8f904435eb8db895558d2d9/lambda_local/environment_variables.py#L10-L33
HDE/python-lambda-local
lambda_local/context.py
millis_interval
def millis_interval(start, end): """start and end are datetime instances""" diff = end - start millis = diff.days * 24 * 60 * 60 * 1000 millis += diff.seconds * 1000 millis += diff.microseconds / 1000 return millis
python
def millis_interval(start, end): """start and end are datetime instances""" diff = end - start millis = diff.days * 24 * 60 * 60 * 1000 millis += diff.seconds * 1000 millis += diff.microseconds / 1000 return millis
start and end are datetime instances
https://github.com/HDE/python-lambda-local/blob/49ad011a039974f1d8f904435eb8db895558d2d9/lambda_local/context.py#L49-L55
locationlabs/mockredis
mockredis/script.py
Script._execute_lua
def _execute_lua(self, keys, args, client): """ Sets KEYS and ARGV alongwith redis.call() function in lua globals and executes the lua redis script """ lua, lua_globals = Script._import_lua(self.load_dependencies) lua_globals.KEYS = self._python_to_lua(keys) lua_globals.ARGV = self._python_to_lua(args) def _call(*call_args): # redis-py and native redis commands are mostly compatible argument # wise, but some exceptions need to be handled here: if str(call_args[0]).lower() == 'lrem': response = client.call( call_args[0], call_args[1], call_args[3], # "count", default is 0 call_args[2]) else: response = client.call(*call_args) return self._python_to_lua(response) lua_globals.redis = {"call": _call} return self._lua_to_python(lua.execute(self.script), return_status=True)
python
def _execute_lua(self, keys, args, client): """ Sets KEYS and ARGV alongwith redis.call() function in lua globals and executes the lua redis script """ lua, lua_globals = Script._import_lua(self.load_dependencies) lua_globals.KEYS = self._python_to_lua(keys) lua_globals.ARGV = self._python_to_lua(args) def _call(*call_args): # redis-py and native redis commands are mostly compatible argument # wise, but some exceptions need to be handled here: if str(call_args[0]).lower() == 'lrem': response = client.call( call_args[0], call_args[1], call_args[3], # "count", default is 0 call_args[2]) else: response = client.call(*call_args) return self._python_to_lua(response) lua_globals.redis = {"call": _call} return self._lua_to_python(lua.execute(self.script), return_status=True)
Sets KEYS and ARGV alongwith redis.call() function in lua globals and executes the lua redis script
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L29-L51
locationlabs/mockredis
mockredis/script.py
Script._import_lua
def _import_lua(load_dependencies=True): """ Import lua and dependencies. :param load_dependencies: should Lua library dependencies be loaded? :raises: RuntimeError if Lua is not available """ try: import lua except ImportError: raise RuntimeError("Lua not installed") lua_globals = lua.globals() if load_dependencies: Script._import_lua_dependencies(lua, lua_globals) return lua, lua_globals
python
def _import_lua(load_dependencies=True): """ Import lua and dependencies. :param load_dependencies: should Lua library dependencies be loaded? :raises: RuntimeError if Lua is not available """ try: import lua except ImportError: raise RuntimeError("Lua not installed") lua_globals = lua.globals() if load_dependencies: Script._import_lua_dependencies(lua, lua_globals) return lua, lua_globals
Import lua and dependencies. :param load_dependencies: should Lua library dependencies be loaded? :raises: RuntimeError if Lua is not available
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L54-L69
locationlabs/mockredis
mockredis/script.py
Script._import_lua_dependencies
def _import_lua_dependencies(lua, lua_globals): """ Imports lua dependencies that are supported by redis lua scripts. The current implementation is fragile to the target platform and lua version and may be disabled if these imports are not needed. Included: - cjson lib. Pending: - base lib. - table lib. - string lib. - math lib. - debug lib. - cmsgpack lib. """ if sys.platform not in ('darwin', 'windows'): import ctypes ctypes.CDLL('liblua5.2.so', mode=ctypes.RTLD_GLOBAL) try: lua_globals.cjson = lua.eval('require "cjson"') except RuntimeError: raise RuntimeError("cjson not installed")
python
def _import_lua_dependencies(lua, lua_globals): """ Imports lua dependencies that are supported by redis lua scripts. The current implementation is fragile to the target platform and lua version and may be disabled if these imports are not needed. Included: - cjson lib. Pending: - base lib. - table lib. - string lib. - math lib. - debug lib. - cmsgpack lib. """ if sys.platform not in ('darwin', 'windows'): import ctypes ctypes.CDLL('liblua5.2.so', mode=ctypes.RTLD_GLOBAL) try: lua_globals.cjson = lua.eval('require "cjson"') except RuntimeError: raise RuntimeError("cjson not installed")
Imports lua dependencies that are supported by redis lua scripts. The current implementation is fragile to the target platform and lua version and may be disabled if these imports are not needed. Included: - cjson lib. Pending: - base lib. - table lib. - string lib. - math lib. - debug lib. - cmsgpack lib.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L72-L96
locationlabs/mockredis
mockredis/script.py
Script._lua_to_python
def _lua_to_python(lval, return_status=False): """ Convert Lua object(s) into Python object(s), as at times Lua object(s) are not compatible with Python functions """ import lua lua_globals = lua.globals() if lval is None: # Lua None --> Python None return None if lua_globals.type(lval) == "table": # Lua table --> Python list pval = [] for i in lval: if return_status: if i == 'ok': return lval[i] if i == 'err': raise ResponseError(lval[i]) pval.append(Script._lua_to_python(lval[i])) return pval elif isinstance(lval, long): # Lua number --> Python long return long(lval) elif isinstance(lval, float): # Lua number --> Python float return float(lval) elif lua_globals.type(lval) == "userdata": # Lua userdata --> Python string return str(lval) elif lua_globals.type(lval) == "string": # Lua string --> Python string return lval elif lua_globals.type(lval) == "boolean": # Lua boolean --> Python bool return bool(lval) raise RuntimeError("Invalid Lua type: " + str(lua_globals.type(lval)))
python
def _lua_to_python(lval, return_status=False): """ Convert Lua object(s) into Python object(s), as at times Lua object(s) are not compatible with Python functions """ import lua lua_globals = lua.globals() if lval is None: # Lua None --> Python None return None if lua_globals.type(lval) == "table": # Lua table --> Python list pval = [] for i in lval: if return_status: if i == 'ok': return lval[i] if i == 'err': raise ResponseError(lval[i]) pval.append(Script._lua_to_python(lval[i])) return pval elif isinstance(lval, long): # Lua number --> Python long return long(lval) elif isinstance(lval, float): # Lua number --> Python float return float(lval) elif lua_globals.type(lval) == "userdata": # Lua userdata --> Python string return str(lval) elif lua_globals.type(lval) == "string": # Lua string --> Python string return lval elif lua_globals.type(lval) == "boolean": # Lua boolean --> Python bool return bool(lval) raise RuntimeError("Invalid Lua type: " + str(lua_globals.type(lval)))
Convert Lua object(s) into Python object(s), as at times Lua object(s) are not compatible with Python functions
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L99-L135
locationlabs/mockredis
mockredis/script.py
Script._python_to_lua
def _python_to_lua(pval): """ Convert Python object(s) into Lua object(s), as at times Python object(s) are not compatible with Lua functions """ import lua if pval is None: # Python None --> Lua None return lua.eval("") if isinstance(pval, (list, tuple, set)): # Python list --> Lua table # e.g.: in lrange # in Python returns: [v1, v2, v3] # in Lua returns: {v1, v2, v3} lua_list = lua.eval("{}") lua_table = lua.eval("table") for item in pval: lua_table.insert(lua_list, Script._python_to_lua(item)) return lua_list elif isinstance(pval, dict): # Python dict --> Lua dict # e.g.: in hgetall # in Python returns: {k1:v1, k2:v2, k3:v3} # in Lua returns: {k1, v1, k2, v2, k3, v3} lua_dict = lua.eval("{}") lua_table = lua.eval("table") for k, v in pval.iteritems(): lua_table.insert(lua_dict, Script._python_to_lua(k)) lua_table.insert(lua_dict, Script._python_to_lua(v)) return lua_dict elif isinstance(pval, str): # Python string --> Lua userdata return pval elif isinstance(pval, bool): # Python bool--> Lua boolean return lua.eval(str(pval).lower()) elif isinstance(pval, (int, long, float)): # Python int --> Lua number lua_globals = lua.globals() return lua_globals.tonumber(str(pval)) raise RuntimeError("Invalid Python type: " + str(type(pval)))
python
def _python_to_lua(pval): """ Convert Python object(s) into Lua object(s), as at times Python object(s) are not compatible with Lua functions """ import lua if pval is None: # Python None --> Lua None return lua.eval("") if isinstance(pval, (list, tuple, set)): # Python list --> Lua table # e.g.: in lrange # in Python returns: [v1, v2, v3] # in Lua returns: {v1, v2, v3} lua_list = lua.eval("{}") lua_table = lua.eval("table") for item in pval: lua_table.insert(lua_list, Script._python_to_lua(item)) return lua_list elif isinstance(pval, dict): # Python dict --> Lua dict # e.g.: in hgetall # in Python returns: {k1:v1, k2:v2, k3:v3} # in Lua returns: {k1, v1, k2, v2, k3, v3} lua_dict = lua.eval("{}") lua_table = lua.eval("table") for k, v in pval.iteritems(): lua_table.insert(lua_dict, Script._python_to_lua(k)) lua_table.insert(lua_dict, Script._python_to_lua(v)) return lua_dict elif isinstance(pval, str): # Python string --> Lua userdata return pval elif isinstance(pval, bool): # Python bool--> Lua boolean return lua.eval(str(pval).lower()) elif isinstance(pval, (int, long, float)): # Python int --> Lua number lua_globals = lua.globals() return lua_globals.tonumber(str(pval)) raise RuntimeError("Invalid Python type: " + str(type(pval)))
Convert Python object(s) into Lua object(s), as at times Python object(s) are not compatible with Lua functions
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L138-L179
locationlabs/mockredis
mockredis/client.py
MockRedis.lock
def lock(self, key, timeout=0, sleep=0): """Emulate lock.""" return MockRedisLock(self, key, timeout, sleep)
python
def lock(self, key, timeout=0, sleep=0): """Emulate lock.""" return MockRedisLock(self, key, timeout, sleep)
Emulate lock.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L77-L79
locationlabs/mockredis
mockredis/client.py
MockRedis.keys
def keys(self, pattern='*'): """Emulate keys.""" # making sure the pattern is unicode/str. try: pattern = pattern.decode('utf-8') # This throws an AttributeError in python 3, or an # UnicodeEncodeError in python 2 except (AttributeError, UnicodeEncodeError): pass # Make regex out of glob styled pattern. regex = fnmatch.translate(pattern) regex = re.compile(re.sub(r'(^|[^\\])\.', r'\1[^/]', regex)) # Find every key that matches the pattern return [key for key in self.redis.keys() if regex.match(key.decode('utf-8'))]
python
def keys(self, pattern='*'): """Emulate keys.""" # making sure the pattern is unicode/str. try: pattern = pattern.decode('utf-8') # This throws an AttributeError in python 3, or an # UnicodeEncodeError in python 2 except (AttributeError, UnicodeEncodeError): pass # Make regex out of glob styled pattern. regex = fnmatch.translate(pattern) regex = re.compile(re.sub(r'(^|[^\\])\.', r'\1[^/]', regex)) # Find every key that matches the pattern return [key for key in self.redis.keys() if regex.match(key.decode('utf-8'))]
Emulate keys.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L154-L169
locationlabs/mockredis
mockredis/client.py
MockRedis.delete
def delete(self, *keys): """Emulate delete.""" key_counter = 0 for key in map(self._encode, keys): if key in self.redis: del self.redis[key] key_counter += 1 if key in self.timeouts: del self.timeouts[key] return key_counter
python
def delete(self, *keys): """Emulate delete.""" key_counter = 0 for key in map(self._encode, keys): if key in self.redis: del self.redis[key] key_counter += 1 if key in self.timeouts: del self.timeouts[key] return key_counter
Emulate delete.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L171-L180
locationlabs/mockredis
mockredis/client.py
MockRedis.expire
def expire(self, key, delta): """Emulate expire""" delta = delta if isinstance(delta, timedelta) else timedelta(seconds=delta) return self._expire(self._encode(key), delta)
python
def expire(self, key, delta): """Emulate expire""" delta = delta if isinstance(delta, timedelta) else timedelta(seconds=delta) return self._expire(self._encode(key), delta)
Emulate expire
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L199-L202
locationlabs/mockredis
mockredis/client.py
MockRedis.pexpire
def pexpire(self, key, milliseconds): """Emulate pexpire""" return self._expire(self._encode(key), timedelta(milliseconds=milliseconds))
python
def pexpire(self, key, milliseconds): """Emulate pexpire""" return self._expire(self._encode(key), timedelta(milliseconds=milliseconds))
Emulate pexpire
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L204-L206
locationlabs/mockredis
mockredis/client.py
MockRedis.expireat
def expireat(self, key, when): """Emulate expireat""" expire_time = datetime.fromtimestamp(when) key = self._encode(key) if key in self.redis: self.timeouts[key] = expire_time return True return False
python
def expireat(self, key, when): """Emulate expireat""" expire_time = datetime.fromtimestamp(when) key = self._encode(key) if key in self.redis: self.timeouts[key] = expire_time return True return False
Emulate expireat
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L208-L215
locationlabs/mockredis
mockredis/client.py
MockRedis.ttl
def ttl(self, key): """ Emulate ttl Even though the official redis commands documentation at http://redis.io/commands/ttl states "Return value: Integer reply: TTL in seconds, -2 when key does not exist or -1 when key does not have a timeout." the redis-py lib returns None for both these cases. The lib behavior has been emulated here. :param key: key for which ttl is requested. :returns: the number of seconds till timeout, None if the key does not exist or if the key has no timeout(as per the redis-py lib behavior). """ value = self.pttl(key) if value is None or value < 0: return value return value // 1000
python
def ttl(self, key): """ Emulate ttl Even though the official redis commands documentation at http://redis.io/commands/ttl states "Return value: Integer reply: TTL in seconds, -2 when key does not exist or -1 when key does not have a timeout." the redis-py lib returns None for both these cases. The lib behavior has been emulated here. :param key: key for which ttl is requested. :returns: the number of seconds till timeout, None if the key does not exist or if the key has no timeout(as per the redis-py lib behavior). """ value = self.pttl(key) if value is None or value < 0: return value return value // 1000
Emulate ttl Even though the official redis commands documentation at http://redis.io/commands/ttl states "Return value: Integer reply: TTL in seconds, -2 when key does not exist or -1 when key does not have a timeout." the redis-py lib returns None for both these cases. The lib behavior has been emulated here. :param key: key for which ttl is requested. :returns: the number of seconds till timeout, None if the key does not exist or if the key has no timeout(as per the redis-py lib behavior).
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L217-L233
locationlabs/mockredis
mockredis/client.py
MockRedis.pttl
def pttl(self, key): """ Emulate pttl :param key: key for which pttl is requested. :returns: the number of milliseconds till timeout, None if the key does not exist or if the key has no timeout(as per the redis-py lib behavior). """ """ Returns time to live in milliseconds if output_ms is True, else returns seconds. """ key = self._encode(key) if key not in self.redis: # as of redis 2.8, -2 is returned if the key does not exist return long(-2) if self.strict else None if key not in self.timeouts: # as of redis 2.8, -1 is returned if the key is persistent # redis-py returns None; command docs say -1 return long(-1) if self.strict else None time_to_live = get_total_milliseconds(self.timeouts[key] - self.clock.now()) return long(max(-1, time_to_live))
python
def pttl(self, key): """ Emulate pttl :param key: key for which pttl is requested. :returns: the number of milliseconds till timeout, None if the key does not exist or if the key has no timeout(as per the redis-py lib behavior). """ """ Returns time to live in milliseconds if output_ms is True, else returns seconds. """ key = self._encode(key) if key not in self.redis: # as of redis 2.8, -2 is returned if the key does not exist return long(-2) if self.strict else None if key not in self.timeouts: # as of redis 2.8, -1 is returned if the key is persistent # redis-py returns None; command docs say -1 return long(-1) if self.strict else None time_to_live = get_total_milliseconds(self.timeouts[key] - self.clock.now()) return long(max(-1, time_to_live))
Emulate pttl :param key: key for which pttl is requested. :returns: the number of milliseconds till timeout, None if the key does not exist or if the key has no timeout(as per the redis-py lib behavior).
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L235-L256
locationlabs/mockredis
mockredis/client.py
MockRedis.do_expire
def do_expire(self): """ Expire objects assuming now == time """ # Deep copy to avoid RuntimeError: dictionary changed size during iteration _timeouts = deepcopy(self.timeouts) for key, value in _timeouts.items(): if value - self.clock.now() < timedelta(0): del self.timeouts[key] # removing the expired key if key in self.redis: self.redis.pop(key, None)
python
def do_expire(self): """ Expire objects assuming now == time """ # Deep copy to avoid RuntimeError: dictionary changed size during iteration _timeouts = deepcopy(self.timeouts) for key, value in _timeouts.items(): if value - self.clock.now() < timedelta(0): del self.timeouts[key] # removing the expired key if key in self.redis: self.redis.pop(key, None)
Expire objects assuming now == time
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L258-L269
locationlabs/mockredis
mockredis/client.py
MockRedis.set
def set(self, key, value, ex=None, px=None, nx=False, xx=False): """ Set the ``value`` for the ``key`` in the context of the provided kwargs. As per the behavior of the redis-py lib: If nx and xx are both set, the function does nothing and None is returned. If px and ex are both set, the preference is given to px. If the key is not set for some reason, the lib function returns None. """ key = self._encode(key) value = self._encode(value) if nx and xx: return None mode = "nx" if nx else "xx" if xx else None if self._should_set(key, mode): expire = None if ex is not None: expire = ex if isinstance(ex, timedelta) else timedelta(seconds=ex) if px is not None: expire = px if isinstance(px, timedelta) else timedelta(milliseconds=px) if expire is not None and expire.total_seconds() <= 0: raise ResponseError("invalid expire time in SETEX") result = self._set(key, value) if expire: self._expire(key, expire) return result
python
def set(self, key, value, ex=None, px=None, nx=False, xx=False): """ Set the ``value`` for the ``key`` in the context of the provided kwargs. As per the behavior of the redis-py lib: If nx and xx are both set, the function does nothing and None is returned. If px and ex are both set, the preference is given to px. If the key is not set for some reason, the lib function returns None. """ key = self._encode(key) value = self._encode(value) if nx and xx: return None mode = "nx" if nx else "xx" if xx else None if self._should_set(key, mode): expire = None if ex is not None: expire = ex if isinstance(ex, timedelta) else timedelta(seconds=ex) if px is not None: expire = px if isinstance(px, timedelta) else timedelta(milliseconds=px) if expire is not None and expire.total_seconds() <= 0: raise ResponseError("invalid expire time in SETEX") result = self._set(key, value) if expire: self._expire(key, expire) return result
Set the ``value`` for the ``key`` in the context of the provided kwargs. As per the behavior of the redis-py lib: If nx and xx are both set, the function does nothing and None is returned. If px and ex are both set, the preference is given to px. If the key is not set for some reason, the lib function returns None.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L313-L342
locationlabs/mockredis
mockredis/client.py
MockRedis._should_set
def _should_set(self, key, mode): """ Determine if it is okay to set a key. If the mode is None, returns True, otherwise, returns True of false based on the value of ``key`` and the ``mode`` (nx | xx). """ if mode is None or mode not in ["nx", "xx"]: return True if mode == "nx": if key in self.redis: # nx means set only if key is absent # false if the key already exists return False elif key not in self.redis: # at this point mode can only be xx # xx means set only if the key already exists # false if is absent return False # for all other cases, return true return True
python
def _should_set(self, key, mode): """ Determine if it is okay to set a key. If the mode is None, returns True, otherwise, returns True of false based on the value of ``key`` and the ``mode`` (nx | xx). """ if mode is None or mode not in ["nx", "xx"]: return True if mode == "nx": if key in self.redis: # nx means set only if key is absent # false if the key already exists return False elif key not in self.redis: # at this point mode can only be xx # xx means set only if the key already exists # false if is absent return False # for all other cases, return true return True
Determine if it is okay to set a key. If the mode is None, returns True, otherwise, returns True of false based on the value of ``key`` and the ``mode`` (nx | xx).
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L359-L381
locationlabs/mockredis
mockredis/client.py
MockRedis.setex
def setex(self, name, time, value): """ Set the value of ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. """ if not self.strict: # when not strict mode swap value and time args order time, value = value, time return self.set(name, value, ex=time)
python
def setex(self, name, time, value): """ Set the value of ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. """ if not self.strict: # when not strict mode swap value and time args order time, value = value, time return self.set(name, value, ex=time)
Set the value of ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L383-L392
locationlabs/mockredis
mockredis/client.py
MockRedis.psetex
def psetex(self, key, time, value): """ Set the value of ``key`` to ``value`` that expires in ``time`` milliseconds. ``time`` can be represented by an integer or a Python timedelta object. """ return self.set(key, value, px=time)
python
def psetex(self, key, time, value): """ Set the value of ``key`` to ``value`` that expires in ``time`` milliseconds. ``time`` can be represented by an integer or a Python timedelta object. """ return self.set(key, value, px=time)
Set the value of ``key`` to ``value`` that expires in ``time`` milliseconds. ``time`` can be represented by an integer or a Python timedelta object.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L394-L400
locationlabs/mockredis
mockredis/client.py
MockRedis.setnx
def setnx(self, key, value): """Set the value of ``key`` to ``value`` if key doesn't exist""" return self.set(key, value, nx=True)
python
def setnx(self, key, value): """Set the value of ``key`` to ``value`` if key doesn't exist""" return self.set(key, value, nx=True)
Set the value of ``key`` to ``value`` if key doesn't exist
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L402-L404
locationlabs/mockredis
mockredis/client.py
MockRedis.mset
def mset(self, *args, **kwargs): """ Sets key/values based on a mapping. Mapping can be supplied as a single dictionary argument or as kwargs. """ mapping = kwargs if args: if len(args) != 1 or not isinstance(args[0], dict): raise RedisError('MSET requires **kwargs or a single dict arg') mapping.update(args[0]) if len(mapping) == 0: raise ResponseError("wrong number of arguments for 'mset' command") for key, value in mapping.items(): self.set(key, value) return True
python
def mset(self, *args, **kwargs): """ Sets key/values based on a mapping. Mapping can be supplied as a single dictionary argument or as kwargs. """ mapping = kwargs if args: if len(args) != 1 or not isinstance(args[0], dict): raise RedisError('MSET requires **kwargs or a single dict arg') mapping.update(args[0]) if len(mapping) == 0: raise ResponseError("wrong number of arguments for 'mset' command") for key, value in mapping.items(): self.set(key, value) return True
Sets key/values based on a mapping. Mapping can be supplied as a single dictionary argument or as kwargs.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L406-L422
locationlabs/mockredis
mockredis/client.py
MockRedis.msetnx
def msetnx(self, *args, **kwargs): """ Sets key/values based on a mapping if none of the keys are already set. Mapping can be supplied as a single dictionary argument or as kwargs. Returns a boolean indicating if the operation was successful. """ if args: if len(args) != 1 or not isinstance(args[0], dict): raise RedisError('MSETNX requires **kwargs or a single dict arg') mapping = args[0] else: mapping = kwargs if len(mapping) == 0: raise ResponseError("wrong number of arguments for 'msetnx' command") for key in mapping.keys(): if self._encode(key) in self.redis: return False for key, value in mapping.items(): self.set(key, value) return True
python
def msetnx(self, *args, **kwargs): """ Sets key/values based on a mapping if none of the keys are already set. Mapping can be supplied as a single dictionary argument or as kwargs. Returns a boolean indicating if the operation was successful. """ if args: if len(args) != 1 or not isinstance(args[0], dict): raise RedisError('MSETNX requires **kwargs or a single dict arg') mapping = args[0] else: mapping = kwargs if len(mapping) == 0: raise ResponseError("wrong number of arguments for 'msetnx' command") for key in mapping.keys(): if self._encode(key) in self.redis: return False for key, value in mapping.items(): self.set(key, value) return True
Sets key/values based on a mapping if none of the keys are already set. Mapping can be supplied as a single dictionary argument or as kwargs. Returns a boolean indicating if the operation was successful.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L424-L446
locationlabs/mockredis
mockredis/client.py
MockRedis.setbit
def setbit(self, key, offset, value): """ Set the bit at ``offset`` in ``key`` to ``value``. """ key = self._encode(key) index, bits, mask = self._get_bits_and_offset(key, offset) if index >= len(bits): bits.extend(b"\x00" * (index + 1 - len(bits))) prev_val = 1 if (bits[index] & mask) else 0 if value: bits[index] |= mask else: bits[index] &= ~mask self.redis[key] = bytes(bits) return prev_val
python
def setbit(self, key, offset, value): """ Set the bit at ``offset`` in ``key`` to ``value``. """ key = self._encode(key) index, bits, mask = self._get_bits_and_offset(key, offset) if index >= len(bits): bits.extend(b"\x00" * (index + 1 - len(bits))) prev_val = 1 if (bits[index] & mask) else 0 if value: bits[index] |= mask else: bits[index] &= ~mask self.redis[key] = bytes(bits) return prev_val
Set the bit at ``offset`` in ``key`` to ``value``.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L465-L484
locationlabs/mockredis
mockredis/client.py
MockRedis.getbit
def getbit(self, key, offset): """ Returns the bit value at ``offset`` in ``key``. """ key = self._encode(key) index, bits, mask = self._get_bits_and_offset(key, offset) if index >= len(bits): return 0 return 1 if (bits[index] & mask) else 0
python
def getbit(self, key, offset): """ Returns the bit value at ``offset`` in ``key``. """ key = self._encode(key) index, bits, mask = self._get_bits_and_offset(key, offset) if index >= len(bits): return 0 return 1 if (bits[index] & mask) else 0
Returns the bit value at ``offset`` in ``key``.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L486-L496
locationlabs/mockredis
mockredis/client.py
MockRedis.hexists
def hexists(self, hashkey, attribute): """Emulate hexists.""" redis_hash = self._get_hash(hashkey, 'HEXISTS') return self._encode(attribute) in redis_hash
python
def hexists(self, hashkey, attribute): """Emulate hexists.""" redis_hash = self._get_hash(hashkey, 'HEXISTS') return self._encode(attribute) in redis_hash
Emulate hexists.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L506-L510
locationlabs/mockredis
mockredis/client.py
MockRedis.hget
def hget(self, hashkey, attribute): """Emulate hget.""" redis_hash = self._get_hash(hashkey, 'HGET') return redis_hash.get(self._encode(attribute))
python
def hget(self, hashkey, attribute): """Emulate hget.""" redis_hash = self._get_hash(hashkey, 'HGET') return redis_hash.get(self._encode(attribute))
Emulate hget.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L512-L516
locationlabs/mockredis
mockredis/client.py
MockRedis.hdel
def hdel(self, hashkey, *keys): """Emulate hdel""" redis_hash = self._get_hash(hashkey, 'HDEL') count = 0 for key in keys: attribute = self._encode(key) if attribute in redis_hash: count += 1 del redis_hash[attribute] if not redis_hash: self.delete(hashkey) return count
python
def hdel(self, hashkey, *keys): """Emulate hdel""" redis_hash = self._get_hash(hashkey, 'HDEL') count = 0 for key in keys: attribute = self._encode(key) if attribute in redis_hash: count += 1 del redis_hash[attribute] if not redis_hash: self.delete(hashkey) return count
Emulate hdel
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L524-L536
locationlabs/mockredis
mockredis/client.py
MockRedis.hmset
def hmset(self, hashkey, value): """Emulate hmset.""" redis_hash = self._get_hash(hashkey, 'HMSET', create=True) for key, value in value.items(): attribute = self._encode(key) redis_hash[attribute] = self._encode(value) return True
python
def hmset(self, hashkey, value): """Emulate hmset.""" redis_hash = self._get_hash(hashkey, 'HMSET', create=True) for key, value in value.items(): attribute = self._encode(key) redis_hash[attribute] = self._encode(value) return True
Emulate hmset.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L543-L550
locationlabs/mockredis
mockredis/client.py
MockRedis.hmget
def hmget(self, hashkey, keys, *args): """Emulate hmget.""" redis_hash = self._get_hash(hashkey, 'HMGET') attributes = self._list_or_args(keys, args) return [redis_hash.get(self._encode(attribute)) for attribute in attributes]
python
def hmget(self, hashkey, keys, *args): """Emulate hmget.""" redis_hash = self._get_hash(hashkey, 'HMGET') attributes = self._list_or_args(keys, args) return [redis_hash.get(self._encode(attribute)) for attribute in attributes]
Emulate hmget.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L552-L557
locationlabs/mockredis
mockredis/client.py
MockRedis.hset
def hset(self, hashkey, attribute, value): """Emulate hset.""" redis_hash = self._get_hash(hashkey, 'HSET', create=True) attribute = self._encode(attribute) attribute_present = attribute in redis_hash redis_hash[attribute] = self._encode(value) return long(0) if attribute_present else long(1)
python
def hset(self, hashkey, attribute, value): """Emulate hset.""" redis_hash = self._get_hash(hashkey, 'HSET', create=True) attribute = self._encode(attribute) attribute_present = attribute in redis_hash redis_hash[attribute] = self._encode(value) return long(0) if attribute_present else long(1)
Emulate hset.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L559-L566
locationlabs/mockredis
mockredis/client.py
MockRedis.hsetnx
def hsetnx(self, hashkey, attribute, value): """Emulate hsetnx.""" redis_hash = self._get_hash(hashkey, 'HSETNX', create=True) attribute = self._encode(attribute) if attribute in redis_hash: return long(0) else: redis_hash[attribute] = self._encode(value) return long(1)
python
def hsetnx(self, hashkey, attribute, value): """Emulate hsetnx.""" redis_hash = self._get_hash(hashkey, 'HSETNX', create=True) attribute = self._encode(attribute) if attribute in redis_hash: return long(0) else: redis_hash[attribute] = self._encode(value) return long(1)
Emulate hsetnx.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L568-L577
locationlabs/mockredis
mockredis/client.py
MockRedis.hincrby
def hincrby(self, hashkey, attribute, increment=1): """Emulate hincrby.""" return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment)
python
def hincrby(self, hashkey, attribute, increment=1): """Emulate hincrby.""" return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment)
Emulate hincrby.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L579-L582
locationlabs/mockredis
mockredis/client.py
MockRedis.hincrbyfloat
def hincrbyfloat(self, hashkey, attribute, increment=1.0): """Emulate hincrbyfloat.""" return self._hincrby(hashkey, attribute, 'HINCRBYFLOAT', float, increment)
python
def hincrbyfloat(self, hashkey, attribute, increment=1.0): """Emulate hincrbyfloat.""" return self._hincrby(hashkey, attribute, 'HINCRBYFLOAT', float, increment)
Emulate hincrbyfloat.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L584-L587
locationlabs/mockredis
mockredis/client.py
MockRedis._hincrby
def _hincrby(self, hashkey, attribute, command, type_, increment): """Shared hincrby and hincrbyfloat routine""" redis_hash = self._get_hash(hashkey, command, create=True) attribute = self._encode(attribute) previous_value = type_(redis_hash.get(attribute, '0')) redis_hash[attribute] = self._encode(previous_value + increment) return type_(redis_hash[attribute])
python
def _hincrby(self, hashkey, attribute, command, type_, increment): """Shared hincrby and hincrbyfloat routine""" redis_hash = self._get_hash(hashkey, command, create=True) attribute = self._encode(attribute) previous_value = type_(redis_hash.get(attribute, '0')) redis_hash[attribute] = self._encode(previous_value + increment) return type_(redis_hash[attribute])
Shared hincrby and hincrbyfloat routine
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L589-L595
locationlabs/mockredis
mockredis/client.py
MockRedis.lrange
def lrange(self, key, start, stop): """Emulate lrange.""" redis_list = self._get_list(key, 'LRANGE') start, stop = self._translate_range(len(redis_list), start, stop) return redis_list[start:stop + 1]
python
def lrange(self, key, start, stop): """Emulate lrange.""" redis_list = self._get_list(key, 'LRANGE') start, stop = self._translate_range(len(redis_list), start, stop) return redis_list[start:stop + 1]
Emulate lrange.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L611-L615
locationlabs/mockredis
mockredis/client.py
MockRedis.lindex
def lindex(self, key, index): """Emulate lindex.""" redis_list = self._get_list(key, 'LINDEX') if self._encode(key) not in self.redis: return None try: return redis_list[index] except (IndexError): # Redis returns nil if the index doesn't exist return None
python
def lindex(self, key, index): """Emulate lindex.""" redis_list = self._get_list(key, 'LINDEX') if self._encode(key) not in self.redis: return None try: return redis_list[index] except (IndexError): # Redis returns nil if the index doesn't exist return None
Emulate lindex.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L617-L629
locationlabs/mockredis
mockredis/client.py
MockRedis._blocking_pop
def _blocking_pop(self, pop_func, keys, timeout): """Emulate blocking pop functionality""" if not isinstance(timeout, (int, long)): raise RuntimeError('timeout is not an integer or out of range') if timeout is None or timeout == 0: timeout = self.blocking_timeout if isinstance(keys, basestring): keys = [keys] else: keys = list(keys) elapsed_time = 0 start = time.time() while elapsed_time < timeout: key, val = self._pop_first_available(pop_func, keys) if val: return key, val # small delay to avoid high cpu utilization time.sleep(self.blocking_sleep_interval) elapsed_time = time.time() - start return None
python
def _blocking_pop(self, pop_func, keys, timeout): """Emulate blocking pop functionality""" if not isinstance(timeout, (int, long)): raise RuntimeError('timeout is not an integer or out of range') if timeout is None or timeout == 0: timeout = self.blocking_timeout if isinstance(keys, basestring): keys = [keys] else: keys = list(keys) elapsed_time = 0 start = time.time() while elapsed_time < timeout: key, val = self._pop_first_available(pop_func, keys) if val: return key, val # small delay to avoid high cpu utilization time.sleep(self.blocking_sleep_interval) elapsed_time = time.time() - start return None
Emulate blocking pop functionality
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L638-L660
locationlabs/mockredis
mockredis/client.py
MockRedis.blpop
def blpop(self, keys, timeout=0): """Emulate blpop""" return self._blocking_pop(self.lpop, keys, timeout)
python
def blpop(self, keys, timeout=0): """Emulate blpop""" return self._blocking_pop(self.lpop, keys, timeout)
Emulate blpop
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L669-L671
locationlabs/mockredis
mockredis/client.py
MockRedis.brpop
def brpop(self, keys, timeout=0): """Emulate brpop""" return self._blocking_pop(self.rpop, keys, timeout)
python
def brpop(self, keys, timeout=0): """Emulate brpop""" return self._blocking_pop(self.rpop, keys, timeout)
Emulate brpop
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L673-L675
locationlabs/mockredis
mockredis/client.py
MockRedis.lpush
def lpush(self, key, *args): """Emulate lpush.""" redis_list = self._get_list(key, 'LPUSH', create=True) # Creates the list at this key if it doesn't exist, and appends args to its beginning args_reversed = [self._encode(arg) for arg in args] args_reversed.reverse() updated_list = args_reversed + redis_list self.redis[self._encode(key)] = updated_list # Return the length of the list after the push operation return len(updated_list)
python
def lpush(self, key, *args): """Emulate lpush.""" redis_list = self._get_list(key, 'LPUSH', create=True) # Creates the list at this key if it doesn't exist, and appends args to its beginning args_reversed = [self._encode(arg) for arg in args] args_reversed.reverse() updated_list = args_reversed + redis_list self.redis[self._encode(key)] = updated_list # Return the length of the list after the push operation return len(updated_list)
Emulate lpush.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L693-L704
locationlabs/mockredis
mockredis/client.py
MockRedis.rpop
def rpop(self, key): """Emulate lpop.""" redis_list = self._get_list(key, 'RPOP') if self._encode(key) not in self.redis: return None try: value = redis_list.pop() if len(redis_list) == 0: self.delete(key) return value except (IndexError): # Redis returns nil if popping from an empty list return None
python
def rpop(self, key): """Emulate lpop.""" redis_list = self._get_list(key, 'RPOP') if self._encode(key) not in self.redis: return None try: value = redis_list.pop() if len(redis_list) == 0: self.delete(key) return value except (IndexError): # Redis returns nil if popping from an empty list return None
Emulate lpop.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L706-L720
locationlabs/mockredis
mockredis/client.py
MockRedis.rpush
def rpush(self, key, *args): """Emulate rpush.""" redis_list = self._get_list(key, 'RPUSH', create=True) # Creates the list at this key if it doesn't exist, and appends args to it redis_list.extend(map(self._encode, args)) # Return the length of the list after the push operation return len(redis_list)
python
def rpush(self, key, *args): """Emulate rpush.""" redis_list = self._get_list(key, 'RPUSH', create=True) # Creates the list at this key if it doesn't exist, and appends args to it redis_list.extend(map(self._encode, args)) # Return the length of the list after the push operation return len(redis_list)
Emulate rpush.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L722-L730
locationlabs/mockredis
mockredis/client.py
MockRedis.lrem
def lrem(self, key, value, count=0): """Emulate lrem.""" value = self._encode(value) redis_list = self._get_list(key, 'LREM') removed_count = 0 if self._encode(key) in self.redis: if count == 0: # Remove all ocurrences while redis_list.count(value): redis_list.remove(value) removed_count += 1 elif count > 0: counter = 0 # remove first 'count' ocurrences while redis_list.count(value): redis_list.remove(value) counter += 1 removed_count += 1 if counter >= count: break elif count < 0: # remove last 'count' ocurrences counter = -count new_list = [] for v in reversed(redis_list): if v == value and counter > 0: counter -= 1 removed_count += 1 else: new_list.append(v) redis_list[:] = list(reversed(new_list)) if removed_count > 0 and len(redis_list) == 0: self.delete(key) return removed_count
python
def lrem(self, key, value, count=0): """Emulate lrem.""" value = self._encode(value) redis_list = self._get_list(key, 'LREM') removed_count = 0 if self._encode(key) in self.redis: if count == 0: # Remove all ocurrences while redis_list.count(value): redis_list.remove(value) removed_count += 1 elif count > 0: counter = 0 # remove first 'count' ocurrences while redis_list.count(value): redis_list.remove(value) counter += 1 removed_count += 1 if counter >= count: break elif count < 0: # remove last 'count' ocurrences counter = -count new_list = [] for v in reversed(redis_list): if v == value and counter > 0: counter -= 1 removed_count += 1 else: new_list.append(v) redis_list[:] = list(reversed(new_list)) if removed_count > 0 and len(redis_list) == 0: self.delete(key) return removed_count
Emulate lrem.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L732-L765
locationlabs/mockredis
mockredis/client.py
MockRedis.ltrim
def ltrim(self, key, start, stop): """Emulate ltrim.""" redis_list = self._get_list(key, 'LTRIM') if redis_list: start, stop = self._translate_range(len(redis_list), start, stop) self.redis[self._encode(key)] = redis_list[start:stop + 1] return True
python
def ltrim(self, key, start, stop): """Emulate ltrim.""" redis_list = self._get_list(key, 'LTRIM') if redis_list: start, stop = self._translate_range(len(redis_list), start, stop) self.redis[self._encode(key)] = redis_list[start:stop + 1] return True
Emulate ltrim.
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L767-L773
locationlabs/mockredis
mockredis/client.py
MockRedis.rpoplpush
def rpoplpush(self, source, destination): """Emulate rpoplpush""" transfer_item = self.rpop(source) if transfer_item is not None: self.lpush(destination, transfer_item) return transfer_item
python
def rpoplpush(self, source, destination): """Emulate rpoplpush""" transfer_item = self.rpop(source) if transfer_item is not None: self.lpush(destination, transfer_item) return transfer_item
Emulate rpoplpush
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L775-L780
locationlabs/mockredis
mockredis/client.py
MockRedis.brpoplpush
def brpoplpush(self, source, destination, timeout=0): """Emulate brpoplpush""" transfer_item = self.brpop(source, timeout) if transfer_item is None: return None key, val = transfer_item self.lpush(destination, val) return val
python
def brpoplpush(self, source, destination, timeout=0): """Emulate brpoplpush""" transfer_item = self.brpop(source, timeout) if transfer_item is None: return None key, val = transfer_item self.lpush(destination, val) return val
Emulate brpoplpush
https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L782-L790