def get_both_hands(midi_file, time_step=0.05): """ Encodes the two hands of a MIDI file and Stacks them together on horizontally Components [0:89] will be left hand And components [89:] will be right hand :param midi_file: path to the file :param time_step: Duration of each vector :return: Encoded matrix with both hands on it """ # Reads the file and encodes each hand separately hands = ms.converter.parse(midi_file) voice = False # If there is more than one voice on for idx, nt in enumerate(hands[0]): # the right hand (first part), just if type(nt) == ms.stream.Voice: # takes the first voice voice = True break if voice: right_notes = encode(hands[0][idx], time_step=time_step) else: right_notes = encode(hands[0], time_step=time_step) for idx, nt in enumerate(hands[1]): # the left hand (second part), just if type(nt) == ms.stream.Voice: # takes the first voice voice = True break if voice: left_notes = encode(hands[1][idx], time_step=time_step) else: left_notes = encode(hands[1], time_step=time_step) # Gets rid of the tempo component right_notes, left_notes = right_notes[:, :-1], left_notes[:, :-1] # Stacks both hands together both = np.empty((max([right_notes.shape[0], left_notes.shape[0]]), 178)) left, right = False, False rest_shortest = np.zeros(89) rest_shortest[87] = 1 if left_notes.shape[0] > right_notes.shape[0]: longest = np.copy(left_notes) left = True elif right_notes.shape[0] > left_notes.shape[0]: longest = np.copy(right_notes) right = True for idx in range(both.shape[0]): try: both[idx, :] = np.hstack((left_notes[idx, :], right_notes[idx, :])) except IndexError: if left: both[idx, :] = np.hstack((longest[idx, :], rest_shortest)) if right: both[idx, :] = np.hstack((rest_shortest, longest[idx, :])) return both
def get_right_hand(midi_file, time_step=0.05): hands = ms.converter.parse(midi_file) voice = False # If there is more than one voice on for idx, nt in enumerate(hands[0]): # the right hand (first part), just if type(nt) == ms.stream.Voice: # takes the first voice voice = True break if voice: right_notes = encode(hands[0][idx], time_step=time_step) else: right_notes = encode(hands[0], time_step=time_step) return right_notes
def multi_many_hot_encode(midi_file): """ Multi-many-hot-encodes two hands """ hands = ms.converter.parse(midi_file) voice = False # If there is more than one voice on for idx, nt in enumerate(hands[0]): # the right hand (first part), just if type(nt) == ms.stream.Voice: # takes the first voice voice = True break if voice: right_notes = encode(hands[0][idx]) else: right_notes = encode(hands[0]) voice = False # And the same for the left hand for idx, nt in enumerate(hands[1]): if type(nt) == ms.stream.Voice: voice = True break if voice: left_notes = encode(hands[1][idx]) else: left_notes = encode(hands[1]) # Combines both encoded hands if right_notes.shape >= left_notes.shape: notes_combined = np.zeros(right_notes.shape) for idx, left_note in enumerate(left_notes): notes_combined[idx] = left_note notes_combined += right_notes else: notes_combined = np.zeros(left_notes.shape) for idx, right_note in enumerate(right_notes): notes_combined[idx] = right_note notes_combined += left_notes # In case there is a rest or a hold # on both hands at the same time for idx, nt in enumerate(notes_combined): if nt[88] == 2: notes_combined[idx][88] = 1 if nt[87] == 2: notes_combined[idx][87] = 1 return notes_combined
def get_right_hand(midi_file, time_step=0.05): """ Gets the encoded right hand of a midi file :param midi_file: path to the file :param time_step: Duration of each vector :return: Encoded right hand without the tempo """ hands = ms.converter.parse(midi_file) voice = False # If there is more than one voice on for idx, nt in enumerate(hands[0]): # the right hand (first part), just if type(nt) == ms.stream.Voice: # takes the first voice voice = True break if voice: right_notes = encode(hands[0][idx], time_step=time_step) else: right_notes = encode(hands[0], time_step=time_step) return right_notes[:, :-1]
def encode_solutions(file): locations = [] orders = [] outputs = np.genfromtxt('./data/y_raw.csv', delimiter=',') for index, permutation in enumerate(outputs): print(f'Encoding solution {index + 1}') encoded = encode(permutation[:-1].astype('int')) with open('./data/y_encoded.csv', 'a', newline = '') as csvfile: writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) writer.writerow(np.append(encoded, permutation[-1]))
def train(protein,clf,dim_red=None,encoding=False,single_frame=False): ''' Args: - protein: "bpti" or "alanine", name of the protein - clf: classifier to use - dim_red: int or None. if not None, it's the reduced dimension for PCA - encode: if False, classify on coordinates; if True, classify on encoded hidden states - single_frame: classify as single frames or sequences. ''' # get features if encoding==False: # get flattened coordinates of each frame traj = dr.load_traj(protein) coords = traj.xyz coords = np.reshape(coords,(len(coords),-1)) X = coords # print coords else: # get encoded hidden states X = encode() # use PCA to reduce dimension if dim_red != None: pca = PCA(dim_red) X = pca.fit(X).transform(X) # print X[0] # get labels with open("/output/"+protein+"/labels"+suffix,"r") as lb: # with open("/protein/data/"+protein+"-labels"+suffix) as lb: Y = np.asarray(pickle.load(lb)) if encoding==True and single_frame==True: # need to match the number of sequences end = -seq_size*window_size+1 if end == 0: end = Y.size Y = Y[0:end:sliding*window_size] # compare with the first frame # Y = Y[-end::sliding*window_size] # compare with the last frame # print Y # training and cross validation data_scores = cross_val_score(clf,X,Y,cv=int(fold)) print("Accuracy with %s folds: %0.2f (+/- %0.2f)" % (fold, data_scores.mean(), data_scores.std()))
import music21 as ms from encoder_decoder import encode def combine(left, right, filepath='test.mid'): """ Input: left - the stream of notes played by the pianist with his left hand right - the stream of notes played by the pianist with his right hand filepath - path to the file in which o/p midi stream is to be stored Output: N/A The combines the streams from the left stream and right stream and outputs a single stream object """ sc = ms.stream.Stream() sc.append(right) sc.append(left) left.offset = 0.0 sc.write("midi", filepath) <<<<<<< HEAD return encode(sc) ======= >>>>>>> a701de4d8db7678434481736b05f2e4d15101c57
# Get Threat coeff. from input for k in range(noftargets): threat_list.append(int(input())) #print(threat_coeff) # Initializing probability matrix prob_matrix = [] print("Enter Success probability matrix : ") for i in range(0, len(weapon_names)): a = [] for j in range(0, noftargets): a.append(float(input())) prob_matrix.append(a) # Encoding Dictionary enc = ed.encode(weapon_names, weapon_instances) best_chrom = [] best_sol = sum(threat_list) # Main Loop for f in range(50): m.initialize(chrom_list, 5, sum(weapon_instances)) #print("hromList: "+str(chrom_list)) assign_all = m.assigne_all(chrom_list, threat_list) #print ("Assign All : " + str(assign_all)) selected_chroms = m.select(assign_all, threat_list, enc, weapon_names, prob_matrix)
import numpy as np import encoder_decoder #this is success probability matrix and it's valid only for 3-types of weapons and 3 targets probability_matrix = [[0.3, 0.6, 0.5], [0.4, 0.5, 0.4], [0.1, 0.2, 0.2]] weapons_type = ['tank', 'aircraft', 'grenade'] enc = encoder_decoder.encode(weapons_type, [2, 1, 2]) #the chrom size is equal to sum of weapons inctances def initialize(List, List_size, chrom_size): for i in range(List_size): arr = np.random.randint(0, 2, chrom_size) #this if statment in case the generated array is full of zeros which is wrong cuz this solution will not reduce the total threat if not arr.__contains__(1): i -= 1 continue List.append(arr) #this function is to assigne each inctance of the weapons to a specific target via roulette wheel #it returns a dictionary with keys are the weapon type and number and the value is the assigned target def assigne(List, threat_list): dictionary = {} Sum = sum(threat_list) wheel_range = [x / Sum for x in threat_list] for i in range(len(List)): if List[i] == 0: #dictionary.update({'weapon #'+str((i+1)):'not assigned'})
import numpy as np import crossover as c import encoder_decoder as ed channels_list = [] # List of channels names channels_ROI = [] # List of channels of roi to be transformed into % chrom_list = [] # population list lu_list = [] # lower and upper list budget = int(input("Enter the Marketing budget in thousands : \n")) Nofchannels = int(input("Enter The number of marketing channels : \n")) for _ in range(Nofchannels): c_name, c_value = input("Enter name and ROI of each channel : \n").split( " ") channels_list.append(c_name) channels_ROI.append(c_value) for __ in range(Nofchannels): l, u = input( "Enter the lower (k) and upper bounds (%) of investment in each channel:\n(enter x if there is no bound)\n" ).split(" ") if (l != "x"): lu_list.append((float((float(l) * 1000) / (budget * 1000) * 100), u)) else: lu_list.append((l, u)) print(ed.encode(channels_list)) print(ed.decode(3))