code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def call( self, input_ids: tf.Tensor = None, token_type_ids: tf.Tensor = None, inputs_embeds: tf.Tensor = None, training: bool = False, ) -> tf.Tensor: """ Applies embedding based on inputs tensor. Returns: final_embeddings (:obj:`tf.Tensor...
Applies embedding based on inputs tensor. Returns: final_embeddings (:obj:`tf.Tensor`): output embedding tensor.
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` ...
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the cross entropy classification loss. Indices should be in ``[0, ..., config.vocab_size - 1]``.
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-S...
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the multiple choice classification loss. Indices should be in ``[0, ..., num_choices]`` where :obj:`num_choices` is the size of the second dimension of the input tensors. (See ...
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
labels (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels - 1]``.
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def call( self, input_ids: Optional[TFModelInputType] = None, attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, inputs_embeds: Optional[Un...
start_positions (:obj:`tf.Tensor` or :obj:`np.ndarray` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Pos...
call
python
JunnYu/RoFormer_pytorch
src/roformer/modeling_tf_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/modeling_tf_roformer.py
Apache-2.0
def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoFormer sequence h...
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoFormer sequence has the following format: - single sequence: ``[CLS] X [SEP]`` - pair of sequences: ``[CLS] A [SEP] B [SEP]`` Args: ...
build_inputs_with_special_tokens
python
JunnYu/RoFormer_pytorch
src/roformer/tokenization_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/tokenization_roformer.py
Apache-2.0
def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False, ) -> List[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when addin...
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method. Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, ...
get_special_tokens_mask
python
JunnYu/RoFormer_pytorch
src/roformer/tokenization_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/tokenization_roformer.py
Apache-2.0
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A RoFormer sequence pair mask has the following format: ...
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A RoFormer sequence pair mask has the following format: :: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | If :obj:`token_ids_1` is :obj...
create_token_type_ids_from_sequences
python
JunnYu/RoFormer_pytorch
src/roformer/tokenization_roformer.py
https://github.com/JunnYu/RoFormer_pytorch/blob/master/src/roformer/tokenization_roformer.py
Apache-2.0
def parse_arguments(): """Parse and return the command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--result_dir', help="Directory where the results are saved.") parser.add_argument('--checkpoint_dir', help="Directory that con...
Parse and return the command line arguments.
parse_arguments
python
salu133445/musegan
src/inference.py
https://github.com/salu133445/musegan/blob/master/src/inference.py
MIT
def setup(): """Parse command line arguments, load model parameters, load configurations and setup environment.""" # Parse the command line arguments args = parse_arguments() # Load parameters params = load_yaml(args.params) # Load training configurations config = load_yaml(args.config...
Parse command line arguments, load model parameters, load configurations and setup environment.
setup
python
salu133445/musegan
src/inference.py
https://github.com/salu133445/musegan/blob/master/src/inference.py
MIT
def slerp(a, b, t): """Return the spherical linear interpolation of point `a` and `b` at specific ratio `t`.""" omega = np.arccos(np.dot(a / np.linalg.norm(a), b / np.linalg.norm(b))) so = np.sin(omega) return np.sin((1 - t) * omega) / so * a + np.sin(t * omega) / so * b
Return the spherical linear interpolation of point `a` and `b` at specific ratio `t`.
slerp
python
salu133445/musegan
src/interpolation.py
https://github.com/salu133445/musegan/blob/master/src/interpolation.py
MIT
def lerp(a, b1, b2, t1, t2): """Return the 2D linear interpolation of point `a`, `b1` and `b2` at specific ratio `t1` and `t2`.""" inter1 = a * (1 - t1) + b1 * t1 inter2 = b2 * (1 - t1) + (b2 + (b1 - a)) * t1 return inter1 * (1 - t2) + t2 * inter2
Return the 2D linear interpolation of point `a`, `b1` and `b2` at specific ratio `t1` and `t2`.
lerp
python
salu133445/musegan
src/interpolation.py
https://github.com/salu133445/musegan/blob/master/src/interpolation.py
MIT
def get_input_z(config, params): """Return input latent code to the generator.""" if ((config['mode'] == 'slerp') and (config['rows'] > 1) and (config['columns'] > 1)): raise ValueError("Only supports 1D interpolation in 'slerp' mode.") a = scipy.stats.truncnorm.rvs( config['low...
Return input latent code to the generator.
get_input_z
python
salu133445/musegan
src/interpolation.py
https://github.com/salu133445/musegan/blob/master/src/interpolation.py
MIT
def create_shared_array(name, shape, dtype): """Create shared array. Prompt if a file with the same name existed.""" try: return sa.create(name, shape, dtype) except FileExistsError: response = "" while response.lower() not in ["y", "n", "yes", "no"]: response = input( ...
Create shared array. Prompt if a file with the same name existed.
create_shared_array
python
salu133445/musegan
src/process_data.py
https://github.com/salu133445/musegan/blob/master/src/process_data.py
MIT
def main(): """Load and save an array to shared memory.""" filepath, name, prefix, dtype = parse_arguments() if name is None: name = os.path.splitext(os.path.basename(filepath))[0] if prefix is not None: name = prefix + "_" + name print("Loading data from '{}'.".format(file...
Load and save an array to shared memory.
main
python
salu133445/musegan
src/process_data.py
https://github.com/salu133445/musegan/blob/master/src/process_data.py
MIT
def setup_dirs(config): """Setup an experiment directory structure and update the `params` dictionary with the directory paths.""" # Get experiment directory structure config['exp_dir'] = os.path.realpath(config['exp_dir']) config['src_dir'] = os.path.join(config['exp_dir'], 'src') config['eval_...
Setup an experiment directory structure and update the `params` dictionary with the directory paths.
setup_dirs
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def setup(): """Parse command line arguments, load model parameters, load configurations, setup environment and setup loggers.""" # Parse the command line arguments args = parse_arguments() # Load parameters params = load_yaml(args.params) if params.get('is_accompaniment') and params.get('c...
Parse command line arguments, load model parameters, load configurations, setup environment and setup loggers.
setup
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def load_training_data(params, config): """Load and return the training data.""" # Load data if params['is_conditional']: raise ValueError("Not supported yet.") else: labels = None LOGGER.info("Loading training data.") data = load_data(config['data_source'], config['data_filename...
Load and return the training data.
load_training_data
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def load_or_create_samples(params, config): """Load or create the samples used as the sampler inputs.""" # Load sample_z LOGGER.info("Loading sample_z.") sample_z_path = os.path.join(config['model_dir'], 'sample_z.npy') if os.path.exists(sample_z_path): sample_z = np.load(sample_z_path) ...
Load or create the samples used as the sampler inputs.
load_or_create_samples
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def get_n_params(var_list): """Return the number of variables in a variable list.""" return int(np.sum([np.product( [x.value for x in var.get_shape()]) for var in var_list]))
Return the number of variables in a variable list.
get_n_params
python
salu133445/musegan
src/train.py
https://github.com/salu133445/musegan/blob/master/src/train.py
MIT
def load_data_from_npz(filename): """Load and return the training data from a npz file (sparse format).""" with np.load(filename) as f: data = np.zeros(f['shape'], np.bool_) data[[x for x in f['nonzero']]] = True return data
Load and return the training data from a npz file (sparse format).
load_data_from_npz
python
salu133445/musegan
src/musegan/data.py
https://github.com/salu133445/musegan/blob/master/src/musegan/data.py
MIT
def get_samples(n_samples, data, labels=None, use_random_transpose=False): """Return some random samples of the training data.""" indices = np.random.choice(len(data), n_samples, False) if np.issubdtype(data.dtype, np.bool_): sample_data = data[indices] * 2. - 1. else: sample_data = data...
Return some random samples of the training data.
get_samples
python
salu133445/musegan
src/musegan/data.py
https://github.com/salu133445/musegan/blob/master/src/musegan/data.py
MIT
def get_dataset(data, labels=None, batch_size=None, data_shape=None, use_random_transpose=False, num_threads=1): """Create and return a tensorflow dataset from an array.""" if labels is None: dataset = tf.data.Dataset.from_generator( lambda: _gen_data(data), tf.float32) ...
Create and return a tensorflow dataset from an array.
get_dataset
python
salu133445/musegan
src/musegan/data.py
https://github.com/salu133445/musegan/blob/master/src/musegan/data.py
MIT
def vector_to_image(array, inverted=True): """ Convert a batched vector array to an image array. Arguments --------- array : `np.array`, ndim=2 The vector array. Returns ------- image : `np.array`, ndim=4 The image array. """ if array.ndim != 2: raise Va...
Convert a batched vector array to an image array. Arguments --------- array : `np.array`, ndim=2 The vector array. Returns ------- image : `np.array`, ndim=4 The image array.
vector_to_image
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def pianoroll_to_image(pianoroll, colormap=None, inverted=True, boundary_width=1, boundary_color=0, frame=False, gamma=1.): """ Convert a batched pianoroll array to an image array. Arguments --------- pianoroll : `np.array`, ndim=5 The pianoroll...
Convert a batched pianoroll array to an image array. Arguments --------- pianoroll : `np.array`, ndim=5 The pianoroll array. The shape is (n_pianorolls, n_bars, n_timestep, n_pitches, n_tracks). boundary_width : int Linewidth of the boundary lines. Default to 0. boundar...
pianoroll_to_image
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def image_pair(image1, image2, mode='side-by-side', boundary_width=1, boundary_color=0, frame=False): """ Pair two image arrays to one single image array. Arguments --------- image1 : `np.array`, ndim=4 The image array at the left in 'side-by-side' mode or at the top in ...
Pair two image arrays to one single image array. Arguments --------- image1 : `np.array`, ndim=4 The image array at the left in 'side-by-side' mode or at the top in 'top-bottom' mode. image2 : `np.array`, ndim=4 The image array at the right in 'side-by-side' mode or at the ...
image_pair
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def image_grid(image, grid_shape, grid_width=3, grid_color=0, frame=True): """ Convert a batched image array to one merged grid image array. Arguments --------- pianoroll : `np.array`, ndim=4 The pianoroll array. The first axis is the batch axis. The second and third axes are the ti...
Convert a batched image array to one merged grid image array. Arguments --------- pianoroll : `np.array`, ndim=4 The pianoroll array. The first axis is the batch axis. The second and third axes are the time and pitch axes, respectively, of the pianorolls. The last axis is the t...
image_grid
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def save_pianoroll(filename, pianoroll, programs, is_drums, tempo, beat_resolution, lowest_pitch): """Saves a batched pianoroll array to a npz file.""" if not np.issubdtype(pianoroll.dtype, np.bool_): raise TypeError("Input pianoroll array must have a boolean dtype.") if pianoroll...
Saves a batched pianoroll array to a npz file.
save_pianoroll
python
salu133445/musegan
src/musegan/io_utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/io_utils.py
MIT
def get_adv_losses(discriminator_real_outputs, discriminator_fake_outputs, kind): """Return the corresponding GAN losses for the generator and the discriminator.""" if kind == 'classic': loss_fn = classic_gan_losses elif kind == 'nonsaturating': loss_fn = nonsaturating...
Return the corresponding GAN losses for the generator and the discriminator.
get_adv_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def classic_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): """Return the classic GAN losses for the generator and the discriminator. (Generator) log(1 - sigmoid(D(G(z)))) (Discriminator) - log(sigmoid(D(x))) - log(1 - sigmoid(D(G(z)))) """ discriminator_loss_real = tf.los...
Return the classic GAN losses for the generator and the discriminator. (Generator) log(1 - sigmoid(D(G(z)))) (Discriminator) - log(sigmoid(D(x))) - log(1 - sigmoid(D(G(z))))
classic_gan_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def nonsaturating_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): """Return the non-saturating GAN losses for the generator and the discriminator. (Generator) -log(sigmoid(D(G(z)))) (Discriminator) -log(sigmoid(D(x))) - log(1 - sigmoid(D(G(z)))) ...
Return the non-saturating GAN losses for the generator and the discriminator. (Generator) -log(sigmoid(D(G(z)))) (Discriminator) -log(sigmoid(D(x))) - log(1 - sigmoid(D(G(z))))
nonsaturating_gan_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def wasserstein_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): """Return the Wasserstein GAN losses for the generator and the discriminator. (Generator) -D(G(z)) (Discriminator) D(G(z)) - D(x) """ generator_loss = -tf.reduce_mean(discriminat...
Return the Wasserstein GAN losses for the generator and the discriminator. (Generator) -D(G(z)) (Discriminator) D(G(z)) - D(x)
wasserstein_gan_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def hinge_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): """Return the Hinge GAN losses for the generator and the discriminator. (Generator) -D(G(z)) (Discriminator) max(0, 1 - D(x)) + max(0, 1 + D(G(z))) """ generator_loss = -tf.reduce_mean(discriminator_fake_outputs) ...
Return the Hinge GAN losses for the generator and the discriminator. (Generator) -D(G(z)) (Discriminator) max(0, 1 - D(x)) + max(0, 1 + D(G(z)))
hinge_gan_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def to_chroma(pianoroll): """Return the chroma features (not normalized).""" if pianoroll.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") remainder = pianoroll.get_shape()[3] % 12 if remainder: pianoroll = tf.pad( pianoroll, ((0, 0), (0, 0), (...
Return the chroma features (not normalized).
to_chroma
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def empty_bar_rate(tensor): """Return the ratio of empty bars to the total number of bars.""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") return tf.reduce_mean( tf.cast(tf.reduce_any(tensor > 0.5, (2, 3)), tf.float32), (0, 1))
Return the ratio of empty bars to the total number of bars.
empty_bar_rate
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def n_pitches_used(tensor): """Return the number of unique pitches used per bar.""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") return tf.reduce_mean(tf.reduce_sum(tf.count_nonzero(tensor, 3), 2), [0, 1])
Return the number of unique pitches used per bar.
n_pitches_used
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def qualified_note_rate(tensor, 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 piano-roll.""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") def _q...
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 piano-roll.
qualified_note_rate
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _qualified_note_rate(array, threshold): """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 piano-roll.""" n_tracks = array.shape[-1] reshaped = array.reshape(-1, array.shape[1] * array.shap...
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 piano-roll.
_qualified_note_rate
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def polyphonic_rate(tensor, 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""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") n_poly = t...
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
polyphonic_rate
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _drum_pattern_mask(n_timesteps, tolerance=0.1): """Return a drum pattern mask with the given tolerance.""" if n_timesteps not in (96, 48, 24, 72, 36, 64, 32, 16): raise ValueError("Unsupported number of timesteps for the drum in " "pattern metric.") i...
Return a drum pattern mask with the given tolerance.
_drum_pattern_mask
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _scale_mask(key=3): """Return a scale mask for the given key. Default to C major scale.""" a_scale_mask = np.array([[[1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0]]], bool) return np.expand_dims(np.roll(a_scale_mask, -key, 2), -1)
Return a scale mask for the given key. Default to C major scale.
_scale_mask
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _tonal_matrix(r1=1.0, r2=1.0, r3=0.5): """Compute and return a tonal matrix for computing the tonal distance [1]. Default argument values are set as suggested by the paper. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. A...
Compute and return a tonal matrix for computing the tonal distance [1]. Default argument values are set as suggested by the paper. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM MM Workshop on Audio and Music Computing Mu...
_tonal_matrix
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _to_tonal_space(tensor): """Return the tensor in tonal space where chroma features are normalized per beat.""" tonal_matrix = tf.constant(_tonal_matrix(), tf.float32) beat_chroma = tf.reduce_sum(tf.reshape( tensor, (-1, beat_resolution, 12, tensor.get_shape()[4])), 1) ...
Return the tensor in tonal space where chroma features are normalized per beat.
_to_tonal_space
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def get_train_nodes(self, x, z=None, y=None, c=None, params=None, config=None): """Return a dictionary of graph nodes for training.""" LOGGER.info("Building training nodes.") with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE) as scope: nodes = {} ...
Return a dictionary of graph nodes for training.
get_train_nodes
python
salu133445/musegan
src/musegan/model.py
https://github.com/salu133445/musegan/blob/master/src/musegan/model.py
MIT
def _array_to_image(array, colormap=None): """Convert an array to an image array and return it.""" if array.ndim == 2: return vector_to_image(array) return pianoroll_to_image(array, colormap)
Convert an array to an image array and return it.
_array_to_image
python
salu133445/musegan
src/musegan/model.py
https://github.com/salu133445/musegan/blob/master/src/musegan/model.py
MIT
def make_sure_path_exists(path): """Create intermidate directories if the path does not exist.""" try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise
Create intermidate directories if the path does not exist.
make_sure_path_exists
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def update_not_none(dict1, dict2): """Update the values of keys in `dict1` with the values of the same key from `dict2` if the values in `dict2` is not None.""" for key, value in dict2.items(): if value is not None: dict1[key] = value
Update the values of keys in `dict1` with the values of the same key from `dict2` if the values in `dict2` is not None.
update_not_none
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def update_existing(dict1, dict2): """Update the values of keys in `dict1` with the values of the same key from `dict2` if the values in `dict2` is not None and the same key is in `dict1`. """ for key, value in dict2.items(): if value is not None and key in dict1: dict1[key] = value
Update the values of keys in `dict1` with the values of the same key from `dict2` if the values in `dict2` is not None and the same key is in `dict1`.
update_existing
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def load_component(component, name, class_name): """Load and return component network from file.""" imported = importlib.import_module( '.'.join(('musegan.presets', component, name))) return getattr(imported, class_name)
Load and return component network from file.
load_component
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def add_file_handler(logger, log_filepath, loglevel=FILE_LOGLEVEL, log_format=FILE_LOG_FORMAT): """Add a file handler to the logger.""" file_handler = logging.FileHandler(log_filepath) file_handler.setLevel(loglevel) file_handler.setFormatter(logging.Formatter(log_format)) logge...
Add a file handler to the logger.
add_file_handler
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def setup_loggers(log_dir, loglevel=FILE_LOGLEVEL, log_format=FILE_LOG_FORMAT): """Setup the loggers with file handlers.""" for name in logging.Logger.manager.loggerDict.keys(): if name.startswith('musegan'): add_file_handler( logging.getLogger(name), os.path.join(log_dir, na...
Setup the loggers with file handlers.
setup_loggers
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def binary_round(x): """ Rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1}, using the straight through estimator for the gradient. """ g = tf.get_default_graph() with ops.name_scope("BinaryRound") as name: with g.gradient_override_map({"Round": "Identity"}): ...
Rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1}, using the straight through estimator for the gradient.
binary_round
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def bernoulli_sample(x): """ Uses a tensor whose values are in [0,1] to sample a tensor with values in {0, 1}, using the straight through estimator for the gradient. E.g., if x is 0.6, bernoulliSample(x) will be 1 with probability 0.6, and 0 otherwise, and the gradient will be pass-through (identit...
Uses a tensor whose values are in [0,1] to sample a tensor with values in {0, 1}, using the straight through estimator for the gradient. E.g., if x is 0.6, bernoulliSample(x) will be 1 with probability 0.6, and 0 otherwise, and the gradient will be pass-through (identity).
bernoulli_sample
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def pass_through_sigmoid(x, slope=1): """Sigmoid that uses identity function as its gradient""" g = tf.get_default_graph() with ops.name_scope("PassThroughSigmoid") as name: with g.gradient_override_map({"Sigmoid": "Identity"}): return tf.sigmoid(x, name=name)
Sigmoid that uses identity function as its gradient
pass_through_sigmoid
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def binary_stochastic_ST(x, slope_tensor=None, pass_through=True, stochastic=True): """ Sigmoid followed by either a random sample from a bernoulli distribution according to the result (binary stochastic neuron) (default), or a sigmoid followed by a binary step function (if stoch...
Sigmoid followed by either a random sample from a bernoulli distribution according to the result (binary stochastic neuron) (default), or a sigmoid followed by a binary step function (if stochastic == False). Uses the straight through estimator. See https://arxiv.org/abs/1308.3432. Arguments: ...
binary_stochastic_ST
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def binary_stochastic_REINFORCE(x, loss_op_name="loss_by_example"): """ Sigmoid followed by a random sample from a bernoulli distribution according to the result (binary stochastic neuron). Uses the REINFORCE estimator. See https://arxiv.org/abs/1308.3432. NOTE: Requires a loss operation with name ...
Sigmoid followed by a random sample from a bernoulli distribution according to the result (binary stochastic neuron). Uses the REINFORCE estimator. See https://arxiv.org/abs/1308.3432. NOTE: Requires a loss operation with name matching the argument for loss_op_name in the graph. This loss operatio...
binary_stochastic_REINFORCE
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def _binaryStochastic_REINFORCE(op, _): """Unbiased estimator for binary stochastic function based on REINFORCE.""" loss_op_name = op.graph.get_collection("REINFORCE")[0][op.name] loss_tensor = op.graph.get_operation_by_name(loss_op_name).outputs[0] sub_tensor = op.outputs[0].consumers()[0].outputs[0] ...
Unbiased estimator for binary stochastic function based on REINFORCE.
_binaryStochastic_REINFORCE
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def binary_wrapper(pre_activations_tensor, estimator, stochastic_tensor=tf.constant(True), pass_through=True, slope_tensor=tf.constant(1.0)): """ Turns a layer of pre-activations (logits) into a layer of binary stochastic neurons Keyword arguments: *estimator: ...
Turns a layer of pre-activations (logits) into a layer of binary stochastic neurons Keyword arguments: *estimator: either ST or REINFORCE *stochastic_tensor: a boolean tensor indicating whether to sample from a bernoulli distribution (True, default) or use a step_function (e.g., fo...
binary_wrapper
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def eval(self, batch, output_type=0, quiet=False, save_fig=False, fig_dir='./'): """ Evaluate one batch of bars according to eval_map and eval_pair Args: batch (tensor): The input tensor. output_type (int): 0 for scalar (mean of list), 1 for list quiet (bool):...
Evaluate one batch of bars according to eval_map and eval_pair Args: batch (tensor): The input tensor. output_type (int): 0 for scalar (mean of list), 1 for list quiet (bool): if true, print the values save_fig (bool): if true, plot figures and save them ...
eval
python
salu133445/musegan
v1/musegan/eval/metrics.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/eval/metrics.py
MIT
def get_placeholder(default_tensor=None, shape=None, name=None): """Return a placeholder_wirh_default if default_tensor given, otherwise a new placeholder is created and return""" if default_tensor is not None: return default_tensor else: if shape is None: raise ValueError('One o...
Return a placeholder_wirh_default if default_tensor given, otherwise a new placeholder is created and return
get_placeholder
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def batch_norm(tensor_in, apply=True): """ Apply a batch normalization layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. apply (bool): True to apply. False to bypass batch normalization. Defaults to True. Returns: tensor: The...
Apply a batch normalization layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. apply (bool): True to apply. False to bypass batch normalization. Defaults to True. Returns: tensor: The resulting tensor.
batch_norm
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def lrelu(tensor_in, alpha=0.2): """Apply a leaky ReLU layer on the input tensor and return the resulting tensor. (alpha defaults to 0.2)""" if tensor_in is not None: return tf.maximum(tensor_in, alpha*tensor_in) else: return tensor_in
Apply a leaky ReLU layer on the input tensor and return the resulting tensor. (alpha defaults to 0.2)
lrelu
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def relu(tensor_in): """Apply a ReLU layer on the input tensor and return the resulting tensor.""" if tensor_in is not None: return tf.nn.relu(tensor_in) else: return tensor_in
Apply a ReLU layer on the input tensor and return the resulting tensor.
relu
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def concat_cond_conv(x, condition=None): """Concatenate conditioning vector on feature map axis.""" if condition is None: return x else: reshape_shape = tf.stack([tf.shape(x)[0], 1, 1, condition.get_shape()[1]]) out_shape = tf.stack([tf.shape(x)[0], x.get_shape()[1], x.get_shape()[2]...
Concatenate conditioning vector on feature map axis.
concat_cond_conv
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def conv2d(tensor_in, out_channels, kernels, strides, stddev=0.02, name='conv2d', reuse=None, padding='VALID'): """ Apply a 2D convolution layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. out_channels (int): The number of output channels...
Apply a 2D convolution layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. out_channels (int): The number of output channels. kernels (list of int): The size of the kernel. [kernel_height, kernel_width] strides (list of int): T...
conv2d
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def transconv2d(tensor_in, out_shape, out_channels, kernels, strides, stddev=0.02, name='transconv2d', reuse=None, padding='VALID'): """ Apply a 2D transposed convolution layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. o...
Apply a 2D transposed convolution layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. out_shape (list of int): The output shape. [height, width] out_channels (int): The number of output channels. kernels (list of int): The size...
transconv2d
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def linear(tensor_in, output_size, stddev=0.02, bias_init=0.0, name='linear', reuse=None): """ Apply a linear layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. output_size (int): The output size. stddev (float): The value passed t...
Apply a linear layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. output_size (int): The output size. stddev (float): The value passed to the truncated normal initializer for weights. Defaults to 0.02. bias_init (float): The v...
linear
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def to_chroma_tf(bar_or_track_bar, is_normalize=True): """Return the chroma tensor of the input tensor""" out_shape = tf.stack([tf.shape(bar_or_track_bar)[0], bar_or_track_bar.get_shape()[1], 12, 7, bar_or_track_bar.get_shape()[3]]) chroma = tf.reduce_sum(tf.reshape(tf.cast(bar_or_t...
Return the chroma tensor of the input tensor
to_chroma_tf
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def to_binary_tf(bar_or_track_bar, threshold=0.0, track_mode=False, melody=False): """Return the binarize tensor of the input tensor (be careful of the channel order!)""" if track_mode: # melody track if melody: melody_is_max = tf.equal(bar_or_track_bar, tf.reduce_max(bar_or_track_ba...
Return the binarize tensor of the input tensor (be careful of the channel order!)
to_binary_tf
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def to_image_tf(tensor_in, colormap=None): """Reverse the second dimension and swap the second dimension and the third dimension""" if colormap is None: colormap = get_colormap() shape = tf.stack([-1, tensor_in.get_shape()[1], tensor_in.get_shape()[2], 3]) recolored = tf.reshape(tf.matmul(tf.res...
Reverse the second dimension and swap the second dimension and the third dimension
to_image_tf
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def get_adversarial_loss(self, discriminator, scope_to_reuse=None): """Return the adversarial losses for the generator and the discriminator.""" if self.config['gan']['type'] == 'gan': d_loss_real = tf.losses.sigmoid_cross_entropy( tf.ones_like(self.D_real.tensor_out)...
Return the adversarial losses for the generator and the discriminator.
get_adversarial_loss
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def get_statistics(self): """Return model statistics (number of paramaters for each component).""" def get_num_parameter(var_list): """Given the variable list, return the total number of parameters. """ return int(np.sum([np.product([x.value for x in var.get_shape()])...
Return model statistics (number of paramaters for each component).
get_statistics
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def get_num_parameter(var_list): """Given the variable list, return the total number of parameters. """ return int(np.sum([np.product([x.value for x in var.get_shape()]) for var in var_list]))
Given the variable list, return the total number of parameters.
get_num_parameter
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def save_statistics(self, filepath=None): """Save model statistics to file. Default to save to the log directory given as a global variable.""" if filepath is None: filepath = os.path.join(self.config['log_dir'], 'model_statistics.txt') wit...
Save model statistics to file. Default to save to the log directory given as a global variable.
save_statistics
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def save_summary(self, filepath=None): """Save model summary to file. Default to save to the log directory given as a global variable.""" if filepath is None: filepath = os.path.join(self.config['log_dir'], 'model_summary.txt') with open(filepath, 'w') as f: f.wri...
Save model summary to file. Default to save to the log directory given as a global variable.
save_summary
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def save(self, filepath=None): """Save the model to a checkpoint file. Default to save to the log directory given as a global variable.""" if filepath is None: filepath = os.path.join(self.config['checkpoint_dir'], self.name + '.model') pri...
Save the model to a checkpoint file. Default to save to the log directory given as a global variable.
save
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def load_latest(self, checkpoint_dir=None): """Load the model from the latest checkpoint in a directory.""" if checkpoint_dir is None: checkpoint_dir = self.config['checkpoint_dir'] print('[*] Loading checkpoint...') with open(os.path.join(checkpoint_dir, 'checkpoint')) as f:...
Load the model from the latest checkpoint in a directory.
load_latest
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def save_samples(self, filename, samples, save_midi=False, shape=None, postfix=None): """Save samples to an image file (and a MIDI file).""" if shape is None: shape = self.config['sample_grid'] if len(samples) > self.config['num_sample']: samples = sa...
Save samples to an image file (and a MIDI file).
save_samples
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def run_sampler(self, targets, feed_dict, save_midi=False, postfix=None): """Run the target operation with feed_dict and save the samples.""" if not isinstance(targets, list): targets = [targets] results = self.sess.run(targets, feed_dict) results = [result[:self.config['num_...
Run the target operation with feed_dict and save the samples.
run_sampler
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def build(self, config): """Build the end-to-end generator.""" nets = OrderedDict() nets['shared'] = NeuralNet(self.tensor_in, config['net_g']['shared'], name='shared') nets['pitch_time_private'] = [ NeuralNet(nets['shared'].tensor_out, ...
Build the end-to-end generator.
build
python
salu133445/musegan
v2/musegan/bmusegan/components.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/bmusegan/components.py
MIT
def get_image_grid(images, shape, grid_width=0, grid_color=0, frame=False): """ Merge the input images and return a merged grid image. Arguments --------- images : np.array, ndim=3 The image array. Shape is (num_image, height, width). shape : list or tuple of int ...
Merge the input images and return a merged grid image. Arguments --------- images : np.array, ndim=3 The image array. Shape is (num_image, height, width). shape : list or tuple of int Shape of the image grid. (height, width) grid_width : int Width of the grid lines. Def...
get_image_grid
python
salu133445/musegan
v2/musegan/utils/image_io.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/image_io.py
MIT
def save_image(filepath, phrases, shape, inverted=True, grid_width=3, grid_color=0, frame=True): """ Save a batch of phrases to a single image grid. Arguments --------- filepath : str Path to save the image grid. phrases : np.array, ndim=5 The phrase array. Shape ...
Save a batch of phrases to a single image grid. Arguments --------- filepath : str Path to save the image grid. phrases : np.array, ndim=5 The phrase array. Shape is (num_phrase, num_bar, num_time_step, num_pitch, num_track). shape : list or tuple of int Shape o...
save_image
python
salu133445/musegan
v2/musegan/utils/image_io.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/image_io.py
MIT
def get_tonal_matrix(r1=1.0, r2=1.0, r3=0.5): """Compute and return a tonal matrix for computing the tonal distance [1]. Default argument values are set as suggested by the paper. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM MM Worksho...
Compute and return a tonal matrix for computing the tonal distance [1]. Default argument values are set as suggested by the paper. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM MM Workshop on Audio and Music Computing Multimedia, 2006. ...
get_tonal_matrix
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def tonal_dist(chroma1, chroma2, tonal_matrix=None): """Return the tonal distance between two chroma features.""" if tonal_matrix is None: tonal_matrix = get_tonal_matrix() warnings.warn("`tonal matrix` not specified. Use default tonal matrix", RuntimeWarning) with warn...
Return the tonal distance between two chroma features.
tonal_dist
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def plot_histogram(hist, fig_dir=None, title=None, max_hist_num=None): """Plot the histograms of the statistics""" import matplotlib.pyplot as plt hist = hist[~np.isnan(hist)] u_value = np.unique(hist) hist_num = len(u_value) if max_hist_num is not None: if len(u_value) > max_hist_num: ...
Plot the histograms of the statistics
plot_histogram
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def print_metrics_mat(self, metrics_mat): """Print the intratrack metrics as a nice formatting table""" print(' ' * 12, ' '.join(['{:^14}'.format(metric_name) for metric_name in self.metric_names])) for t, track_name in enumerate(self.track_names): ...
Print the intratrack metrics as a nice formatting table
print_metrics_mat
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def print_metrics_pair(self, pair_matrix): """Print the intertrack metrics as a nice formatting table""" for idx, pair in enumerate(self.tonal_distance_pairs): print("{:12} {:12} {:12.5f}".format( self.track_names[pair[0]], self.track_names[pair[1]], pair_matr...
Print the intertrack metrics as a nice formatting table
print_metrics_pair
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def eval(self, bars, verbose=False, mat_path=None, fig_dir=None): """Evaluate the input bars with the metrics""" score_matrix = np.empty((len(self.metric_names), len(self.track_names), bars.shape[0])) score_matrix.fill(np.nan) score_pair_matrix = np.zeros...
Evaluate the input bars with the metrics
eval
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def eval_dataset(filepath, result_dir, location, config): """Run evaluation on a dataset stored in either shared array (if `location` is 'sa') or in hard disk (if `location` is 'hd') and save the results to the given directory. """ def load_data(filepath, location): """Load and return the t...
Run evaluation on a dataset stored in either shared array (if `location` is 'sa') or in hard disk (if `location` is 'hd') and save the results to the given directory.
eval_dataset
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def print_mat_file(mat_path, config): """Print the score matrices stored in a file.""" metrics = Metrics(config) with np.load(mat_path) as loaded: metrics.print_metrics_mat(loaded['score_matrix_mean']) metrics.print_metrics_pair(loaded['score_pair_matrix_mean'])
Print the score matrices stored in a file.
print_mat_file
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def write_midi(filepath, pianorolls, program_nums=None, is_drums=None, track_names=None, velocity=100, tempo=120.0, beat_resolution=24): """ Write the given piano-roll(s) to a single MIDI file. Arguments --------- filepath : str Path to save the MIDI file. pianorolls : np...
Write the given piano-roll(s) to a single MIDI file. Arguments --------- filepath : str Path to save the MIDI file. pianorolls : np.array, ndim=3 The piano-roll array to be written to the MIDI file. Shape is (num_timestep, num_pitch, num_track). program_nums : int or li...
write_midi
python
salu133445/musegan
v2/musegan/utils/midi_io.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/midi_io.py
MIT
def save_midi(filepath, phrases, config): """ Save a batch of phrases to a single MIDI file. Arguments --------- filepath : str Path to save the image grid. phrases : list of np.array Phrase arrays to be saved. All arrays must have the same shape. pause : int Length ...
Save a batch of phrases to a single MIDI file. Arguments --------- filepath : str Path to save the image grid. phrases : list of np.array Phrase arrays to be saved. All arrays must have the same shape. pause : int Length of pauses (in timestep) to be inserted between ph...
save_midi
python
salu133445/musegan
v2/musegan/utils/midi_io.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/midi_io.py
MIT
def stream_complete(self, stream_id: int): """ When a stream is complete, we can send our response. """ try: request_data = self.stream_data[stream_id] except KeyError: # Just return, we probably 405'd this already return headers = req...
When a stream is complete, we can send our response.
stream_complete
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
def receive_data(self, data: bytes, flow_controlled_length: int, stream_id: int): """ We've received some data on a stream. If that stream is one we're expecting data on, save it off (and account for the received amount of data in flow control so that the client can send more data). ...
We've received some data on a stream. If that stream is one we're expecting data on, save it off (and account for the received amount of data in flow control so that the client can send more data). Otherwise, reset the stream.
receive_data
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
def stream_reset(self, stream_id): """ A stream reset was sent. Stop sending data. """ if stream_id in self.flow_control_futures: future = self.flow_control_futures.pop(stream_id) future.cancel()
A stream reset was sent. Stop sending data.
stream_reset
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
async def send_data(self, data, stream_id): """ Send data according to the flow control rules. """ while data: while self.conn.local_flow_control_window(stream_id) < 1: try: await self.wait_for_flow_control(stream_id) except...
Send data according to the flow control rules.
send_data
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
async def wait_for_flow_control(self, stream_id): """ Waits for a Future that fires when the flow control window is opened. """ f = asyncio.Future() self.flow_control_futures[stream_id] = f await f
Waits for a Future that fires when the flow control window is opened.
wait_for_flow_control
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
def window_updated(self, stream_id, delta): """ A window update frame was received. Unblock some number of flow control Futures. """ if stream_id and stream_id in self.flow_control_futures: f = self.flow_control_futures.pop(stream_id) f.set_result(delta) ...
A window update frame was received. Unblock some number of flow control Futures.
window_updated
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT