Best Python code snippet using autotest_python
datapreparation.py
Source:datapreparation.py
1from __future__ import division2import numpy as np3import matplotlib.pyplot as plt4import pandas as pd5import pretty_midi6import os7import pypianoroll as pproll8import sys9import IPython10import fluidsynth11import torch12### need also to install fluidsynth to be able to synthesize midi file to audio (pip install fluidsynth)13def piano_roll_to_pretty_midi(piano_roll, fs=100, program=2):14 '''Convert a Piano Roll array into a PrettyMidi object15 with a single instrument.16 Parameters17 ----------18 piano_roll : np.ndarray, shape=(128,frames), dtype=int19 Piano roll of one instrument20 fs : int21 Sampling frequency of the columns, i.e. each column is spaced apart22 by ``1./fs`` seconds.23 program : int24 The program number of the instrument.25 Returns26 -------27 midi_object : pretty_midi.PrettyMIDI28 A pretty_midi.PrettyMIDI class instance describing29 the piano roll.30 '''31 notes, frames = piano_roll.shape32 pm = pretty_midi.PrettyMIDI()33 instrument = pretty_midi.Instrument(program=program)34 # pad 1 column of zeros so we can acknowledge inital and ending events35 piano_roll = np.pad(piano_roll, [(0, 0), (1, 1)], 'constant')36 # use changes in velocities to find note on / note off events37 velocity_changes = np.nonzero(np.diff(piano_roll).T)38 # keep track on velocities and note on times39 prev_velocities = np.zeros(notes, dtype=int)40 note_on_time = np.zeros(notes)41 for time, note in zip(*velocity_changes):42 # use time + 1 because of padding above43 velocity = piano_roll[note, time + 1]44 time = time / fs45 if velocity > 0:46 if prev_velocities[note] == 0:47 note_on_time[note] = time48 prev_velocities[note] = velocity49 else:50 pm_note = pretty_midi.Note(51 velocity=prev_velocities[note],52 pitch=note,53 start=note_on_time[note],54 end=time)55 instrument.notes.append(pm_note)56 prev_velocities[note] = 057 pm.instruments.append(instrument)58 return pm59def midfile_to_piano_roll(filepath,fs=5):60 """ convert a mid file to a piano roll matrix and saves it in a csv file61 input: path to mid file62 output: path to piano_roll csv file63 """64 pm = pretty_midi.PrettyMIDI(filepath)65 pr=pm.get_piano_roll(fs)66 df = pd.DataFrame(pr)67 df.to_csv(filepath[:-3]+"csv")68 return filepath[:-3]+"csv"69def piano_roll_to_mid_file(pianoroll_matrix,fname,fs=5):70 """ input: piano roll matrix with shape (number of notes, time steps)71 output: string with path to mid file72 """73 piano_roll_to_pretty_midi(pianoroll_matrix,fs).write(fname)74 return os.path.join(os.getcwd(),fname)75 76 77def midfile_to_piano_roll_ins(filepath,instrument_n=0,fs=5):78 """ convert mid file to piano_roll csv matrix, but selecting a specific instrument in the mid file79 input: path to mid file, intrument to select in midfile80 output: path to piano_roll csv file81 """82 pm = pretty_midi.PrettyMIDI(filepath)83 pr=pm.instruments[instrument_n].get_piano_roll(fs)84 df = pd.DataFrame(pr)85 df.to_csv(filepath[:-3]+str(instrument_n)+".csv")86 return filepath[:-3]+str(instrument_n)+".csv"87def load_all_dataset(dirpath,binarize=True):88 """ given a diretory finds all the csv in the diretory an load them as numpy arrays89 input: path a diretory90 output: list of numpy arrays91 """92 if(binarize):93 return [(pd.read_csv(os.path.join(dirpath, file)).values>0).astype(int) for file in sorted(os.listdir(dirpath)) if file.endswith(".csv")]94 else:95 return [pd.read_csv(os.path.join(dirpath, file)).values for file in sorted(os.listdir(dirpath)) if file.endswith(".csv")]96def load_all_dataset_names(dirpath):97 """ given a diretory finds all the csv in the d98iretory an split the first part99 of the name of the file to return as a tag for the associated numpy array100 input: path a diretory101 output: list of strings102 """103 return [file.split('_')[0] for file in sorted(os.listdir(dirpath)) if file.endswith(".csv")]104def get_max_length(dataset):105 """ find the maximum length of piano roll matrices in a list of matrices106 input: list of numpy 2d arrays107 output: maximun shape[1] of the list of arrays108 109 """110 return np.max([x.shape[1] for x in dataset])111def get_numkeys(dataset):112 """ return all the number of keys present in the piano roll matrices 113 (typically it should all have the same number of keys and it should be 128)114 input: list of numpy 2d arrays115 output: unique shape[0] of the list of arrays116 117 """118 return np.unique([x.shape[0] for x in dataset])119def visualize_piano_roll(pianoroll_matrix,fs=5):120 """ input: piano roll matrix with shape (number of notes, time steps)121 effect: generates a nice graph with the piano roll visualization122 """123 if(pianoroll_matrix.shape[0]==128):124 pianoroll_matrix=pianoroll_matrix.T.astype(float)125 track = pproll.Track(pianoroll=pianoroll_matrix, program=0, is_drum=False, name='piano roll') 126 # Plot the piano-roll127 fig, ax = track.plot(beat_resolution=fs)128 plt.show()129def embed_play_v1(piano_roll_matrix,fs=5):130 return IPython.display.Audio(data=piano_roll_to_pretty_midi(piano_roll_matrix,fs).synthesize(),rate=44100)131def generate_round(model,tag,n,k=1,init=None):132 if(init is None):133 init = torch.zeros(size=(k,1,model.input_size)).cuda()134 else:135 k = init.shape[0]136 res = init137 hidden = None138 for i in xrange(n//k):139 init,hidden = model.forward(init,tag,hidden)140 #init = torch.round(torch.exp(init))141 init = torch.round(init/torch.max(init))142 res = torch.cat ( ( res, init ) )143 return res144def generate_smooth(model,tag,n,init):145 res = init146 hidden = None147 for i in xrange(n):148 init_new,hidden = model.forward(init,tag,hidden)149 #init = torch.round(torch.exp(init))150 init_new = init_new[-1:]151 init_new = torch.round(init_new/torch.max(init_new))152 res = torch.cat ( ( res, init_new ) )153 init = torch.cat( (init[1:], init_new) )154 return res155def gen_music(model,length=1000,init=None,composer=0,fs=5):156 if(init is None):157 song=generate_round(model, torch.LongTensor([composer]).unsqueeze(1).cuda(),length,1)158 else:159 song=generate_round(model, torch.LongTensor([composer]).unsqueeze(1).cuda(),length,1,init)160 res = ( song.squeeze(1).detach().cpu().numpy()).astype(int).T161 visualize_piano_roll(res,fs)162 return embed_play_v1(res,fs)163def gen_music_initkeys(model,length=1000,initkeys=40,composer=0,fs=5):164 init = torch.zeros(size=(1,1,model.input_size)).cuda()165 init[0,0,initkeys]=1166 song=generate_round(model, torch.LongTensor([composer]).unsqueeze(1).cuda(),length,1,init)167 res = ( song.squeeze(1).detach().cpu().numpy()).astype(int).T168 visualize_piano_roll(res,fs)169 return embed_play_v1(res,fs)170 #return song171 172def gen_music_pianoroll(model,length=1000,init=None,composer=0,fs=5):173 if(init is None):174 song=generate_round(model, torch.LongTensor([composer]).unsqueeze(1).cuda(),length,1)175 else:176 song=generate_round(model, torch.LongTensor([composer]).unsqueeze(1).cuda(),length,1,init)177 res = ( song.squeeze(1).detach().cpu().numpy()).astype(int).T178 return res179def gen_music_seconds(model,init,composer=0,fs=5,gen_seconds=10,init_seconds=5):180 if(init is None):181 song=generate_round(model, torch.LongTensor([composer]).unsqueeze(1).cuda(),gen_seconds*fs,1)182 else:183 init_index = int(init_seconds*fs) 184 song=generate_round(model, torch.LongTensor([composer]).unsqueeze(1).cuda(),(gen_seconds-init_seconds+1)*fs,1,init[1:(init_index+1)])185 res = ( song.squeeze(1).detach().cpu().numpy()).astype(float).T186 visualize_piano_roll(res,fs)187 return embed_play_v1(res,fs)188def gen_music_seconds_smooth(model,init,composer=0,fs=5,gen_seconds=10,init_seconds=5):189 init_index = int(init_seconds*fs) 190 tag = torch.LongTensor([composer]).unsqueeze(1).cuda()191 song=generate_smooth(model,tag,(gen_seconds-init_seconds+1)*fs,init[1:(init_index+1)])192 res = ( song.squeeze(1).detach().cpu().numpy()).astype(float).T193 visualize_piano_roll(res,fs)194 return embed_play_v1(res,fs)195 196 ...
gradient_descent.py
Source:gradient_descent.py
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""4Created on Fri Nov 2 15:04:43 20185@author: vadim6"""7import random8def func(point, f):9 x, y = point10 if f == 1:11 return (1-x) ** 2 + 100 * (y - x ** 2) ** 2 # Rosenbrock12 elif f == 2:13 return (x ** 2 + y - 11) ** 2 + (x + y ** 2 - 7) ** 2 # Himmelblau14 elif f == 3:15 return (x - 4) ** 2 + y ** 216def part_x(point, f):17 x, y = point18 if f == 1:19 return -2 + 2 * x - 400 * x * y + 400 * x ** 320 elif f == 2:21 return 4 * x ** 3 + 2 * y ** 2 + 4 * x * y - 42 * x - 1422 elif f == 3:23 return 2 * x - 824 25def part_y(point, f):26 x, y = point27 if f == 1:28 return 200 * y - 200 * x ** 229 elif f == 2:30 return 4 * y ** 3 + 2 * x ** 2 + 4 * x * y - 26 * y - 2231 elif f == 3:32 return 2 * y33 34def output(point, f):35 x, y = point36 digits = 037 return 'Point: (' + str((round(x, digits), round(y, digits))) + ', F: ' + str(round(f, 0))38 39def GD(init, f, iters = 0):40 rate = 0.000001 # learning rate41 accuracy = 0.0000000000000142 x, y = init43 x_new = x - rate * part_x(init, f)44 y_new = y - rate * part_y(init, f)45 init_new = (x_new, y_new)46 if abs(func(init, f) - func(init_new, f)) < accuracy or iters > 2000:47 return init_new48 else:49 return GD(init_new, f, iters + 1)50#Rosenbrock function51init = (1.1, 1.1)52x, y = GD(init, 1)53f = func((x, y), 1)54print(output((x,y), f) + '\n')55#Himmelblau function56results = []57for _ in range(100):58 init = (random.randint(-5, 5), random.randint(-5, 5))59 x, y = GD(init, 2)60 x = round(x, 2)61 y = round(y, 2)62 results.append((x, y))63results = set(results)64for _, point in enumerate(results):65 f = func(point, 2)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!