language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
Python
def decode_arrangement(self, solution) -> pd.DataFrame: """take an arrangement of ensemble indeces and translate to suppliers""" sol = {} for i, idx in enumerate(solution): cardname = self.keys[i] config = self.ensembles[i][idx] sol[cardname] = self.suppliers[i].get_suppliers_from_config(config) #turn dict into DataFrame headers = ['supplier', 'cardname', 'cost', 'url'] entries = [] for key in sol: card = key for supplier, cost, url in sol[key]: entries.append([supplier, card, cost, url]) return pd.DataFrame(entries, columns = headers)
def decode_arrangement(self, solution) -> pd.DataFrame: """take an arrangement of ensemble indeces and translate to suppliers""" sol = {} for i, idx in enumerate(solution): cardname = self.keys[i] config = self.ensembles[i][idx] sol[cardname] = self.suppliers[i].get_suppliers_from_config(config) #turn dict into DataFrame headers = ['supplier', 'cardname', 'cost', 'url'] entries = [] for key in sol: card = key for supplier, cost, url in sol[key]: entries.append([supplier, card, cost, url]) return pd.DataFrame(entries, columns = headers)
Python
def _parse_cod(filename) -> CardList: """Parse .COD filetypes (cockatric format .xml) Imports all cards anywhere in the deck """ import xml.etree.ElementTree as et xtree = et.parse(filename) xroot = xtree.getroot() xcards = xroot.findall('.//card') #find all cards in tree card_names = [] card_numbers = [] #get card name and number of cards and append to list for xcard in xcards: card_numbers.append(int(xcard.attrib.get('number'))) card_names.append(xcard.attrib.get('name')) #turn list of cards into dataframe data = {'Name': card_names, 'Number': card_numbers} return(CardList(data))
def _parse_cod(filename) -> CardList: """Parse .COD filetypes (cockatric format .xml) Imports all cards anywhere in the deck """ import xml.etree.ElementTree as et xtree = et.parse(filename) xroot = xtree.getroot() xcards = xroot.findall('.//card') #find all cards in tree card_names = [] card_numbers = [] #get card name and number of cards and append to list for xcard in xcards: card_numbers.append(int(xcard.attrib.get('number'))) card_names.append(xcard.attrib.get('name')) #turn list of cards into dataframe data = {'Name': card_names, 'Number': card_numbers} return(CardList(data))
Python
def generate_random(self, N): """generate random population of size N""" population = [] for i in range(N): ensemble = [randint(0, upper_limit) for upper_limit in self.bounds] population.append(ensemble) return np.array(population)
def generate_random(self, N): """generate random population of size N""" population = [] for i in range(N): ensemble = [randint(0, upper_limit) for upper_limit in self.bounds] population.append(ensemble) return np.array(population)
Python
def run(self, num_iterations = 50, **kwargs): """run the genetic algorithm to find the optimal card arrangement. The genetic algorithm object will be stored as self.model.""" #setup system self.cost_calculator = t.CostCalculator(self.suppliers_allcards, self.all_ensembles_dict) bounds = np.array(self.cost_calculator.ensemble_sizes) - 1 #define cost functions cost_func = lambda p: sum(self.cost_calculator.get_cost(p)) #create model self.model = ga(cost_func, bounds, **kwargs) fitness_list = []; for i in range(num_iterations): #Update f = next(self.model) #get fitness values fitness_list.append(f[0]) #Output print('\r(%d/%d) '%(i+1,num_iterations), end = '') print('top ensemble fitness: %1.1f '%f[0], end = '') print('\nDone') self.solution = self.cost_calculator.decode_arrangement(self.model.get_solution())
def run(self, num_iterations = 50, **kwargs): """run the genetic algorithm to find the optimal card arrangement. The genetic algorithm object will be stored as self.model.""" #setup system self.cost_calculator = t.CostCalculator(self.suppliers_allcards, self.all_ensembles_dict) bounds = np.array(self.cost_calculator.ensemble_sizes) - 1 #define cost functions cost_func = lambda p: sum(self.cost_calculator.get_cost(p)) #create model self.model = ga(cost_func, bounds, **kwargs) fitness_list = []; for i in range(num_iterations): #Update f = next(self.model) #get fitness values fitness_list.append(f[0]) #Output print('\r(%d/%d) '%(i+1,num_iterations), end = '') print('top ensemble fitness: %1.1f '%f[0], end = '') print('\nDone') self.solution = self.cost_calculator.decode_arrangement(self.model.get_solution())
Python
def plot_results(self): """create bar-chart of suppliers with num_cards and cost per supplier""" #get data new_df = self.solution.groupby('supplier').sum() new_df['count'] = self.solution.groupby('supplier').supplier.count() new_df = new_df.sort_values(by=['count'], ascending = False) #plotting ax = new_df.plot.bar(secondary_y = 'cost', rot=90) ax.legend(loc='upper left', bbox_to_anchor=(0., 1.11, 1., .102)) ax.right_ax.legend(loc='upper right', bbox_to_anchor=(0., 1.11, 1., .102)) ax.set_ylabel('count') ax.set_xlabel('supplier name') ax.right_ax.set_ylabel('cost') plt.tight_layout()
def plot_results(self): """create bar-chart of suppliers with num_cards and cost per supplier""" #get data new_df = self.solution.groupby('supplier').sum() new_df['count'] = self.solution.groupby('supplier').supplier.count() new_df = new_df.sort_values(by=['count'], ascending = False) #plotting ax = new_df.plot.bar(secondary_y = 'cost', rot=90) ax.legend(loc='upper left', bbox_to_anchor=(0., 1.11, 1., .102)) ax.right_ax.legend(loc='upper right', bbox_to_anchor=(0., 1.11, 1., .102)) ax.set_ylabel('count') ax.set_xlabel('supplier name') ax.right_ax.set_ylabel('cost') plt.tight_layout()
Python
def evaluate(individual): ''' Evaluate the individual proposed by evolution for fitness, via the simplified cmdline tool interface. This function marshalls in all the parameters, calls out to the cmdline tool, and fetches the returned fitness information To tailor the genetic search for your particular problem and dataset, duplicate 'fn_mackey_glass.py', and customise it, then save and rename it, ensuring it can run from the examples directory. Then reinstall to activate it. Once it's ready to go, you can call "fn_autotune" with the name of your new cmdline function as a parameter, so it's executed here and is finding optimal parameters for your own data pipeline. ''' # make sure we are working in the examples directory, from where we can call the cmdline tools. os.chdir('/home/andrew/pytorch-esn/examples') # extract the values for the parameters from the individual chromosome my_input_size = individual[0] #ok my_output_size = individual[1] #ok my_batch_first = individual[2] #ok my_hidden_size = individual[3] #ok my_num_layers = individual[4] #ok my_nonlinearity = individual[5] #ok my_leaking_rate = individual[6] #ok my_spectral_radius = individual[7] #ok my_w_io = individual[8] #ok my_w_ih_scale = individual[9] #ok my_density = individual[10] #ok my_lambda_reg = individual[11] #ok my_readout_training = individual[12] #ok my_output_steps = individual[13] #ok my_cmdline_tool = individual[14] #ok my_dataset = individual[15] # for now only fn_mackey_glass is configured # construct the command line to run the individual using the cmdline fn runstring = my_cmdline_tool + " --dataset " + my_dataset + " --input_size " + str(my_input_size) + " --output_size " + str(my_output_size) + " --batch_first " + str(my_batch_first) + " --hidden_size " + str(my_hidden_size) + " --num_layers " + str(my_num_layers) + " --leaking_rate " + str(my_leaking_rate) + " --spectral_radius " + str(my_spectral_radius) + " --nonlinearity " + str(my_nonlinearity) + " --w_io " + str(my_w_io) + " --w_ih_scale " + str(my_w_ih_scale) + " --lambda_reg " + str(my_lambda_reg) + " --density " + str(my_density) + " --readout_training " + str(my_readout_training) + " --output_steps " + str(my_output_steps) + " --auto true" + " --seed 10" #result = subprocess.run(runstring, stdout=subprocess.PIPE) try: stream = os.popen(runstring) result = stream.read() except: result = "123456.12345 123456.12345" # I'm forcing the failed call to have bad fitness, and push on with the learning # add in my new function here as so # Test try: test_mse = float(result.split(" ")[0]) duration = float(result.split(" ")[1]) except: test_mse = float(123456.12345) duration = float(123456.12345) #print(runstring, " # test_error: ", test_mse," # eval_duration: ", duration) return test_mse, duration
def evaluate(individual): ''' Evaluate the individual proposed by evolution for fitness, via the simplified cmdline tool interface. This function marshalls in all the parameters, calls out to the cmdline tool, and fetches the returned fitness information To tailor the genetic search for your particular problem and dataset, duplicate 'fn_mackey_glass.py', and customise it, then save and rename it, ensuring it can run from the examples directory. Then reinstall to activate it. Once it's ready to go, you can call "fn_autotune" with the name of your new cmdline function as a parameter, so it's executed here and is finding optimal parameters for your own data pipeline. ''' # make sure we are working in the examples directory, from where we can call the cmdline tools. os.chdir('/home/andrew/pytorch-esn/examples') # extract the values for the parameters from the individual chromosome my_input_size = individual[0] #ok my_output_size = individual[1] #ok my_batch_first = individual[2] #ok my_hidden_size = individual[3] #ok my_num_layers = individual[4] #ok my_nonlinearity = individual[5] #ok my_leaking_rate = individual[6] #ok my_spectral_radius = individual[7] #ok my_w_io = individual[8] #ok my_w_ih_scale = individual[9] #ok my_density = individual[10] #ok my_lambda_reg = individual[11] #ok my_readout_training = individual[12] #ok my_output_steps = individual[13] #ok my_cmdline_tool = individual[14] #ok my_dataset = individual[15] # for now only fn_mackey_glass is configured # construct the command line to run the individual using the cmdline fn runstring = my_cmdline_tool + " --dataset " + my_dataset + " --input_size " + str(my_input_size) + " --output_size " + str(my_output_size) + " --batch_first " + str(my_batch_first) + " --hidden_size " + str(my_hidden_size) + " --num_layers " + str(my_num_layers) + " --leaking_rate " + str(my_leaking_rate) + " --spectral_radius " + str(my_spectral_radius) + " --nonlinearity " + str(my_nonlinearity) + " --w_io " + str(my_w_io) + " --w_ih_scale " + str(my_w_ih_scale) + " --lambda_reg " + str(my_lambda_reg) + " --density " + str(my_density) + " --readout_training " + str(my_readout_training) + " --output_steps " + str(my_output_steps) + " --auto true" + " --seed 10" #result = subprocess.run(runstring, stdout=subprocess.PIPE) try: stream = os.popen(runstring) result = stream.read() except: result = "123456.12345 123456.12345" # I'm forcing the failed call to have bad fitness, and push on with the learning # add in my new function here as so # Test try: test_mse = float(result.split(" ")[0]) duration = float(result.split(" ")[1]) except: test_mse = float(123456.12345) duration = float(123456.12345) #print(runstring, " # test_error: ", test_mse," # eval_duration: ", duration) return test_mse, duration
Python
def send_mattermost(): """Send report message to mattermost.""" message = get_crawler_report() webhook_url = 'https://chat.buygta.today/hooks/zbr8kctkytnebk76pcrshyysba' requests.post(webhook_url, json={'text': message})
def send_mattermost(): """Send report message to mattermost.""" message = get_crawler_report() webhook_url = 'https://chat.buygta.today/hooks/zbr8kctkytnebk76pcrshyysba' requests.post(webhook_url, json={'text': message})
Python
def add_lines(image_array, xys, width=1, weights=None): """ Add a set of lines (xys) to an existing image_array width: width of lines weights: [], optional list of multipliers for lines. """ for i, xy in enumerate(xys): # loop over lines # create a new gray scale image image = Image.new("L", (image_array.shape[1], image_array.shape[0])) # draw the line ImageDraw.Draw(image).line(xy, 200, width=width) # convert to array new_image_array = np.asarray(image, dtype=np.uint8).astype(float) # apply weights if provided if weights is not None: new_image_array *= weights[i] # add to existing array image_array += new_image_array # convolve image new_image_array = scipy.ndimage.filters.convolve(image_array, get_kernel(width * 4)) return new_image_array
def add_lines(image_array, xys, width=1, weights=None): """ Add a set of lines (xys) to an existing image_array width: width of lines weights: [], optional list of multipliers for lines. """ for i, xy in enumerate(xys): # loop over lines # create a new gray scale image image = Image.new("L", (image_array.shape[1], image_array.shape[0])) # draw the line ImageDraw.Draw(image).line(xy, 200, width=width) # convert to array new_image_array = np.asarray(image, dtype=np.uint8).astype(float) # apply weights if provided if weights is not None: new_image_array *= weights[i] # add to existing array image_array += new_image_array # convolve image new_image_array = scipy.ndimage.filters.convolve(image_array, get_kernel(width * 4)) return new_image_array
Python
def to_image(array, hue=.62): """converts an array of floats to an array of RGB values using a colormap""" # apply saturation function image_data = np.log(array + 1) # create colormap, change these values to adjust to look of your plot saturation_values = [[0, 0], [1, .68], [.78, .87], [0, 1]] colors = [hsv_to_rgb([hue, x, y]) for x, y in saturation_values] cmap = LinearSegmentedColormap.from_list("my_colormap", colors) # apply colormap out = cmap(image_data / image_data.max()) # convert to 8-bit unsigned integer out = (out * 255).astype(np.uint8) return out # Convert Latitude and Longitude to Pixel Coordinates
def to_image(array, hue=.62): """converts an array of floats to an array of RGB values using a colormap""" # apply saturation function image_data = np.log(array + 1) # create colormap, change these values to adjust to look of your plot saturation_values = [[0, 0], [1, .68], [.78, .87], [0, 1]] colors = [hsv_to_rgb([hue, x, y]) for x, y in saturation_values] cmap = LinearSegmentedColormap.from_list("my_colormap", colors) # apply colormap out = cmap(image_data / image_data.max()) # convert to 8-bit unsigned integer out = (out * 255).astype(np.uint8) return out # Convert Latitude and Longitude to Pixel Coordinates
Python
def row_to_pixel(row, image_shape): """ convert a row (1 trip) to pixel coordinates of start and end point """ start_y, start_x = latlon_to_pixel(row["s_lat"], row["s_lng"], image_shape) end_y, end_x = latlon_to_pixel(row["e_lat"], row["e_lng"], image_shape) xy = (start_x, start_y, end_x, end_y) return xy
def row_to_pixel(row, image_shape): """ convert a row (1 trip) to pixel coordinates of start and end point """ start_y, start_x = latlon_to_pixel(row["s_lat"], row["s_lng"], image_shape) end_y, end_x = latlon_to_pixel(row["e_lat"], row["e_lng"], image_shape) xy = (start_x, start_y, end_x, end_y) return xy
Python
def add_alpha(image_data): """ Uses the Value in HSV as an alpha channel. This creates an image that blends nicely with a black background. """ # get hsv image hsv = rgb_to_hsv(image_data[:, :, :3].astype(float) / 255) # create new image and set alpha channel new_image_data = np.zeros(image_data.shape) new_image_data[:, :, 3] = hsv[:, :, 2] # set value of hsv image to either 0 or 1. hsv[:, :, 2] = np.where(hsv[:, :, 2] > 0, 1, 0) # combine alpha and new rgb new_image_data[:, :, :3] = hsv_to_rgb(hsv) return new_image_data
def add_alpha(image_data): """ Uses the Value in HSV as an alpha channel. This creates an image that blends nicely with a black background. """ # get hsv image hsv = rgb_to_hsv(image_data[:, :, :3].astype(float) / 255) # create new image and set alpha channel new_image_data = np.zeros(image_data.shape) new_image_data[:, :, 3] = hsv[:, :, 2] # set value of hsv image to either 0 or 1. hsv[:, :, 2] = np.where(hsv[:, :, 2] > 0, 1, 0) # combine alpha and new rgb new_image_data[:, :, :3] = hsv_to_rgb(hsv) return new_image_data
Python
def to_image(array, hue=.62): """converts an array of floats to an array of RGB values using a colormap""" # apply saturation function image_data = np.log(array + 1) # create colormap, change these values to adjust to look of your plot saturation_values = [[0, 0], [.75, .68], [.78, .87], [0, 1]] colors = [hsv_to_rgb([hue, x, y]) for x, y in saturation_values] cmap = LinearSegmentedColormap.from_list("my_colormap", colors) # apply colormap out = cmap(image_data / image_data.max()) # convert to 8-bit unsigned integer out = (out * 255).astype(np.uint8) return out
def to_image(array, hue=.62): """converts an array of floats to an array of RGB values using a colormap""" # apply saturation function image_data = np.log(array + 1) # create colormap, change these values to adjust to look of your plot saturation_values = [[0, 0], [.75, .68], [.78, .87], [0, 1]] colors = [hsv_to_rgb([hue, x, y]) for x, y in saturation_values] cmap = LinearSegmentedColormap.from_list("my_colormap", colors) # apply colormap out = cmap(image_data / image_data.max()) # convert to 8-bit unsigned integer out = (out * 255).astype(np.uint8) return out
Python
def row_to_pixel(row, image_shape, columns=None): """ convert a row (1 trip) to pixel coordinates of start and end point """ start_y, start_x = latlon_to_pixel(row["s_lat"], row["s_lng"], image_shape) end_y, end_x = latlon_to_pixel(row["e_lat"], row["e_lng"], image_shape) xy = (start_x, start_y, end_x, end_y) return xy
def row_to_pixel(row, image_shape, columns=None): """ convert a row (1 trip) to pixel coordinates of start and end point """ start_y, start_x = latlon_to_pixel(row["s_lat"], row["s_lng"], image_shape) end_y, end_x = latlon_to_pixel(row["e_lat"], row["e_lng"], image_shape) xy = (start_x, start_y, end_x, end_y) return xy
Python
def add_alpha(image_data): """ Uses the Value in HSV as an alpha channel. This creates an image that blends nicely with a black background. """ # get hsv image hsv = rgb_to_hsv(image_data[:, :, :3].astype(float) / 255) # create new image and set alpha channel new_image_data = np.zeros(image_data.shape) new_image_data[:, :, 3] = hsv[:, :, 2] # set value of hsv image to either 0 or 1. hsv[:, :, 2] = np.where(hsv[:, :, 2] > 0, 1, 0) # combine alpha and new rgb new_image_data[:, :, :3] = hsv_to_rgb(hsv) return new_image_data
def add_alpha(image_data): """ Uses the Value in HSV as an alpha channel. This creates an image that blends nicely with a black background. """ # get hsv image hsv = rgb_to_hsv(image_data[:, :, :3].astype(float) / 255) # create new image and set alpha channel new_image_data = np.zeros(image_data.shape) new_image_data[:, :, 3] = hsv[:, :, 2] # set value of hsv image to either 0 or 1. hsv[:, :, 2] = np.where(hsv[:, :, 2] > 0, 1, 0) # combine alpha and new rgb new_image_data[:, :, :3] = hsv_to_rgb(hsv) return new_image_data
Python
def spectrogram(audio, nfft=256, fs=8000, noverlap=32): """Computes the spectrogram of an audio sample. Computes the spectrogram of an audio sample using the power spectral density. The scale used for frequency axis is dB power (10 * log10). In this project spectrograms are used as input x to recurrent neural nets. Args: audio (numpy.ndarray): The audio sample data as 1D array. If 2D, only the first channel is processed (ie audio[0]). nfft (int): Lenght of FFT window for the computation of a spectrogram timestep. Better be a power of 2 for efficiency reasons. fs (int): The sampling frequency (samples per time unit). noverlap (int): Overlap between adjacent windows. Returns: numpy.ndarray: The spectrogram. It is 2D: first dimension is time (timesteps), the second one is the frequency. """ data = audio if audio.ndim==1 else audio[:,0] # working on the first channel only spec, f, t = mlab.specgram(data, nfft, fs, noverlap = noverlap) return spec.T.astype(np.float32)
def spectrogram(audio, nfft=256, fs=8000, noverlap=32): """Computes the spectrogram of an audio sample. Computes the spectrogram of an audio sample using the power spectral density. The scale used for frequency axis is dB power (10 * log10). In this project spectrograms are used as input x to recurrent neural nets. Args: audio (numpy.ndarray): The audio sample data as 1D array. If 2D, only the first channel is processed (ie audio[0]). nfft (int): Lenght of FFT window for the computation of a spectrogram timestep. Better be a power of 2 for efficiency reasons. fs (int): The sampling frequency (samples per time unit). noverlap (int): Overlap between adjacent windows. Returns: numpy.ndarray: The spectrogram. It is 2D: first dimension is time (timesteps), the second one is the frequency. """ data = audio if audio.ndim==1 else audio[:,0] # working on the first channel only spec, f, t = mlab.specgram(data, nfft, fs, noverlap = noverlap) return spec.T.astype(np.float32)
Python
def normalize_volume(audio, dBFS=-15): """Normalizes the volume of an audio clip. Normalizes the amplitude of and audio clip to match a specified value of decibels relative to full scale. Args: audio (pydub AudioSegment): The audio clip to be normalized. dBFS (int): the desired decibel of ratio between root mean squared amplitude of the audio and the max possible amplitude. Returns: pydub.AudioSegment: The normalized audio clip """ delta = dBFS - audio.dBFS return audio.apply_gain(delta)
def normalize_volume(audio, dBFS=-15): """Normalizes the volume of an audio clip. Normalizes the amplitude of and audio clip to match a specified value of decibels relative to full scale. Args: audio (pydub AudioSegment): The audio clip to be normalized. dBFS (int): the desired decibel of ratio between root mean squared amplitude of the audio and the max possible amplitude. Returns: pydub.AudioSegment: The normalized audio clip """ delta = dBFS - audio.dBFS return audio.apply_gain(delta)
Python
def detect_leading_silence(audio, silence_threshold=-27.0, chunk_size=10): '''Detects leading silence in an audio clip. Iterates chunck by chunck from the beginning of the audioclip, until finding the first one with volume above threshold. Args: audio (pydub AudioSegment): The audio clip. silence_threshold (int): the volume threshold in dB wrt full scale defining the silence. chunk_size (int): lenght in ms of audio chuncks tested for silence. Returns: int: the millisecond since the beginning of audio clip where initial silence ends ''' trim_ms = 0 # ms chunk_size = int(max(chunk_size,1)) while True: #print(sound[trim_ms:trim_ms+chunk_size].dBFS) if audio[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold and trim_ms < len(audio): trim_ms += chunk_size else: break return trim_ms
def detect_leading_silence(audio, silence_threshold=-27.0, chunk_size=10): '''Detects leading silence in an audio clip. Iterates chunck by chunck from the beginning of the audioclip, until finding the first one with volume above threshold. Args: audio (pydub AudioSegment): The audio clip. silence_threshold (int): the volume threshold in dB wrt full scale defining the silence. chunk_size (int): lenght in ms of audio chuncks tested for silence. Returns: int: the millisecond since the beginning of audio clip where initial silence ends ''' trim_ms = 0 # ms chunk_size = int(max(chunk_size,1)) while True: #print(sound[trim_ms:trim_ms+chunk_size].dBFS) if audio[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold and trim_ms < len(audio): trim_ms += chunk_size else: break return trim_ms
Python
def trim_audio_sample(audio, silence_threshold=-27.0): """Trims an audio clip removing silences at the beginning and at the end. Args: audio (pydub AudioSegment): The audio clip. silence_threshold (int): the volume threshold in dB wrt full scale defining the silence. Returns: pydub.AudioSegment: trimmed audio clip """ start_trim = detect_leading_silence(audio,silence_threshold) end_trim = detect_leading_silence(audio.reverse(),silence_threshold) duration = len(audio) #print(start_trim, end_trim, duration) trimmed_audio = audio[start_trim:duration-end_trim] return trimmed_audio
def trim_audio_sample(audio, silence_threshold=-27.0): """Trims an audio clip removing silences at the beginning and at the end. Args: audio (pydub AudioSegment): The audio clip. silence_threshold (int): the volume threshold in dB wrt full scale defining the silence. Returns: pydub.AudioSegment: trimmed audio clip """ start_trim = detect_leading_silence(audio,silence_threshold) end_trim = detect_leading_silence(audio.reverse(),silence_threshold) duration = len(audio) #print(start_trim, end_trim, duration) trimmed_audio = audio[start_trim:duration-end_trim] return trimmed_audio
Python
def load_audio_files(folder_name, dBFS_norm=-15, dBFS_min=-28, dBFS_max=-15, clip_start_ms=0, clip_end_ms=0): """Load audio all audio files from a folder, recursively. The entire folder subtree is explored and all audio files are loaded as pydub.AudioSegment. Actually this functions tries to load all files, so that basically each ffmpeg supported audio file type will be correctly loaded. As a consequence of trying to load all files, if non audio files are in the folder subtree, for each an error will be logged to console. This does not compromise the success of the function. A number of filters is applied to each audioclip: - If frame rate is different from 44100Hz, the audioclip is resampled at this frequency. - Volume normalization. - Optional removal a fixed lenght head and tail. - Automated trimming of heading and trailing silence. Args: folder_name (str): Folder to search for audio files. dBFS_norm (int): Full scale dB level for volume normalization or None not to normalize. dBFS_min (int): Ignored if dBFS_norm is not None. Else, if the volume level is lower than this threshold, it is amplified to this level. dBFS_max (int): Ignored if dBFS_norm is not None. Else, if the volume level is higher than this threshold, it is normalized to this level. clip_start_ms (int): length in ms of chunck to be removed from audioclips head. clip_end_ms (int): length in ms of chunck to be removed from audioclips tail. Returns: list of pydub.AudioSegment: loaded audio clips """ if not os.path.isdir(folder_name): raise FileNotFoundError('folder does not exist') segments = [] clip_start_ms = max(int(clip_start_ms),0) clip_end_ms = max(int(clip_end_ms),0) for f in util.list_file_recursive(folder_name): #if f.endswith(".wav") or f.endswith(".mp3") or f.endswith(".flac") or f.endswith(".ogg"): try: s = AudioSegment.from_file(f) s = s.set_frame_rate(44100) if dBFS_norm is not None: s = normalize_volume(s,dBFS_norm) elif dBFS_min is not None and s.dBFS < dBFS_min: s = normalize_volume(s,dBFS_min) elif dBFS_max is not None and s.dBFS > dBFS_max: s = normalize_volume(s,dBFS_max) if clip_start_ms==0 and clip_end_ms==0: pass elif clip_end_ms==0: s = s[clip_start_ms:] else: s = s[clip_start_ms:-clip_end_ms] s = trim_audio_sample(s,silence_threshold=-27) segments.append(s) except Exception as e: print("Info: failed to load file: " + f) raise e return segments
def load_audio_files(folder_name, dBFS_norm=-15, dBFS_min=-28, dBFS_max=-15, clip_start_ms=0, clip_end_ms=0): """Load audio all audio files from a folder, recursively. The entire folder subtree is explored and all audio files are loaded as pydub.AudioSegment. Actually this functions tries to load all files, so that basically each ffmpeg supported audio file type will be correctly loaded. As a consequence of trying to load all files, if non audio files are in the folder subtree, for each an error will be logged to console. This does not compromise the success of the function. A number of filters is applied to each audioclip: - If frame rate is different from 44100Hz, the audioclip is resampled at this frequency. - Volume normalization. - Optional removal a fixed lenght head and tail. - Automated trimming of heading and trailing silence. Args: folder_name (str): Folder to search for audio files. dBFS_norm (int): Full scale dB level for volume normalization or None not to normalize. dBFS_min (int): Ignored if dBFS_norm is not None. Else, if the volume level is lower than this threshold, it is amplified to this level. dBFS_max (int): Ignored if dBFS_norm is not None. Else, if the volume level is higher than this threshold, it is normalized to this level. clip_start_ms (int): length in ms of chunck to be removed from audioclips head. clip_end_ms (int): length in ms of chunck to be removed from audioclips tail. Returns: list of pydub.AudioSegment: loaded audio clips """ if not os.path.isdir(folder_name): raise FileNotFoundError('folder does not exist') segments = [] clip_start_ms = max(int(clip_start_ms),0) clip_end_ms = max(int(clip_end_ms),0) for f in util.list_file_recursive(folder_name): #if f.endswith(".wav") or f.endswith(".mp3") or f.endswith(".flac") or f.endswith(".ogg"): try: s = AudioSegment.from_file(f) s = s.set_frame_rate(44100) if dBFS_norm is not None: s = normalize_volume(s,dBFS_norm) elif dBFS_min is not None and s.dBFS < dBFS_min: s = normalize_volume(s,dBFS_min) elif dBFS_max is not None and s.dBFS > dBFS_max: s = normalize_volume(s,dBFS_max) if clip_start_ms==0 and clip_end_ms==0: pass elif clip_end_ms==0: s = s[clip_start_ms:] else: s = s[clip_start_ms:-clip_end_ms] s = trim_audio_sample(s,silence_threshold=-27) segments.append(s) except Exception as e: print("Info: failed to load file: " + f) raise e return segments
Python
def extract_audio_sequence(infile, outfile, start, length_s, audio_stream_idx=0): """Extracts from a media file a fixed length audio clip at specified position. The extracted audio clip is saved to file. The audio is re-encoded at 44100Hz and in case it has multiple channels, only the first is retained. If multiple audio streams are present, it's possible to select one of them by providing the 0-base index. This fuction depends on ffmpeg which must therfore be installed. Args: infile (str): The name of the input media file. outfile (str): The name of the output audio file. start (int): The start position in seconds of the audio clip. length_s (str): The length in seconds of the audio clip. audio_stream_idx (str): The zero based index of the audio stream. """ cmd1 = "ffmpeg -y -i" cmd2 = " -ss {0} -t {1} -ab 192000 -vn -map 0:a:{2} -af asetrate=44100 -ac 1" cmd2_fmt = cmd2.format(str(start), str(length_s), str(audio_stream_idx)) cmd_all = cmd1.split() + [infile] + cmd2_fmt.split() + [outfile] #print(cmd_all) process = subprocess.Popen(cmd_all, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) output, error = process.communicate() #if output is not None: # print(output) #if error is not None: # print(error)
def extract_audio_sequence(infile, outfile, start, length_s, audio_stream_idx=0): """Extracts from a media file a fixed length audio clip at specified position. The extracted audio clip is saved to file. The audio is re-encoded at 44100Hz and in case it has multiple channels, only the first is retained. If multiple audio streams are present, it's possible to select one of them by providing the 0-base index. This fuction depends on ffmpeg which must therfore be installed. Args: infile (str): The name of the input media file. outfile (str): The name of the output audio file. start (int): The start position in seconds of the audio clip. length_s (str): The length in seconds of the audio clip. audio_stream_idx (str): The zero based index of the audio stream. """ cmd1 = "ffmpeg -y -i" cmd2 = " -ss {0} -t {1} -ab 192000 -vn -map 0:a:{2} -af asetrate=44100 -ac 1" cmd2_fmt = cmd2.format(str(start), str(length_s), str(audio_stream_idx)) cmd_all = cmd1.split() + [infile] + cmd2_fmt.split() + [outfile] #print(cmd_all) process = subprocess.Popen(cmd_all, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) output, error = process.communicate() #if output is not None: # print(output) #if error is not None: # print(error)
Python
def print_memory_usage(): """Prints the RAM usage of the process. """ process = psutil.Process(os.getpid()) print("Memory usage:", _sizeof_fmt(int(process.memory_info().rss))) #print(process.memory_info())
def print_memory_usage(): """Prints the RAM usage of the process. """ process = psutil.Process(os.getpid()) print("Memory usage:", _sizeof_fmt(int(process.memory_info().rss))) #print(process.memory_info())
Python
def print_sizeof_vars(variables): """Prints the size (RAM occupancy) of provided variables. Reported sizes are not representative for lists and dicts since they only store pointers to objects. In this sense this functions work in shallow rather than deep mode. Args: variables (list): The list of variable to print. For example, the list of local variables can be obtained with locals(). """ for name, size in sorted(((name, sys.getsizeof(value)) for name,value in variables.items()), key= lambda x: -x[1])[:10]: print("{:>30}: {:>8}".format(name,_sizeof_fmt(size)))
def print_sizeof_vars(variables): """Prints the size (RAM occupancy) of provided variables. Reported sizes are not representative for lists and dicts since they only store pointers to objects. In this sense this functions work in shallow rather than deep mode. Args: variables (list): The list of variable to print. For example, the list of local variables can be obtained with locals(). """ for name, size in sorted(((name, sys.getsizeof(value)) for name,value in variables.items()), key= lambda x: -x[1])[:10]: print("{:>30}: {:>8}".format(name,_sizeof_fmt(size)))
Python
def _sizeof_fmt(num, suffix='B'): """Format a number as human readable, based on 1024 multipliers. Suited to be used to reformat a size expressed in bytes. By Fred Cirera, after https://stackoverflow.com/a/1094933/1870254 Args: num (int): The number to be formatted. suffix (str): the measure unit to append at the end of the formatted number. Returns: str: The formatted number including multiplier and measure unit. """ for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def _sizeof_fmt(num, suffix='B'): """Format a number as human readable, based on 1024 multipliers. Suited to be used to reformat a size expressed in bytes. By Fred Cirera, after https://stackoverflow.com/a/1094933/1870254 Args: num (int): The number to be formatted. suffix (str): the measure unit to append at the end of the formatted number. Returns: str: The formatted number including multiplier and measure unit. """ for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
Python
def list_file_recursive(folder): """Gets the names (including path) of files in a folder subtree. The folder is explored recursively. Subfolder names are not included in the list. The file names include paths: can be directly used to open them. Args: folder (str): The folder to search for files. Returns: list: The list of file names. """ return [os.path.join(dp, f) for dp, dn, filenames in os.walk(folder) for f in filenames]
def list_file_recursive(folder): """Gets the names (including path) of files in a folder subtree. The folder is explored recursively. Subfolder names are not included in the list. The file names include paths: can be directly used to open them. Args: folder (str): The folder to search for files. Returns: list: The list of file names. """ return [os.path.join(dp, f) for dp, dn, filenames in os.walk(folder) for f in filenames]
Python
def pauseresume(self): """ Boolean: whether the user has issued a play/pause request. """ with self._lock: return self._pauseresume
def pauseresume(self): """ Boolean: whether the user has issued a play/pause request. """ with self._lock: return self._pauseresume
Python
def stop(self): """ Boolean: whether the user has issued a stop request. """ with self._lock: return self._stop
def stop(self): """ Boolean: whether the user has issued a stop request. """ with self._lock: return self._stop
Python
def save(self, folder=None): """Saves the TrainingHistory data to history.json file. Args: folder (str): the folder where to save the trining history data. It can be None if a previous folder was already provided either to the constructor, or to a previous call to save(). """ if folder is not None: self._folder=folder if self._folder is None: raise NotADirectoryError("A directory must be specified either in __init__() or in save()") file_name = os.path.join(self._folder,"history.json") with open(file_name, 'w') as outfile: json.dump([self.loss, self.val_loss], outfile)
def save(self, folder=None): """Saves the TrainingHistory data to history.json file. Args: folder (str): the folder where to save the trining history data. It can be None if a previous folder was already provided either to the constructor, or to a previous call to save(). """ if folder is not None: self._folder=folder if self._folder is None: raise NotADirectoryError("A directory must be specified either in __init__() or in save()") file_name = os.path.join(self._folder,"history.json") with open(file_name, 'w') as outfile: json.dump([self.loss, self.val_loss], outfile)
Python
def extend(self, his): """Extends the history with the outcome of a training round. Args: his (keras.callbacks.History): the object returned by keras.Model.fit() """ self._loss.extend(his.history['loss']) self._val_loss.extend(his.history['val_loss'])
def extend(self, his): """Extends the history with the outcome of a training round. Args: his (keras.callbacks.History): the object returned by keras.Model.fit() """ self._loss.extend(his.history['loss']) self._val_loss.extend(his.history['val_loss'])
Python
def plot(self): """ Plots training and validation loss across epochs. """ plt.rcParams["figure.figsize"] =(12,6) plt.plot(self._loss, '-b') plt.plot(self._val_loss, '-r') plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper right') plt.grid() plt.show()
def plot(self): """ Plots training and validation loss across epochs. """ plt.rcParams["figure.figsize"] =(12,6) plt.plot(self._loss, '-b') plt.plot(self._val_loss, '-r') plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper right') plt.grid() plt.show()
Python
def load_model_for_live(model_dir, epoch_to_load): """Loads a model to be used for live predictions. The model is converted to stateful and the batch size set to one sample. The model should have been previously created with the timestep dimension of batch_input_shape (or of batch_shape) to None, so that predictions on a variable number of timesteps is supported. Args: model_dir (str): The folder where the model was saved. epoch_to_load (int): The epoch whose weights will be loaded in the model. Returns: keras.models.Model: The model, ready for use. """ model_file = os.path.join(model_dir,"model.json") weight_file = os.path.join(model_dir,"weights_ep_" +str(epoch_to_load).zfill(3)+".h5") with open(model_file, 'r') as f: json_str = f.read() json_str = json_str.replace("\"stateful\": false","\"stateful\": true") # making model stateful json_str = re.sub("\"batch_input_shape\": \[[^,]+,","\"batch_input_shape\": [1,", json_str) #making batch of one single example model = model_from_json(json_str) model.load_weights(weight_file, by_name=True) return model
def load_model_for_live(model_dir, epoch_to_load): """Loads a model to be used for live predictions. The model is converted to stateful and the batch size set to one sample. The model should have been previously created with the timestep dimension of batch_input_shape (or of batch_shape) to None, so that predictions on a variable number of timesteps is supported. Args: model_dir (str): The folder where the model was saved. epoch_to_load (int): The epoch whose weights will be loaded in the model. Returns: keras.models.Model: The model, ready for use. """ model_file = os.path.join(model_dir,"model.json") weight_file = os.path.join(model_dir,"weights_ep_" +str(epoch_to_load).zfill(3)+".h5") with open(model_file, 'r') as f: json_str = f.read() json_str = json_str.replace("\"stateful\": false","\"stateful\": true") # making model stateful json_str = re.sub("\"batch_input_shape\": \[[^,]+,","\"batch_input_shape\": [1,", json_str) #making batch of one single example model = model_from_json(json_str) model.load_weights(weight_file, by_name=True) return model
Python
def load_model(model_dir, epoch_to_load): """Loads a model to be used for train/test. This method allow to evaluate and or resume the training of a previously created model. Args: model_dir (str): The folder where the model was saved. epoch_to_load (int): The epoch whose weights will be loaded in the model. Returns: keras.models.Model: The model, ready for use. """ model_file = os.path.join(model_dir,"model.json") weight_file = os.path.join(model_dir,"weights_ep_" +str(epoch_to_load).zfill(3)+".h5") with open(model_file, 'r') as f: json_str = f.read() #json_str = json_str.replace("\"stateful\": false","\"stateful\": true") # making model stateful #json_str = re.sub("\"batch_input_shape\": \[[0-9]+,","\"batch_input_shape\": [1,", json_str) #making batch of one single example model = model_from_json(json_str) model.load_weights(weight_file, by_name=True) return model
def load_model(model_dir, epoch_to_load): """Loads a model to be used for train/test. This method allow to evaluate and or resume the training of a previously created model. Args: model_dir (str): The folder where the model was saved. epoch_to_load (int): The epoch whose weights will be loaded in the model. Returns: keras.models.Model: The model, ready for use. """ model_file = os.path.join(model_dir,"model.json") weight_file = os.path.join(model_dir,"weights_ep_" +str(epoch_to_load).zfill(3)+".h5") with open(model_file, 'r') as f: json_str = f.read() #json_str = json_str.replace("\"stateful\": false","\"stateful\": true") # making model stateful #json_str = re.sub("\"batch_input_shape\": \[[0-9]+,","\"batch_input_shape\": [1,", json_str) #making batch of one single example model = model_from_json(json_str) model.load_weights(weight_file, by_name=True) return model
Python
def load_weights(model, filepath, lookup={}, ignore=[], transform=None, verbose=True): """Modified version of keras load_weights that loads as much as it can. Useful for transfer learning. read the weights of layers stored in file and copy them to a model layer. the name of each layer is used to match the file's layers with the model's. It is possible to have layers in the model that dont appear in the file. The loading stops if a problem is encountered and the weights of the file layer that first caused the problem are returned. Args: model (keras.models.Model): The target. filepath (str): Source hdf5 file. lookup (dict): (optional) By default, the weights of each layer in the file are copied to the layer with the same name in the model. Using lookup you can replace the file name with a different model layer name, or to a list of model layer names, in which case the same weights will be copied to all layer models. ignore (list): (optional) The list of model layer names to ignore in transform (function): (optional) Function that receives the list of weights read from a layer in the file and filters them to the weights that will be loaded in the target model. verbose (bool): Flag. Highly recommended to keep this true and to follow the print messages. Returns: weights of the file layer which first caused the load to abort or None on successful load. """ if verbose: print('Loading', filepath, 'to', model.name) with h5py.File(filepath, mode='r') as f: # new file format layer_names = [n.decode('utf8') for n in f.attrs['layer_names']] # we batch weight value assignments in a single backend call # which provides a speedup in TensorFlow. weight_value_tuples = [] for name in layer_names: if verbose: print(name) g = f[name] weight_names = [n.decode('utf8') for n in g.attrs['weight_names']] if len(weight_names): weight_values = [g[weight_name] for weight_name in weight_names] if verbose: print('loading', ' '.join(_str_shape(w) for w in weight_values)) target_names = lookup.get(name, name) if isinstance(target_names, str): target_names = [target_names] # handle the case were lookup asks to send the same weight to multiple layers target_names = [target_name for target_name in target_names if target_name == name or target_name not in layer_names] for target_name in target_names: if verbose: print(target_name) try: layer = model.get_layer(name=target_name) except: layer = None if layer: # the same weight_values are copied to each of the target layers symbolic_weights = layer.trainable_weights + layer.non_trainable_weights if transform is not None: transformed_weight_values = transform(weight_values, layer) if transformed_weight_values is not None: if verbose: print('(%d->%d)'%(len(weight_values),len(transformed_weight_values))) weight_values = transformed_weight_values problem = len(symbolic_weights) != len(weight_values) if problem and verbose: print('(bad #wgts)'), if not problem: weight_value_tuples += zip(symbolic_weights, weight_values) else: problem = True if problem: if verbose: if name in ignore or ignore == '*': print('(skipping)') else: print('ABORT') if not (name in ignore or ignore == '*'): K.batch_set_value(weight_value_tuples) return [np.array(w) for w in weight_values] if verbose: print() else: if verbose: print('skipping this is empty file layer') K.batch_set_value(weight_value_tuples)
def load_weights(model, filepath, lookup={}, ignore=[], transform=None, verbose=True): """Modified version of keras load_weights that loads as much as it can. Useful for transfer learning. read the weights of layers stored in file and copy them to a model layer. the name of each layer is used to match the file's layers with the model's. It is possible to have layers in the model that dont appear in the file. The loading stops if a problem is encountered and the weights of the file layer that first caused the problem are returned. Args: model (keras.models.Model): The target. filepath (str): Source hdf5 file. lookup (dict): (optional) By default, the weights of each layer in the file are copied to the layer with the same name in the model. Using lookup you can replace the file name with a different model layer name, or to a list of model layer names, in which case the same weights will be copied to all layer models. ignore (list): (optional) The list of model layer names to ignore in transform (function): (optional) Function that receives the list of weights read from a layer in the file and filters them to the weights that will be loaded in the target model. verbose (bool): Flag. Highly recommended to keep this true and to follow the print messages. Returns: weights of the file layer which first caused the load to abort or None on successful load. """ if verbose: print('Loading', filepath, 'to', model.name) with h5py.File(filepath, mode='r') as f: # new file format layer_names = [n.decode('utf8') for n in f.attrs['layer_names']] # we batch weight value assignments in a single backend call # which provides a speedup in TensorFlow. weight_value_tuples = [] for name in layer_names: if verbose: print(name) g = f[name] weight_names = [n.decode('utf8') for n in g.attrs['weight_names']] if len(weight_names): weight_values = [g[weight_name] for weight_name in weight_names] if verbose: print('loading', ' '.join(_str_shape(w) for w in weight_values)) target_names = lookup.get(name, name) if isinstance(target_names, str): target_names = [target_names] # handle the case were lookup asks to send the same weight to multiple layers target_names = [target_name for target_name in target_names if target_name == name or target_name not in layer_names] for target_name in target_names: if verbose: print(target_name) try: layer = model.get_layer(name=target_name) except: layer = None if layer: # the same weight_values are copied to each of the target layers symbolic_weights = layer.trainable_weights + layer.non_trainable_weights if transform is not None: transformed_weight_values = transform(weight_values, layer) if transformed_weight_values is not None: if verbose: print('(%d->%d)'%(len(weight_values),len(transformed_weight_values))) weight_values = transformed_weight_values problem = len(symbolic_weights) != len(weight_values) if problem and verbose: print('(bad #wgts)'), if not problem: weight_value_tuples += zip(symbolic_weights, weight_values) else: problem = True if problem: if verbose: if name in ignore or ignore == '*': print('(skipping)') else: print('ABORT') if not (name in ignore or ignore == '*'): K.batch_set_value(weight_value_tuples) return [np.array(w) for w in weight_values] if verbose: print() else: if verbose: print('skipping this is empty file layer') K.batch_set_value(weight_value_tuples)
Python
def extract_backgrounds(src_folder, dst_folder, n_seq, seq_len_s): """Extract random audio sequences from media files. Generates a number of fixed lenght background audio sequences, picking at random position from a buch on multimedia files on disk. The generated sequences are used as input to the create_dataset() function. The generated audio clips are saved as wav files with progressive names. Supported input multimedia file formats are .avi, .mp3, .mp4, .mkv, *.flac, *.wav. Files are decoded with ffmpeg, so ffmpeg is a dependency. For each sequence to be generate a random file is chosen, a random position is picked and, in case the file has multiple audio streams, one of them is picked at random. The audio is re-encoded at 44100Hz and in case it has multiple channels, only the first is retained. Args: src_folder (str): The name of the folder where the source media files are located. dst_folder (str): The folder where to save the audio sequences. Must not exist yet. n_seq (int): The total number of sequences to be extracted. seq_len_s (int): The length in seconds of each sequence. """ assert os.path.isdir(src_folder) assert not os.path.isdir(dst_folder) os.makedirs(dst_folder) src_files = [f for f in list_file_recursive(src_folder) if f.endswith(".avi") or f.endswith(".mp3") or f.endswith(".mp4") or f.endswith(".mkv") or f.endswith(".flac") or f.endswith(".wav")] for i in range(n_seq): f = random.choice(src_files) f_len = get_length_s(f) n_streams = get_n_audio_streams(f) of = os.path.join(dst_folder,str(i).zfill(6)+".wav") if (f_len is None) or (n_streams is None): src_files.remove(f) print("Warning: failed to extract from ", f) if len(src_files)==0: raise OSError("Error: failed to all source files") i-=1 continue stream_idx = n_streams if n_streams==0 else random.randrange(n_streams) start = random.randrange(int(f_len*0.95-seq_len_s)) print(i, "of", n_seq, "|", f, "(", start ,"/" , f_len , ") ch", stream_idx) extract_audio_sequence(f,of,start,seq_len_s,stream_idx)
def extract_backgrounds(src_folder, dst_folder, n_seq, seq_len_s): """Extract random audio sequences from media files. Generates a number of fixed lenght background audio sequences, picking at random position from a buch on multimedia files on disk. The generated sequences are used as input to the create_dataset() function. The generated audio clips are saved as wav files with progressive names. Supported input multimedia file formats are .avi, .mp3, .mp4, .mkv, *.flac, *.wav. Files are decoded with ffmpeg, so ffmpeg is a dependency. For each sequence to be generate a random file is chosen, a random position is picked and, in case the file has multiple audio streams, one of them is picked at random. The audio is re-encoded at 44100Hz and in case it has multiple channels, only the first is retained. Args: src_folder (str): The name of the folder where the source media files are located. dst_folder (str): The folder where to save the audio sequences. Must not exist yet. n_seq (int): The total number of sequences to be extracted. seq_len_s (int): The length in seconds of each sequence. """ assert os.path.isdir(src_folder) assert not os.path.isdir(dst_folder) os.makedirs(dst_folder) src_files = [f for f in list_file_recursive(src_folder) if f.endswith(".avi") or f.endswith(".mp3") or f.endswith(".mp4") or f.endswith(".mkv") or f.endswith(".flac") or f.endswith(".wav")] for i in range(n_seq): f = random.choice(src_files) f_len = get_length_s(f) n_streams = get_n_audio_streams(f) of = os.path.join(dst_folder,str(i).zfill(6)+".wav") if (f_len is None) or (n_streams is None): src_files.remove(f) print("Warning: failed to extract from ", f) if len(src_files)==0: raise OSError("Error: failed to all source files") i-=1 continue stream_idx = n_streams if n_streams==0 else random.randrange(n_streams) start = random.randrange(int(f_len*0.95-seq_len_s)) print(i, "of", n_seq, "|", f, "(", start ,"/" , f_len , ") ch", stream_idx) extract_audio_sequence(f,of,start,seq_len_s,stream_idx)
Python
def _get_snippet_position(snip, bg, other_positions, max_attempt=50): """Tries to randoly pick a position for overlaing a snippet on a audio clip. The picked position is checked against all other previously reserved slices of the background audio clip. In case of ovrlap the position is discarded and the function picks another candidate. Args: snip (pydub.AudioSegment): The short audio clip to be overlaid on the background. bg (pydub.AudioSegment): The background audio clip. other_positions (list of lists two of int): The already reserved segments of background. max_attempt (int): The maximum number of attempt to get a position. Returns: list of two int: The start and end position in millisecond for the snippet or None if all the max_attempt candidates overlapped. """ for i in range(max_attempt): start = random.randrange(SAMPLE_LEN_S*1000-len(snip)-100) #leaving empty ms to the end of sample to have room for setting Y to ones end = start + len(snip) -1 # check for overlap overlap = False for prev_pos in other_positions: a = max(start, prev_pos[0]) b = min(end, prev_pos[1]) if a<=b: overlap = True break if not overlap: return [start, end] #print("KO") return None
def _get_snippet_position(snip, bg, other_positions, max_attempt=50): """Tries to randoly pick a position for overlaing a snippet on a audio clip. The picked position is checked against all other previously reserved slices of the background audio clip. In case of ovrlap the position is discarded and the function picks another candidate. Args: snip (pydub.AudioSegment): The short audio clip to be overlaid on the background. bg (pydub.AudioSegment): The background audio clip. other_positions (list of lists two of int): The already reserved segments of background. max_attempt (int): The maximum number of attempt to get a position. Returns: list of two int: The start and end position in millisecond for the snippet or None if all the max_attempt candidates overlapped. """ for i in range(max_attempt): start = random.randrange(SAMPLE_LEN_S*1000-len(snip)-100) #leaving empty ms to the end of sample to have room for setting Y to ones end = start + len(snip) -1 # check for overlap overlap = False for prev_pos in other_positions: a = max(start, prev_pos[0]) b = min(end, prev_pos[1]) if a<=b: overlap = True break if not overlap: return [start, end] #print("KO") return None
Python
def _create_audio_sample(backgrounds, snippets, is_neg_class = True, create_global_feat = False, pulse_len_ts = 50, dont_care=None): """Creates a single audio clip sample for the dataset and its corresponding target. Creates a single fixed length audio clip sample and its corresponding target y. The x matrix of the sample can be generated by computing the spectrogram of the audio clip, but this is not done within this function. This is a helper function used by create_dataset() The audio clip is created overlaing a random number of random trigger word snippets over a randomly selected slice of a radomly selected background. Args: backgrounds (list of pydub.AudioSegment): The background audio clips. snippets (list of lists of pydub.AudioSegment): The trigger word audio clips: one list per each trigger word class. A single word for each audio clip. is_neg_class (boolean): Same as create_dataset() param. create_global_feat (boolean): Same as create_dataset() param. pulse_len_ts (int): The number of timesteps to raise target to 1 after a trigger word snippet ends. dont_care (float): Ranging from 0 to 1. Set to zero or None to disable. If greater than zero, in the target and for each inserted snippet an interval of timesteps is determined, ending where the snippet end and having lenght corresponding to the snippet length (in timestep) multiplied by dont_care factor. This interval should be 0 valued in the target but its value is lowered to -0.0001 so that it can be distingushed from value 0. In particular, this can be used by the loss function to interpet those timesteps as don't cares having zero loss, whatever the prediced values. For example dont_care= 0.3 converts the last 30% of timesteps of each trigger word to don't cares and this, in conjuction with the proper custom loss, allows the model learn to detect the trigger word in advance, without having to wait it has finished. For multiple class, don't care mechanism is applied to each class feature and to the optional global feature too. Returns: pydub AudioSegment: The generated audio clip. numpy.ndarray: The target y of shape (1, T, ?) (the last dimension depends on is_neg_class and create_global_feat) """ global counters # GETTING A RANDOM SELECTED SLICE OF RANDOM SELECTED BACKGROUND bg = random.choice(backgrounds) bg_pos = random.randrange(len(bg) -SAMPLE_LEN_S*1000) bg = bg[bg_pos:bg_pos+SAMPLE_LEN_S*1000] # DECIDING HOW MANY SNIPPET TO INSERT n_snippets = int(math.ceil(random.triangular(0,MAX_SNIPPETS_PER_SAMPLE,MAX_SNIPPETS_PER_SAMPLE))) positions = [] #list of position [start, stop] of snippets already inserted into the sample n_classes = len(snippets) #INTIALIZING THE TARGET n_pos_classes = n_classes if is_neg_class is False else n_classes-1 is_multiclass = n_pos_classes>1 create_global_feat = create_global_feat if is_multiclass else False n_feat = n_pos_classes if not create_global_feat else n_pos_classes+1 y = np.zeros((1,T,n_feat),np.float32) delta = 0 # feature shift in target if is_neg_class: delta -=1 if create_global_feat: delta +=1 # INSERTING SNIPPETS #print(n_snippets) for i in range(n_snippets): #selecting one class and one snippet form it cla = random.randrange(len(snippets)) #print("\t",i) if cla==0 else print("\t",i, "*") counters[cla]+=1 idx = random.randrange(len(snippets[cla])) snip = snippets[cla][idx] pos = _get_snippet_position(snip, bg, positions) if pos is None: # failed to find room to insert the snippet, the sample is complete break #overlaying the snippet onto the background positions.append(pos) bg = bg.overlay(snip, pos[0]) #setting the target snip_start = int(pos[0]*T/(1000*SAMPLE_LEN_S)) snip_end = int(pos[1]*T/(1000*SAMPLE_LEN_S)) snip_len = snip_end-snip_start if cla==0 and is_neg_class: continue y[0,snip_end+1:snip_end+pulse_len_ts+1,cla+delta] = 1 if dont_care is not None: dc_len = int(snip_len*dont_care) if dc_len>0: y[0,snip_end+1-dc_len:snip_end+1,cla+delta] = -0.0001 #TODO TODO if create_global_feat: y[0,snip_end+1:snip_end+pulse_len_ts+1,0] = 1 if dont_care is not None and dc_len>0: y[0,snip_end+1-dc_len:snip_end+1,0] = -0.0001 return normalize_volume(bg) , y
def _create_audio_sample(backgrounds, snippets, is_neg_class = True, create_global_feat = False, pulse_len_ts = 50, dont_care=None): """Creates a single audio clip sample for the dataset and its corresponding target. Creates a single fixed length audio clip sample and its corresponding target y. The x matrix of the sample can be generated by computing the spectrogram of the audio clip, but this is not done within this function. This is a helper function used by create_dataset() The audio clip is created overlaing a random number of random trigger word snippets over a randomly selected slice of a radomly selected background. Args: backgrounds (list of pydub.AudioSegment): The background audio clips. snippets (list of lists of pydub.AudioSegment): The trigger word audio clips: one list per each trigger word class. A single word for each audio clip. is_neg_class (boolean): Same as create_dataset() param. create_global_feat (boolean): Same as create_dataset() param. pulse_len_ts (int): The number of timesteps to raise target to 1 after a trigger word snippet ends. dont_care (float): Ranging from 0 to 1. Set to zero or None to disable. If greater than zero, in the target and for each inserted snippet an interval of timesteps is determined, ending where the snippet end and having lenght corresponding to the snippet length (in timestep) multiplied by dont_care factor. This interval should be 0 valued in the target but its value is lowered to -0.0001 so that it can be distingushed from value 0. In particular, this can be used by the loss function to interpet those timesteps as don't cares having zero loss, whatever the prediced values. For example dont_care= 0.3 converts the last 30% of timesteps of each trigger word to don't cares and this, in conjuction with the proper custom loss, allows the model learn to detect the trigger word in advance, without having to wait it has finished. For multiple class, don't care mechanism is applied to each class feature and to the optional global feature too. Returns: pydub AudioSegment: The generated audio clip. numpy.ndarray: The target y of shape (1, T, ?) (the last dimension depends on is_neg_class and create_global_feat) """ global counters # GETTING A RANDOM SELECTED SLICE OF RANDOM SELECTED BACKGROUND bg = random.choice(backgrounds) bg_pos = random.randrange(len(bg) -SAMPLE_LEN_S*1000) bg = bg[bg_pos:bg_pos+SAMPLE_LEN_S*1000] # DECIDING HOW MANY SNIPPET TO INSERT n_snippets = int(math.ceil(random.triangular(0,MAX_SNIPPETS_PER_SAMPLE,MAX_SNIPPETS_PER_SAMPLE))) positions = [] #list of position [start, stop] of snippets already inserted into the sample n_classes = len(snippets) #INTIALIZING THE TARGET n_pos_classes = n_classes if is_neg_class is False else n_classes-1 is_multiclass = n_pos_classes>1 create_global_feat = create_global_feat if is_multiclass else False n_feat = n_pos_classes if not create_global_feat else n_pos_classes+1 y = np.zeros((1,T,n_feat),np.float32) delta = 0 # feature shift in target if is_neg_class: delta -=1 if create_global_feat: delta +=1 # INSERTING SNIPPETS #print(n_snippets) for i in range(n_snippets): #selecting one class and one snippet form it cla = random.randrange(len(snippets)) #print("\t",i) if cla==0 else print("\t",i, "*") counters[cla]+=1 idx = random.randrange(len(snippets[cla])) snip = snippets[cla][idx] pos = _get_snippet_position(snip, bg, positions) if pos is None: # failed to find room to insert the snippet, the sample is complete break #overlaying the snippet onto the background positions.append(pos) bg = bg.overlay(snip, pos[0]) #setting the target snip_start = int(pos[0]*T/(1000*SAMPLE_LEN_S)) snip_end = int(pos[1]*T/(1000*SAMPLE_LEN_S)) snip_len = snip_end-snip_start if cla==0 and is_neg_class: continue y[0,snip_end+1:snip_end+pulse_len_ts+1,cla+delta] = 1 if dont_care is not None: dc_len = int(snip_len*dont_care) if dc_len>0: y[0,snip_end+1-dc_len:snip_end+1,cla+delta] = -0.0001 #TODO TODO if create_global_feat: y[0,snip_end+1:snip_end+pulse_len_ts+1,0] = 1 if dont_care is not None and dc_len>0: y[0,snip_end+1-dc_len:snip_end+1,0] = -0.0001 return normalize_volume(bg) , y
Python
def create_dataset( background_dir, class_dirs, class_labels, n_samples, save_dir, is_neg_class = True, create_global_feat = False, n_samples_per_training_split = None, pulse_len_ts = 50, dont_care=0.3 ): """Create a detaset for trigger word detection task. Create a dataset, shuffle it, split it and save it to disk. The destination folder must not exist yet otherwise the function fails (intermediate folders of the provided path are created if needed). The dataset is created as follows: * Background audio clips are loaded from disk. * For each class, representative audio clips are loaded from disk. * For each sample to generate: ** A fixed length background is randomly selected from the pool of background audio clips. ** A random number of trigger words audio clips are randomly selected and overlaid on the background at random positions. ** The resulting audio clip is saved to file for for future use ** The spectrogram of the audio clip is computed, being the sample x ** The corresponding target y is generated with the same number of timesteps of x and as many features as the trigger word classes (excepted the optional negative class). y is initialized to 0 and raised to 1 for 50 timesteps after end of an overlaid trigger word, only in the feature corresponding to the trigger word class. If create_global_feat is True and if there are 2+ positive classes, an additional binary classification feature is created in the target (at index 0) being 1 when any of the other positive classes is 1. When there is just one positive class (and optionally a negative class), create_global_feat flag is ignored. * All the x and y are stacked in the X, Y dataset matrices. * The dataset is then splitted in training, development and test sets (70-15-15). Optionally, the training set can be further split in fixed size chunks (to save memory when training). * Each split is saved to npz file. * Class labels and other dataset metadata are saved to metadata.json. For multi-class classification (2+ non negative classes), the target is one-hot. The match of indices between class_labels and the target features may be broken: is_neg_class = True removes the first feature shifting all the others by -1, while create_global_feat = True adds a feature at index 0 shifting all the others by +1. If both set they compensates each other... The target is 3 dimensional in any case (#samples, #timesteps, #features), even for single class when #features=1. The current implementation generates the whole dataset before splitting and saving, so that the dataset has to fit in memory, otherwise the process crashes. With the standard settings for timesteps it is possible to generate up to 10K samples for each 8GB of phisical memory. Args: background_dir (str): The directory containing background audio clips. class_dirs (list of str): The list of directories, one per class, containing the trigger words audio samples (negative class, if present, must be at 0 index). Each audio file must contain exactely one word. class_labels (list of str): The class labels (in the same order of class_dirs). n_samples (int): The total number of samples to generate. save_dir (str): The dataset destination folder. is_neg_class (boolean): If True, the fist class is the "negative class", which has no target feature. create_global_feat (boolean): n_samples_per_training_split (int): If not None, the training set will be split in multiple files with n_samples_per_training_split samples each. pulse_len_ts (int): The length in timestep of the "one" pulse in sample's target after the end of each trigger word instance. dont_care (float): switch and factor for "don't care" functionality. Cfr. docs of _create_audio_sample() for details. """ global counters t0=time.time() #CREATING TARGET FOLDER print("CREATING TARGET FOLDER") if os.path.isdir(save_dir): raise FileExistsError('The target folder exists already. Please remove it manually and retry.') audio_samples_folder = os.path.join(save_dir,"audio_samples") os.makedirs(audio_samples_folder) print_memory_usage() #LOADING RAW AUDIO FILEs print("LOADING RAW AUDIO FILEs") backgrounds = load_audio_files(background_dir,dBFS_norm=None) n_classes = len(class_labels) assert len(class_dirs)==n_classes counters = np.zeros(n_classes) snippets = [] for i in range(n_classes): snippets.append(load_audio_files(class_dirs[i])) print("#backgrounds:", len(backgrounds)) print("#snippets:") [print("\t", lab, "-->", len(sni)) for sni,lab in zip(snippets, class_labels)] print_memory_usage() t1=time.time() print("Time:", int(t1-t0), "s") input("Press Enter to continue...") t1=time.time() #CREATING SAMPLES print("CREATING SAMPLES") m=n_samples def get_sample_shape(backgrounds,snippets,is_neg_class,create_global_feat): audio, y = _create_audio_sample(backgrounds,snippets,is_neg_class,create_global_feat) audio.set_frame_rate(44100).set_channels(1).export("tmp.wav", format="wav") rate, audio44khz = wavfile.read("tmp.wav") os.remove("tmp.wav") x=spectrogram(audio44khz) return x.shape, y.shape #x_list = [] #y_list = [] shax, shay = get_sample_shape(backgrounds,snippets,is_neg_class,create_global_feat) #print(shax,shay) X = np.empty((m,) + shax,dtype=np.float32) Y = np.empty((m,) + shay[1:],dtype=np.float32) #print("#X:", X.shape) #print("#Y:", Y.shape) #print_sizeof_vars(locals()) #input("Press Enter to continue...") for i in range(m): if i%200==0: print("Creating sample ", i, " of ", m) #Create audio sample by overlay audio, y = _create_audio_sample(backgrounds,snippets,is_neg_class,create_global_feat,pulse_len_ts, dont_care) #Compute spectrogram of the audio sample filename = os.path.join(audio_samples_folder,str(i).zfill(6)+".wav") audio.set_frame_rate(44100).set_channels(1).export(filename, format="wav") # saving audio to file rate, audio44khz = wavfile.read(filename) # loading audio so to have 44100Hz freq #print(rate) assert abs(rate-44100)<1 x=spectrogram(audio44khz) X[i]=x Y[i]=y del snippets, backgrounds #X=np.stack(x_list,axis=0) #Y=np.stack(y_list,axis=0) #del x_list, y_list print("#X:", X.shape) print("#Y:", Y.shape) print("class counters", counters) print_memory_usage() print_sizeof_vars(locals()) t2=time.time() print("Time:", int(t2-t1), "s") input("Press Enter to continue...") t2=time.time() #SPLITTING THE DATASET # no use: it's already randomly generated print("SPLITTING") Xs, Ys, n_tr_samples = _split_dataset(X,Y,n_samples_per_training_split=n_samples_per_training_split) #print("Done") #SAVING THE DATASET print("SAVING THE DATASET") _save_dataset(Xs, Ys, save_dir) with open(os.path.join(save_dir,"metadata.json"), 'w') as metadata_file: json.dump({\ "class_dirs":class_dirs, "background_dir":background_dir, "class_labels":class_labels, "n_classes":n_classes, "n_samples":n_samples, "is_neg_class": is_neg_class, "create_global_feat": create_global_feat, "n_samples_per_training_split": n_samples_per_training_split, "n_training_samples": n_tr_samples, "n_training_files": 0 if not isinstance(Xs[0],(list,)) else len(Xs[0]) }, metadata_file) t3=time.time() print("Time:", int(t3-t2), "s")
def create_dataset( background_dir, class_dirs, class_labels, n_samples, save_dir, is_neg_class = True, create_global_feat = False, n_samples_per_training_split = None, pulse_len_ts = 50, dont_care=0.3 ): """Create a detaset for trigger word detection task. Create a dataset, shuffle it, split it and save it to disk. The destination folder must not exist yet otherwise the function fails (intermediate folders of the provided path are created if needed). The dataset is created as follows: * Background audio clips are loaded from disk. * For each class, representative audio clips are loaded from disk. * For each sample to generate: ** A fixed length background is randomly selected from the pool of background audio clips. ** A random number of trigger words audio clips are randomly selected and overlaid on the background at random positions. ** The resulting audio clip is saved to file for for future use ** The spectrogram of the audio clip is computed, being the sample x ** The corresponding target y is generated with the same number of timesteps of x and as many features as the trigger word classes (excepted the optional negative class). y is initialized to 0 and raised to 1 for 50 timesteps after end of an overlaid trigger word, only in the feature corresponding to the trigger word class. If create_global_feat is True and if there are 2+ positive classes, an additional binary classification feature is created in the target (at index 0) being 1 when any of the other positive classes is 1. When there is just one positive class (and optionally a negative class), create_global_feat flag is ignored. * All the x and y are stacked in the X, Y dataset matrices. * The dataset is then splitted in training, development and test sets (70-15-15). Optionally, the training set can be further split in fixed size chunks (to save memory when training). * Each split is saved to npz file. * Class labels and other dataset metadata are saved to metadata.json. For multi-class classification (2+ non negative classes), the target is one-hot. The match of indices between class_labels and the target features may be broken: is_neg_class = True removes the first feature shifting all the others by -1, while create_global_feat = True adds a feature at index 0 shifting all the others by +1. If both set they compensates each other... The target is 3 dimensional in any case (#samples, #timesteps, #features), even for single class when #features=1. The current implementation generates the whole dataset before splitting and saving, so that the dataset has to fit in memory, otherwise the process crashes. With the standard settings for timesteps it is possible to generate up to 10K samples for each 8GB of phisical memory. Args: background_dir (str): The directory containing background audio clips. class_dirs (list of str): The list of directories, one per class, containing the trigger words audio samples (negative class, if present, must be at 0 index). Each audio file must contain exactely one word. class_labels (list of str): The class labels (in the same order of class_dirs). n_samples (int): The total number of samples to generate. save_dir (str): The dataset destination folder. is_neg_class (boolean): If True, the fist class is the "negative class", which has no target feature. create_global_feat (boolean): n_samples_per_training_split (int): If not None, the training set will be split in multiple files with n_samples_per_training_split samples each. pulse_len_ts (int): The length in timestep of the "one" pulse in sample's target after the end of each trigger word instance. dont_care (float): switch and factor for "don't care" functionality. Cfr. docs of _create_audio_sample() for details. """ global counters t0=time.time() #CREATING TARGET FOLDER print("CREATING TARGET FOLDER") if os.path.isdir(save_dir): raise FileExistsError('The target folder exists already. Please remove it manually and retry.') audio_samples_folder = os.path.join(save_dir,"audio_samples") os.makedirs(audio_samples_folder) print_memory_usage() #LOADING RAW AUDIO FILEs print("LOADING RAW AUDIO FILEs") backgrounds = load_audio_files(background_dir,dBFS_norm=None) n_classes = len(class_labels) assert len(class_dirs)==n_classes counters = np.zeros(n_classes) snippets = [] for i in range(n_classes): snippets.append(load_audio_files(class_dirs[i])) print("#backgrounds:", len(backgrounds)) print("#snippets:") [print("\t", lab, "-->", len(sni)) for sni,lab in zip(snippets, class_labels)] print_memory_usage() t1=time.time() print("Time:", int(t1-t0), "s") input("Press Enter to continue...") t1=time.time() #CREATING SAMPLES print("CREATING SAMPLES") m=n_samples def get_sample_shape(backgrounds,snippets,is_neg_class,create_global_feat): audio, y = _create_audio_sample(backgrounds,snippets,is_neg_class,create_global_feat) audio.set_frame_rate(44100).set_channels(1).export("tmp.wav", format="wav") rate, audio44khz = wavfile.read("tmp.wav") os.remove("tmp.wav") x=spectrogram(audio44khz) return x.shape, y.shape #x_list = [] #y_list = [] shax, shay = get_sample_shape(backgrounds,snippets,is_neg_class,create_global_feat) #print(shax,shay) X = np.empty((m,) + shax,dtype=np.float32) Y = np.empty((m,) + shay[1:],dtype=np.float32) #print("#X:", X.shape) #print("#Y:", Y.shape) #print_sizeof_vars(locals()) #input("Press Enter to continue...") for i in range(m): if i%200==0: print("Creating sample ", i, " of ", m) #Create audio sample by overlay audio, y = _create_audio_sample(backgrounds,snippets,is_neg_class,create_global_feat,pulse_len_ts, dont_care) #Compute spectrogram of the audio sample filename = os.path.join(audio_samples_folder,str(i).zfill(6)+".wav") audio.set_frame_rate(44100).set_channels(1).export(filename, format="wav") # saving audio to file rate, audio44khz = wavfile.read(filename) # loading audio so to have 44100Hz freq #print(rate) assert abs(rate-44100)<1 x=spectrogram(audio44khz) X[i]=x Y[i]=y del snippets, backgrounds #X=np.stack(x_list,axis=0) #Y=np.stack(y_list,axis=0) #del x_list, y_list print("#X:", X.shape) print("#Y:", Y.shape) print("class counters", counters) print_memory_usage() print_sizeof_vars(locals()) t2=time.time() print("Time:", int(t2-t1), "s") input("Press Enter to continue...") t2=time.time() #SPLITTING THE DATASET # no use: it's already randomly generated print("SPLITTING") Xs, Ys, n_tr_samples = _split_dataset(X,Y,n_samples_per_training_split=n_samples_per_training_split) #print("Done") #SAVING THE DATASET print("SAVING THE DATASET") _save_dataset(Xs, Ys, save_dir) with open(os.path.join(save_dir,"metadata.json"), 'w') as metadata_file: json.dump({\ "class_dirs":class_dirs, "background_dir":background_dir, "class_labels":class_labels, "n_classes":n_classes, "n_samples":n_samples, "is_neg_class": is_neg_class, "create_global_feat": create_global_feat, "n_samples_per_training_split": n_samples_per_training_split, "n_training_samples": n_tr_samples, "n_training_files": 0 if not isinstance(Xs[0],(list,)) else len(Xs[0]) }, metadata_file) t3=time.time() print("Time:", int(t3-t2), "s")
Python
def _split_dataset(X,Y, train_perc = 0.7, dev_perc = 0.15, m_clip=5000, do_shuffle=False, n_samples_per_training_split = None): """Splits a dataset into training development and test sets. Optionally shuffle the dataset before splitting. The splits are sized according to the given percentages, but dev and test sets sizes are clipped to m_clip samples each. Samples are taken in the following order: dev, test, train. This information can be useful during error analysis to match the audio samples to the samples in each split. The training set can be further split in chunks of a predefined size. Args: X (numpy.ndarray): The X matrix. Y (numpy.ndarray): The Y matrix. train_perc (float): The percentage of data to be destined to training set [0-1]. dev_perc (float): The percentage of data to be destined to dev set [0-1]. m_clip (int): The maximum number of samples of dev and test sets. do_shuffle (boolean): Wheter to shuffle the dataset before splitting. n_samples_per_training_split (int): The number of samples per each chunk of training set or None not to split training set in chunks. Returns: list: X splits list: Y splits int: number of training samples """ #SHUFFLING m = X.shape[0] if do_shuffle is True: shuffled = list(range(m)) random.shuffle(shuffled) X_shuf = X[shuffled,:] Y_shuf = Y[shuffled,:] else: X_shuf = X Y_shuf = Y #SPLITTING' train_perc = 0.7 dev_perc = 0.15 test_perc = 1.0-train_perc-dev_perc dev_cum = int(min(dev_perc*m,10000)) test_cum = int(dev_cum + min(test_perc*m, m_clip)) X_dev = X_shuf[0:dev_cum] Y_dev = Y_shuf[0:dev_cum] X_test = X_shuf[dev_cum:test_cum] Y_test = Y_shuf[dev_cum:test_cum] X_train = X_shuf[test_cum:m] Y_train = Y_shuf[test_cum:m] X_tr_split = [] Y_tr_split = [] if n_samples_per_training_split is not None: n_splits = int(X_train.shape[0]/n_samples_per_training_split) n_splits = n_splits+1 if X_train.shape[0]%n_samples_per_training_split!=0 else n_splits for i in range(n_splits-1): X_tr_split.append(X_train[i*n_samples_per_training_split:(i+1)*n_samples_per_training_split]) Y_tr_split.append(Y_train[i*n_samples_per_training_split:(i+1)*n_samples_per_training_split]) X_tr_split.append(X_train[(n_splits-1)*n_samples_per_training_split:]) Y_tr_split.append(Y_train[(n_splits-1)*n_samples_per_training_split:]) return [[X_tr_split, X_dev, X_test],[Y_tr_split, Y_dev, Y_test],X_train.shape[0]] return [[X_train, X_dev, X_test],[Y_train, Y_dev, Y_test],X_train.shape[0]]
def _split_dataset(X,Y, train_perc = 0.7, dev_perc = 0.15, m_clip=5000, do_shuffle=False, n_samples_per_training_split = None): """Splits a dataset into training development and test sets. Optionally shuffle the dataset before splitting. The splits are sized according to the given percentages, but dev and test sets sizes are clipped to m_clip samples each. Samples are taken in the following order: dev, test, train. This information can be useful during error analysis to match the audio samples to the samples in each split. The training set can be further split in chunks of a predefined size. Args: X (numpy.ndarray): The X matrix. Y (numpy.ndarray): The Y matrix. train_perc (float): The percentage of data to be destined to training set [0-1]. dev_perc (float): The percentage of data to be destined to dev set [0-1]. m_clip (int): The maximum number of samples of dev and test sets. do_shuffle (boolean): Wheter to shuffle the dataset before splitting. n_samples_per_training_split (int): The number of samples per each chunk of training set or None not to split training set in chunks. Returns: list: X splits list: Y splits int: number of training samples """ #SHUFFLING m = X.shape[0] if do_shuffle is True: shuffled = list(range(m)) random.shuffle(shuffled) X_shuf = X[shuffled,:] Y_shuf = Y[shuffled,:] else: X_shuf = X Y_shuf = Y #SPLITTING' train_perc = 0.7 dev_perc = 0.15 test_perc = 1.0-train_perc-dev_perc dev_cum = int(min(dev_perc*m,10000)) test_cum = int(dev_cum + min(test_perc*m, m_clip)) X_dev = X_shuf[0:dev_cum] Y_dev = Y_shuf[0:dev_cum] X_test = X_shuf[dev_cum:test_cum] Y_test = Y_shuf[dev_cum:test_cum] X_train = X_shuf[test_cum:m] Y_train = Y_shuf[test_cum:m] X_tr_split = [] Y_tr_split = [] if n_samples_per_training_split is not None: n_splits = int(X_train.shape[0]/n_samples_per_training_split) n_splits = n_splits+1 if X_train.shape[0]%n_samples_per_training_split!=0 else n_splits for i in range(n_splits-1): X_tr_split.append(X_train[i*n_samples_per_training_split:(i+1)*n_samples_per_training_split]) Y_tr_split.append(Y_train[i*n_samples_per_training_split:(i+1)*n_samples_per_training_split]) X_tr_split.append(X_train[(n_splits-1)*n_samples_per_training_split:]) Y_tr_split.append(Y_train[(n_splits-1)*n_samples_per_training_split:]) return [[X_tr_split, X_dev, X_test],[Y_tr_split, Y_dev, Y_test],X_train.shape[0]] return [[X_train, X_dev, X_test],[Y_train, Y_dev, Y_test],X_train.shape[0]]
Python
def load_single_dataset(filename): """Loads a partial dataset from a single npz file. Can be used lo load data from either train.npz or dev.npz or test.npz. The dataset is a list of X and Y, with: #X = (#samples, #timesteps, #feature_in) #Y = (#samples, #timesteps, #feature_out) Indeed in this project the number of input timesteps is equal to the number of output timesteps. Args: filename (str): The name of the npz file. Returns: list of numpy.ndarray: [X, Y] """ try: ds = np.load(filename) return [ds['X'],ds['Y']] except Exception as e: print('Unable to load data from', filename, ':', e)
def load_single_dataset(filename): """Loads a partial dataset from a single npz file. Can be used lo load data from either train.npz or dev.npz or test.npz. The dataset is a list of X and Y, with: #X = (#samples, #timesteps, #feature_in) #Y = (#samples, #timesteps, #feature_out) Indeed in this project the number of input timesteps is equal to the number of output timesteps. Args: filename (str): The name of the npz file. Returns: list of numpy.ndarray: [X, Y] """ try: ds = np.load(filename) return [ds['X'],ds['Y']] except Exception as e: print('Unable to load data from', filename, ':', e)
Python
def load_dataset_metadata(ds_folder): """Loads from file the metadata relative to a dataset. Metadata are loaded from metadata.json file in the dataset folder. They are a dictionary including the most relevant parameters passed to create_dataset() on dataset creation. Args: ds_folder (str): The folder containing dataset files. Returns: dict: The dataset metadata """ with open(os.path.join(ds_folder,"metadata.json")) as f: data = json.load(f) return data
def load_dataset_metadata(ds_folder): """Loads from file the metadata relative to a dataset. Metadata are loaded from metadata.json file in the dataset folder. They are a dictionary including the most relevant parameters passed to create_dataset() on dataset creation. Args: ds_folder (str): The folder containing dataset files. Returns: dict: The dataset metadata """ with open(os.path.join(ds_folder,"metadata.json")) as f: data = json.load(f) return data
Python
def _custom_loss(y_true, y_pred): """Computes loss for single trigger word detection model. The loss is the sum over samples and timesteps of the binary cross entropy between target and prediction. The only variation is that values of target lower than -0.001 are interpreted as a don't care values. Where don't care value are present the loss is forced to zero. Args: y_true (keras.backend.Tensor): target (shape = (#samples, #timesteps, 1)) y_pred (keras.backend.Tensor): predictions to match against the target, same shape of y_true Returns: keras.backend.Tensor: Scalar cost. """ # COMPUTING BINARY CROSS-ENTROPY one = K.ones(K.shape(y_true)) loss = -y_true*K.log(tf.clip_by_value(y_pred,1e-10,1.0))-(one-y_true)*K.log(tf.clip_by_value(one-y_pred,1e-10,1.0)) #SETTING TO ZERO WHERE TARGET IS "DON't CARE" thres = tf.fill(K.shape(y_true),-0.001) fil = tf.cast(K.greater(y_true, thres), tf.float32) loss_filtered = loss*fil #SUMMING OVER TIMESTEP AND SAMPLES cost = K.sum(loss_filtered) return cost
def _custom_loss(y_true, y_pred): """Computes loss for single trigger word detection model. The loss is the sum over samples and timesteps of the binary cross entropy between target and prediction. The only variation is that values of target lower than -0.001 are interpreted as a don't care values. Where don't care value are present the loss is forced to zero. Args: y_true (keras.backend.Tensor): target (shape = (#samples, #timesteps, 1)) y_pred (keras.backend.Tensor): predictions to match against the target, same shape of y_true Returns: keras.backend.Tensor: Scalar cost. """ # COMPUTING BINARY CROSS-ENTROPY one = K.ones(K.shape(y_true)) loss = -y_true*K.log(tf.clip_by_value(y_pred,1e-10,1.0))-(one-y_true)*K.log(tf.clip_by_value(one-y_pred,1e-10,1.0)) #SETTING TO ZERO WHERE TARGET IS "DON't CARE" thres = tf.fill(K.shape(y_true),-0.001) fil = tf.cast(K.greater(y_true, thres), tf.float32) loss_filtered = loss*fil #SUMMING OVER TIMESTEP AND SAMPLES cost = K.sum(loss_filtered) return cost
Python
def create_model(model_dir): """ Creates and compiles a keras LSTM based model for single trigger word detection. Also saves the model architecture to json file. Args: model_dir (str): The folder where to save model.json. Returns: keras.models.Model: the model """ model = Sequential() model.add(LSTM(units=64, return_sequences=True, batch_input_shape=(None,None,129), name='lstm1')) #for sake of live prediction it's important to pass batch_input_shape with timesteps dimension set to none model.add(Dropout(0.5, name='do1')) model.add(BatchNormalization(name='bn1')) model.add(LSTM(units=128, return_sequences=True, name='lstm2')) model.add(Dropout(0.5, name='do2')) model.add(BatchNormalization(name='bn2')) model.add(LSTM(units=256, return_sequences=True, name='lstm3')) model.add(Dropout(0.5, name='do3')) model.add(BatchNormalization(name='bn3')) model.add(TimeDistributed(Dense(1, activation="sigmoid", name='dense'), name='td')) #model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=None) model.compile(optimizer='rmsprop', loss=_custom_loss, metrics=None) with open(os.path.join(model_dir,"model.json"), "w") as f: f.write(model.to_json()) return model
def create_model(model_dir): """ Creates and compiles a keras LSTM based model for single trigger word detection. Also saves the model architecture to json file. Args: model_dir (str): The folder where to save model.json. Returns: keras.models.Model: the model """ model = Sequential() model.add(LSTM(units=64, return_sequences=True, batch_input_shape=(None,None,129), name='lstm1')) #for sake of live prediction it's important to pass batch_input_shape with timesteps dimension set to none model.add(Dropout(0.5, name='do1')) model.add(BatchNormalization(name='bn1')) model.add(LSTM(units=128, return_sequences=True, name='lstm2')) model.add(Dropout(0.5, name='do2')) model.add(BatchNormalization(name='bn2')) model.add(LSTM(units=256, return_sequences=True, name='lstm3')) model.add(Dropout(0.5, name='do3')) model.add(BatchNormalization(name='bn3')) model.add(TimeDistributed(Dense(1, activation="sigmoid", name='dense'), name='td')) #model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=None) model.compile(optimizer='rmsprop', loss=_custom_loss, metrics=None) with open(os.path.join(model_dir,"model.json"), "w") as f: f.write(model.to_json()) return model
Python
def train_more(model, model_dir, X_train, Y_train, X_dev, Y_dev, ep_start, more_ep, save_ep = 2, batch_size=16, h=None): """Performs a training round. Training history is updated. Model weights are periodically saved to file. In the end model summary is printed and training history plotted. Args: model (keras.models.Model): The model to train. model_dir (str): The folder where to save weights and history. X_train (numpy.ndarray): The trainig set samples. Y_train (numpy.ndarray): The trainig set targets. X_dev (numpy.ndarray): The validation set samples. Y_dev (numpy.ndarray): The validation set targets. ep_start (int): The last epoch trained, 0 if model is brand new. more_ep (int): The number of additional epoch to train. save_ep (int): The frequency for saving weights and history to file. batch_size (int): The number of samples of training batches. h (util_model.TrainingHistory): The training history of the model. """ ep = ep_start for i in range(0,more_ep,save_ep): his = model.fit(X_train, Y_train, batch_size = batch_size, epochs=ep+save_ep, validation_data=(X_dev, Y_dev), shuffle=False, initial_epoch=ep) if h is not None: h.extend(his) ep+=save_ep model.save(os.path.join(model_dir,"model_ep_" +str(ep).zfill(3)+".h5")) model.save_weights(os.path.join(model_dir,"weights_ep_" +str(ep).zfill(3)+".h5")) if h is not None: h.save(model_dir) model.summary() if h is not None: h.plot()
def train_more(model, model_dir, X_train, Y_train, X_dev, Y_dev, ep_start, more_ep, save_ep = 2, batch_size=16, h=None): """Performs a training round. Training history is updated. Model weights are periodically saved to file. In the end model summary is printed and training history plotted. Args: model (keras.models.Model): The model to train. model_dir (str): The folder where to save weights and history. X_train (numpy.ndarray): The trainig set samples. Y_train (numpy.ndarray): The trainig set targets. X_dev (numpy.ndarray): The validation set samples. Y_dev (numpy.ndarray): The validation set targets. ep_start (int): The last epoch trained, 0 if model is brand new. more_ep (int): The number of additional epoch to train. save_ep (int): The frequency for saving weights and history to file. batch_size (int): The number of samples of training batches. h (util_model.TrainingHistory): The training history of the model. """ ep = ep_start for i in range(0,more_ep,save_ep): his = model.fit(X_train, Y_train, batch_size = batch_size, epochs=ep+save_ep, validation_data=(X_dev, Y_dev), shuffle=False, initial_epoch=ep) if h is not None: h.extend(his) ep+=save_ep model.save(os.path.join(model_dir,"model_ep_" +str(ep).zfill(3)+".h5")) model.save_weights(os.path.join(model_dir,"weights_ep_" +str(ep).zfill(3)+".h5")) if h is not None: h.save(model_dir) model.summary() if h is not None: h.plot()
Python
def _composite_loss(y_true, y_pred): """Computes loss for multi trigger word detection model. The target (both true and predicted) is twofold: * the first feature goes to one after any trigger word being pronounced. * the remaining features are one per trigger word class going to one only atfer a word of that specific class has been pronounced. This loss computes sums over samples and timesteps the sum of two terms: * The binary cross entropy of the first feature * The multiclass cross entropy of the remaining features, but only for where y_true is one, otherwise this term goes to 0 --> if no trigger word has just finished, it does not matter which class will be predicted... Args: y_true (keras.backend.Tensor): target (shape = (#samples, #timesteps, #positive_classes+1)) y_pred (keras.backend.Tensor): predictions to match against the target, same shape of y_true Returns: keras.backend.Tensor: Scalar cost. """ Ytb = y_true[:,:,:1] # first feature is the bynary classification target for the task "any cmd vs no cmd". b stands for binary Ytm = y_true[:,:,1:] # all other features are the one hot target for the task "which cmd". m stands for multiple Ypb = y_pred[:,:,:1] Ypm = y_pred[:,:,1:] # COMPUTING BINARY CROSS-ENTROPY one = K.ones(K.shape(Ytb)) Lb = -Ytb*K.log(tf.clip_by_value(Ypb,1e-10,1.0))-(one-Ytb)*K.log(tf.clip_by_value(one-Ypb,1e-10,1.0)) # binary loss #SETTING BINARY CROSS-ENTROPY ZERO WHERE TARGET IS "DON't CARE" thres = tf.fill(K.shape(Lb),-0.001) fil = tf.cast(K.greater(Ytb, thres), tf.float32) Lb_fil = Lb*fil # COMPUTING MULTICLASS CROSS-ENTROPY parts = [] for i in range(_n_classes): parts.append(-Ytm[:,:,i:i+1]*K.log(tf.clip_by_value(Ypm[:,:,i:i+1],1e-10,1.0))) Lm=tf.add_n(parts) Lmm = Lm*Ytb Cb = K.sum(Lb_fil) Cm = K.sum(Lmm) C = Cb+Cm return C #return [C, Cb, Cm, Lb, Lm, Lmm, y_true, y_pred]
def _composite_loss(y_true, y_pred): """Computes loss for multi trigger word detection model. The target (both true and predicted) is twofold: * the first feature goes to one after any trigger word being pronounced. * the remaining features are one per trigger word class going to one only atfer a word of that specific class has been pronounced. This loss computes sums over samples and timesteps the sum of two terms: * The binary cross entropy of the first feature * The multiclass cross entropy of the remaining features, but only for where y_true is one, otherwise this term goes to 0 --> if no trigger word has just finished, it does not matter which class will be predicted... Args: y_true (keras.backend.Tensor): target (shape = (#samples, #timesteps, #positive_classes+1)) y_pred (keras.backend.Tensor): predictions to match against the target, same shape of y_true Returns: keras.backend.Tensor: Scalar cost. """ Ytb = y_true[:,:,:1] # first feature is the bynary classification target for the task "any cmd vs no cmd". b stands for binary Ytm = y_true[:,:,1:] # all other features are the one hot target for the task "which cmd". m stands for multiple Ypb = y_pred[:,:,:1] Ypm = y_pred[:,:,1:] # COMPUTING BINARY CROSS-ENTROPY one = K.ones(K.shape(Ytb)) Lb = -Ytb*K.log(tf.clip_by_value(Ypb,1e-10,1.0))-(one-Ytb)*K.log(tf.clip_by_value(one-Ypb,1e-10,1.0)) # binary loss #SETTING BINARY CROSS-ENTROPY ZERO WHERE TARGET IS "DON't CARE" thres = tf.fill(K.shape(Lb),-0.001) fil = tf.cast(K.greater(Ytb, thres), tf.float32) Lb_fil = Lb*fil # COMPUTING MULTICLASS CROSS-ENTROPY parts = [] for i in range(_n_classes): parts.append(-Ytm[:,:,i:i+1]*K.log(tf.clip_by_value(Ypm[:,:,i:i+1],1e-10,1.0))) Lm=tf.add_n(parts) Lmm = Lm*Ytb Cb = K.sum(Lb_fil) Cm = K.sum(Lmm) C = Cb+Cm return C #return [C, Cb, Cm, Lb, Lm, Lmm, y_true, y_pred]
Python
def create_model(model_dir, n_classes=9, n_feat_out=129): """ Creates and compiles a keras LSTM based model for multi trigger word detection. Also saves the model architecture to json file. Args: model_dir (str): The folder where to save model.json. Returns: keras.models.Model: the model """ global _n_classes inputs = Input(batch_shape=(None,None,n_feat_out), name='input') #for sake of live prediction it's important to pass batch_input_shape with timesteps dimension set to none X = LSTM(units=64, return_sequences=True, name='lstm1')(inputs) X = Dropout(0.4, name='do1')(X) X = BatchNormalization(name='bn1')(X) X = LSTM(units=128, return_sequences=True, name='lstm2')(X) X = Dropout(0.4, name='do2')(X) X = BatchNormalization(name='bn2')(X) X = LSTM(units=256, return_sequences=True, name='lstm3')(X) X = Dropout(0.4, name='do3')(X) X = BatchNormalization(name='bn3')(X) Y_bin = TimeDistributed(Dense(1, activation="sigmoid", name='dense1'), name='td1')(X) Y_multi = TimeDistributed(Dense(9, activation="softmax", name='dense2'), name='td2')(X) Y=Concatenate(axis=2, name='concat')([Y_bin,Y_multi]) model = Model(inputs=inputs, outputs=Y) _n_classes = n_classes # used by _composite_loss() model.compile(optimizer='rmsprop', loss=_composite_loss, metrics=None) with open(os.path.join(model_dir,"model.json"), "w") as f: f.write(model.to_json()) return model
def create_model(model_dir, n_classes=9, n_feat_out=129): """ Creates and compiles a keras LSTM based model for multi trigger word detection. Also saves the model architecture to json file. Args: model_dir (str): The folder where to save model.json. Returns: keras.models.Model: the model """ global _n_classes inputs = Input(batch_shape=(None,None,n_feat_out), name='input') #for sake of live prediction it's important to pass batch_input_shape with timesteps dimension set to none X = LSTM(units=64, return_sequences=True, name='lstm1')(inputs) X = Dropout(0.4, name='do1')(X) X = BatchNormalization(name='bn1')(X) X = LSTM(units=128, return_sequences=True, name='lstm2')(X) X = Dropout(0.4, name='do2')(X) X = BatchNormalization(name='bn2')(X) X = LSTM(units=256, return_sequences=True, name='lstm3')(X) X = Dropout(0.4, name='do3')(X) X = BatchNormalization(name='bn3')(X) Y_bin = TimeDistributed(Dense(1, activation="sigmoid", name='dense1'), name='td1')(X) Y_multi = TimeDistributed(Dense(9, activation="softmax", name='dense2'), name='td2')(X) Y=Concatenate(axis=2, name='concat')([Y_bin,Y_multi]) model = Model(inputs=inputs, outputs=Y) _n_classes = n_classes # used by _composite_loss() model.compile(optimizer='rmsprop', loss=_composite_loss, metrics=None) with open(os.path.join(model_dir,"model.json"), "w") as f: f.write(model.to_json()) return model
Python
def train_more(model, model_dir, train_feeder, X_dev, Y_dev, ep_start, more_ep, save_ep = 2, batch_size=16, h=None): """Performs a training round. Training history is updated. Model weights are periodically saved to file. In the end model summary is printed and training history plotted. Args: model (keras.models.Model): The model to train. model_dir (str): The folder where to save weights and history. ep_start (int): The last epoch trained, 0 if model is brand new. more_ep (int): The number of additional epoch to train. save_ep (int): The frequency for saving weights and history to file. batch_size (int): The number of samples of training batches. h (util_model.TrainingHistory): The training history of the model. """ ep = ep_start for i in range(0,more_ep,save_ep): his = model.fit_generator(train_feeder, epochs=ep+save_ep, validation_data=(X_dev, Y_dev), shuffle=False, initial_epoch=ep, use_multiprocessing=True, workers=1) if h is not None: h.extend(his) ep+=save_ep model.save(os.path.join(model_dir,"model_ep_" +str(ep).zfill(3)+".h5")) model.save_weights(os.path.join(model_dir,"weights_ep_" +str(ep).zfill(3)+".h5")) if h is not None: h.save(model_dir) model.summary() if h is not None: h.plot()
def train_more(model, model_dir, train_feeder, X_dev, Y_dev, ep_start, more_ep, save_ep = 2, batch_size=16, h=None): """Performs a training round. Training history is updated. Model weights are periodically saved to file. In the end model summary is printed and training history plotted. Args: model (keras.models.Model): The model to train. model_dir (str): The folder where to save weights and history. ep_start (int): The last epoch trained, 0 if model is brand new. more_ep (int): The number of additional epoch to train. save_ep (int): The frequency for saving weights and history to file. batch_size (int): The number of samples of training batches. h (util_model.TrainingHistory): The training history of the model. """ ep = ep_start for i in range(0,more_ep,save_ep): his = model.fit_generator(train_feeder, epochs=ep+save_ep, validation_data=(X_dev, Y_dev), shuffle=False, initial_epoch=ep, use_multiprocessing=True, workers=1) if h is not None: h.extend(his) ep+=save_ep model.save(os.path.join(model_dir,"model_ep_" +str(ep).zfill(3)+".h5")) model.save_weights(os.path.join(model_dir,"weights_ep_" +str(ep).zfill(3)+".h5")) if h is not None: h.save(model_dir) model.summary() if h is not None: h.plot()
Python
def evaluate_plot_single(Y, Yp, n_plot=10, ds_folder=None, delta=0, idx_list=None): """Plots prediction vs target for randomly selected samples (for the single trigger work detection case). Each plot represent a sample. Timesteps are on x axis, while y axis range from 0 to 1. Two curves are displayed: prediction and ground truth target. Sample to plot are randomly selected from the provided sets Y ad Yp. If called in an IPython console/notebook, it also provides a player for the audio clip corresponding to each sample. The sample indices printed and plotted always refers to the order of samples in Y (and Yp), despite delta being different from zero and/or idx_list being provided. Args: Y (numpy.ndarray): The set of ground truth target #Y = (#samples, #timesteps, #feat_out). Yp (numpy.ndarray): The set of predictions #Yp = (#samples, #timesteps, #feat_out). n_plot (int): The number of samples to plot. ds_folder (str): (Optional) The folder containing the dataset. If provided and if the method is called from an Ipython console, a player is displayed for each sample's audio clip. delta (int): The index of the first sample of Y and Yp within the whole dataset. For datasets created with "dataset" module this is: * 0 if working on the validation set * #devset_samples + #testset_samples if working on the training set idx_list (list of int): If provided, instead of random picking from all samples in Y, the choice is made among this subset of indices. This allows to perform error analysis, by providing indices of samples with prediction errors. """ if idx_list is None: idx = random.sample(range(Y.shape[0]), n_plot) else: idx = random.sample(idx_list, n_plot) for i in idx: if ds_folder is not None: filename = os.path.join(ds_folder, "audio_samples", str(i+delta).zfill(6)+".wav") print("Sample:", i, filename) IPython.display.display(IPython.display.Audio(filename)) else: print("Sample:", i) plt.plot(Y[i], '-b', label='ground truth') plt.plot(Yp[i], '-r', label='prediction') plt.legend(loc='upper right') plt.gca().set_title("Sample " + str(i)) plt.gca().set_ylim([-.1,1.1]) plt.show() plt.figure()
def evaluate_plot_single(Y, Yp, n_plot=10, ds_folder=None, delta=0, idx_list=None): """Plots prediction vs target for randomly selected samples (for the single trigger work detection case). Each plot represent a sample. Timesteps are on x axis, while y axis range from 0 to 1. Two curves are displayed: prediction and ground truth target. Sample to plot are randomly selected from the provided sets Y ad Yp. If called in an IPython console/notebook, it also provides a player for the audio clip corresponding to each sample. The sample indices printed and plotted always refers to the order of samples in Y (and Yp), despite delta being different from zero and/or idx_list being provided. Args: Y (numpy.ndarray): The set of ground truth target #Y = (#samples, #timesteps, #feat_out). Yp (numpy.ndarray): The set of predictions #Yp = (#samples, #timesteps, #feat_out). n_plot (int): The number of samples to plot. ds_folder (str): (Optional) The folder containing the dataset. If provided and if the method is called from an Ipython console, a player is displayed for each sample's audio clip. delta (int): The index of the first sample of Y and Yp within the whole dataset. For datasets created with "dataset" module this is: * 0 if working on the validation set * #devset_samples + #testset_samples if working on the training set idx_list (list of int): If provided, instead of random picking from all samples in Y, the choice is made among this subset of indices. This allows to perform error analysis, by providing indices of samples with prediction errors. """ if idx_list is None: idx = random.sample(range(Y.shape[0]), n_plot) else: idx = random.sample(idx_list, n_plot) for i in idx: if ds_folder is not None: filename = os.path.join(ds_folder, "audio_samples", str(i+delta).zfill(6)+".wav") print("Sample:", i, filename) IPython.display.display(IPython.display.Audio(filename)) else: print("Sample:", i) plt.plot(Y[i], '-b', label='ground truth') plt.plot(Yp[i], '-r', label='prediction') plt.legend(loc='upper right') plt.gca().set_title("Sample " + str(i)) plt.gca().set_ylim([-.1,1.1]) plt.show() plt.figure()
Python
def evaluate_plot_multi(Y, Yp, n_plot=10, ds_folder=None, delta=0, idx_list=None): """Plots prediction vs target for randomly selected samples (for the multiple trigger work detection case). Each figure represent a sample and has 4 sub plots. Timesteps are on x axis, while y axis always range from 0 to 1. This is the contents of the sub plots: * top-left: prediction and ground truth of the global binary feature: "has any trigger word just finished being pronounced?" * top-right: prediction and ground truth of the feature corresponding the trigger word class having the greatest number of occurrences in the sample. * bottom-right: prediction and ground truth of the feature corresponding the trigger word class having the second greatest number of occurrences in the sample. * bottom-left: prediction of all remaninig class features. Two curves are displayed: prediction and ground truth target. Sample to plot are randomly selected from the provided sets Y ad Yp. If called in an IPython console/notebook, it also provides a player for the audio clip corresponding to each sample. The sample indices printed and plotted always refers to the order of samples in Y (and Yp), despite delta being different from zero and/or idx_list being provided. Args: Y (numpy.ndarray): The set of ground truth target #Y = (#samples, #timesteps, #feat_out). Yp (numpy.ndarray): The set of predictions #Yp = (#samples, #timesteps, #feat_out). n_plot (int): The number of samples to plot. ds_folder (str): (Optional) The folder containing the dataset. If provided and if the method is called from an Ipython console, a player is displayed for each sample's audio clip. delta (int): The index of the first sample of Y and Yp within the whole dataset. For datasets created with "dataset" module this is: * 0 if working on the validation set * #devset_samples + #testset_samples if working on the training set idx_list (list of int): If provided, instead of random picking from all samples in Y, the choice is made among this subset of indices. This allows to perform error analysis, by providing indices of samples with prediction errors. """ if idx_list is None: idx = random.sample(range(Y.shape[0]), n_plot) else: idx = random.choices(idx_list,k=n_plot) for i in idx: if ds_folder is not None: filename = os.path.join(ds_folder, "audio_samples", str(i+delta).zfill(6)+".wav") print("Sample:", i, filename) IPython.display.display(IPython.display.Audio(filename)) else: print("Sample:", i) ytb = Y[i,:,:1] ypb = Yp[i,:,:1] ytm = Y[i,:,1:] ypm = Yp[i,:,1:] # PLOT BINARY ax = plt.subplot(2, 2, 1) plt.plot(ytb, '-b', label='binary ground truth') plt.plot(ypb, '-r', label='binary prediction') plt.legend() ax.set_ylim([-.1,1.1]) ytm_avg = ytm.mean(axis=0) sorted_idx = np.argsort(ytm_avg) # PLOT MULTI TOP 1 ax = plt.subplot(2, 2, 2) plt.plot(ytm[:,sorted_idx[-1]], '-b', label='1st top multiple ground truth') plt.plot(ypm[:,sorted_idx[-1]], '-r', label='1st top multiple prediction') plt.legend() ax.set_ylim([-.1,1.1]) # PLOT MULTI TOP 2 ax = plt.subplot(2, 2, 4) plt.plot(ytm[:,sorted_idx[-2]], '-b', label='2nd top multiple ground truth') plt.plot(ypm[:,sorted_idx[-2]], '-r', label='2nd top multiple prediction') plt.legend() ax.set_ylim([-.1,1.1]) # PLOT MULTI OTHERS n_classes = ypm.shape[-1] if n_classes>2: ax = plt.subplot(2, 2, 3) for u in range(n_classes-2): plt.plot(ypm[:,sorted_idx[u]]) ax.set_title("multiple predictions of not 1st and 2nd classes") ax.set_ylim([-.1,1.1]) plt.suptitle("Sample " + str(i)) plt.show() plt.figure()
def evaluate_plot_multi(Y, Yp, n_plot=10, ds_folder=None, delta=0, idx_list=None): """Plots prediction vs target for randomly selected samples (for the multiple trigger work detection case). Each figure represent a sample and has 4 sub plots. Timesteps are on x axis, while y axis always range from 0 to 1. This is the contents of the sub plots: * top-left: prediction and ground truth of the global binary feature: "has any trigger word just finished being pronounced?" * top-right: prediction and ground truth of the feature corresponding the trigger word class having the greatest number of occurrences in the sample. * bottom-right: prediction and ground truth of the feature corresponding the trigger word class having the second greatest number of occurrences in the sample. * bottom-left: prediction of all remaninig class features. Two curves are displayed: prediction and ground truth target. Sample to plot are randomly selected from the provided sets Y ad Yp. If called in an IPython console/notebook, it also provides a player for the audio clip corresponding to each sample. The sample indices printed and plotted always refers to the order of samples in Y (and Yp), despite delta being different from zero and/or idx_list being provided. Args: Y (numpy.ndarray): The set of ground truth target #Y = (#samples, #timesteps, #feat_out). Yp (numpy.ndarray): The set of predictions #Yp = (#samples, #timesteps, #feat_out). n_plot (int): The number of samples to plot. ds_folder (str): (Optional) The folder containing the dataset. If provided and if the method is called from an Ipython console, a player is displayed for each sample's audio clip. delta (int): The index of the first sample of Y and Yp within the whole dataset. For datasets created with "dataset" module this is: * 0 if working on the validation set * #devset_samples + #testset_samples if working on the training set idx_list (list of int): If provided, instead of random picking from all samples in Y, the choice is made among this subset of indices. This allows to perform error analysis, by providing indices of samples with prediction errors. """ if idx_list is None: idx = random.sample(range(Y.shape[0]), n_plot) else: idx = random.choices(idx_list,k=n_plot) for i in idx: if ds_folder is not None: filename = os.path.join(ds_folder, "audio_samples", str(i+delta).zfill(6)+".wav") print("Sample:", i, filename) IPython.display.display(IPython.display.Audio(filename)) else: print("Sample:", i) ytb = Y[i,:,:1] ypb = Yp[i,:,:1] ytm = Y[i,:,1:] ypm = Yp[i,:,1:] # PLOT BINARY ax = plt.subplot(2, 2, 1) plt.plot(ytb, '-b', label='binary ground truth') plt.plot(ypb, '-r', label='binary prediction') plt.legend() ax.set_ylim([-.1,1.1]) ytm_avg = ytm.mean(axis=0) sorted_idx = np.argsort(ytm_avg) # PLOT MULTI TOP 1 ax = plt.subplot(2, 2, 2) plt.plot(ytm[:,sorted_idx[-1]], '-b', label='1st top multiple ground truth') plt.plot(ypm[:,sorted_idx[-1]], '-r', label='1st top multiple prediction') plt.legend() ax.set_ylim([-.1,1.1]) # PLOT MULTI TOP 2 ax = plt.subplot(2, 2, 4) plt.plot(ytm[:,sorted_idx[-2]], '-b', label='2nd top multiple ground truth') plt.plot(ypm[:,sorted_idx[-2]], '-r', label='2nd top multiple prediction') plt.legend() ax.set_ylim([-.1,1.1]) # PLOT MULTI OTHERS n_classes = ypm.shape[-1] if n_classes>2: ax = plt.subplot(2, 2, 3) for u in range(n_classes-2): plt.plot(ypm[:,sorted_idx[u]]) ax.set_title("multiple predictions of not 1st and 2nd classes") ax.set_ylim([-.1,1.1]) plt.suptitle("Sample " + str(i)) plt.show() plt.figure()
Python
def find_peaks(y, confidence_thres = 0.5, mean_win_size=9, consistency_thres = 0.75, peak_min_len = 15): """Finds peaks in a univariate timeseries. This function applies to single features of target and predictions of single samples. The first step is binarization of the series: each value is converted to either 0 or 1 depending on accuracy threshold. Then a 1D mean filter is applied followed by another binary thresholding, to deal with short lived spikes in the series. The results is the looked for peaks which are returned after the suppression of too short ones. Args: y (numpy.ndarray): The univariate time series to analyze. confidence_thres (float): The threshold of the first binarization, being the minimum level of confidence for a "one" prediction. mean_win_size (int): The length in timesteps of the window for the mean filtering. consistency_thres (float): The threshold for the binarization after mean filtering being, the minimum percentage of "one" timesteps around the current for it to be declared a "one". peak_min_len (int): The threshold in timesteps under which, peaks are declared too short and suppressed. Returns: list of (int,int): List of peaks as (first ts, last ts). """ peak_ker = np.full((mean_win_size,), 1.0/mean_win_size) try: tmp = y.flatten()>confidence_thres y_filterd = np.convolve(tmp,peak_ker,'same') except ValueError as e: print(tmp.shape) print(peak_ker.shape) raise e #plt.plot(y_filterd, '-r', label="filtered") y_bin = y_filterd>consistency_thres #plt.plot(y_bin, '-g', label="filtered binary") peaks = [] p_start = p_end = 0 is_peak = False for i in range(y_bin.size): if y_bin[i]==1 and not is_peak: is_peak = True p_start = i elif (y_bin[i]==0 or i==y_bin.size-1) and is_peak: is_peak = False p_end = i if p_end-p_start >= peak_min_len: peaks.append((p_start, p_end)) return peaks
def find_peaks(y, confidence_thres = 0.5, mean_win_size=9, consistency_thres = 0.75, peak_min_len = 15): """Finds peaks in a univariate timeseries. This function applies to single features of target and predictions of single samples. The first step is binarization of the series: each value is converted to either 0 or 1 depending on accuracy threshold. Then a 1D mean filter is applied followed by another binary thresholding, to deal with short lived spikes in the series. The results is the looked for peaks which are returned after the suppression of too short ones. Args: y (numpy.ndarray): The univariate time series to analyze. confidence_thres (float): The threshold of the first binarization, being the minimum level of confidence for a "one" prediction. mean_win_size (int): The length in timesteps of the window for the mean filtering. consistency_thres (float): The threshold for the binarization after mean filtering being, the minimum percentage of "one" timesteps around the current for it to be declared a "one". peak_min_len (int): The threshold in timesteps under which, peaks are declared too short and suppressed. Returns: list of (int,int): List of peaks as (first ts, last ts). """ peak_ker = np.full((mean_win_size,), 1.0/mean_win_size) try: tmp = y.flatten()>confidence_thres y_filterd = np.convolve(tmp,peak_ker,'same') except ValueError as e: print(tmp.shape) print(peak_ker.shape) raise e #plt.plot(y_filterd, '-r', label="filtered") y_bin = y_filterd>consistency_thres #plt.plot(y_bin, '-g', label="filtered binary") peaks = [] p_start = p_end = 0 is_peak = False for i in range(y_bin.size): if y_bin[i]==1 and not is_peak: is_peak = True p_start = i elif (y_bin[i]==0 or i==y_bin.size-1) and is_peak: is_peak = False p_end = i if p_end-p_start >= peak_min_len: peaks.append((p_start, p_end)) return peaks
Python
def _iou(p1, p2): """Computes intersection over union of two intervals. Args: p1 ((int,int)): First interval as (first ts, last ts) p2 ((int,int)): Second interval as (first ts, last ts) Returns: float: intersection over union of the two intervals. """ i_start = max(p1[0],p2[0]) i_end = min(p1[1],p2[1]) i_len = max(0,i_end-i_start) o_start = min(p1[0],p2[0]) o_end = max(p1[1],p2[1]) o_len = o_end-o_start return float(i_len)/o_len
def _iou(p1, p2): """Computes intersection over union of two intervals. Args: p1 ((int,int)): First interval as (first ts, last ts) p2 ((int,int)): Second interval as (first ts, last ts) Returns: float: intersection over union of the two intervals. """ i_start = max(p1[0],p2[0]) i_end = min(p1[1],p2[1]) i_len = max(0,i_end-i_start) o_start = min(p1[0],p2[0]) o_end = max(p1[1],p2[1]) o_len = o_end-o_start return float(i_len)/o_len
Python
def _ioam(p1, p2): """Computes intersection of two intervals over the armonic mean of their lengths. This is a better metric for peak matching than classic intersection over union: it still ranges from 0 to 1 but keeps higher values if one interval is much shorter than the other, specifically it cannot be lower than I/(2*min(L1,L2)). Args: p1 ((int,int)): First interval as (first ts, last ts) p2 ((int,int)): Second interval as (first ts, last ts) Returns: float: interval intersection over armonic mean of intervals' lengths. """ i_start = max(p1[0],p2[0]) i_end = min(p1[1],p2[1]) i_len = max(0,i_end-i_start) l1 = p1[1]-p1[0] l2 = p2[1]-p2[0] am = 2*l1*l2/(l1+l2) return float(i_len)/am
def _ioam(p1, p2): """Computes intersection of two intervals over the armonic mean of their lengths. This is a better metric for peak matching than classic intersection over union: it still ranges from 0 to 1 but keeps higher values if one interval is much shorter than the other, specifically it cannot be lower than I/(2*min(L1,L2)). Args: p1 ((int,int)): First interval as (first ts, last ts) p2 ((int,int)): Second interval as (first ts, last ts) Returns: float: interval intersection over armonic mean of intervals' lengths. """ i_start = max(p1[0],p2[0]) i_end = min(p1[1],p2[1]) i_len = max(0,i_end-i_start) l1 = p1[1]-p1[0] l2 = p2[1]-p2[0] am = 2*l1*l2/(l1+l2) return float(i_len)/am
Python
def _delta(p1, p2): """Computes the shift between the start of two intervals. Args: p1 ((int,int)): First interval as (first ts, last ts) p2 ((int,int)): Second interval as (first ts, last ts) Returns: float: interval intersection over armonic mean of intervals' lengths. """ return p2[0]-p1[0]
def _delta(p1, p2): """Computes the shift between the start of two intervals. Args: p1 ((int,int)): First interval as (first ts, last ts) p2 ((int,int)): Second interval as (first ts, last ts) Returns: float: interval intersection over armonic mean of intervals' lengths. """ return p2[0]-p1[0]
Python
def _compare_peaks(pt, pp): """Compares the peaks extrated from univariate target and univariate prediction. This function matches the peaks extracted from a single feature of target and relative prediction respectively. Peaks are consequently classified as: * true positives: when there is a match in the two lists * false postive: unmatched peaks of the prediction * false negative: unmatched peaks of the target Args: pt (list of (int, int)): peaks from a single feature of target pp (list of (int, int)): peaks from a single feature of prediction Returns: list of ((int, int),(int, int)): true positives list of (int, int): false postives list of (int, int): false negatives """ TP = [] #true positive peaks FP = [] #false positive peaks FN = [] #false negative peaks it=0 ip=0 while it<len(pt) and ip<len(pp): if _ioam(pt[it],pp[ip])>0.25: TP.append((pt[it],pp[ip])) it+=1 ip+=1 else: if pt[it][1]<pp[ip][1]: FN.append(pt[it]) it+=1 else: FP.append(pp[ip]) ip+=1 if it<len(pt): for i in range(it,len(pt)): FN.append(pt[i]) elif ip<len(pp): for i in range(ip,len(pp)): FP.append(pp[i]) return [TP, FP, FN]
def _compare_peaks(pt, pp): """Compares the peaks extrated from univariate target and univariate prediction. This function matches the peaks extracted from a single feature of target and relative prediction respectively. Peaks are consequently classified as: * true positives: when there is a match in the two lists * false postive: unmatched peaks of the prediction * false negative: unmatched peaks of the target Args: pt (list of (int, int)): peaks from a single feature of target pp (list of (int, int)): peaks from a single feature of prediction Returns: list of ((int, int),(int, int)): true positives list of (int, int): false postives list of (int, int): false negatives """ TP = [] #true positive peaks FP = [] #false positive peaks FN = [] #false negative peaks it=0 ip=0 while it<len(pt) and ip<len(pp): if _ioam(pt[it],pp[ip])>0.25: TP.append((pt[it],pp[ip])) it+=1 ip+=1 else: if pt[it][1]<pp[ip][1]: FN.append(pt[it]) it+=1 else: FP.append(pp[ip]) ip+=1 if it<len(pt): for i in range(it,len(pt)): FN.append(pt[i]) elif ip<len(pp): for i in range(ip,len(pp)): FP.append(pp[i]) return [TP, FP, FN]
Python
def _match_peak(p, pp, return_ioam=False): """Checks a list of peaks for matches against a single peak. Given a peak p and a list of peaks pp (computed by find_peaks()) search in pp a peak matching with p, base on ioam() metric. If found, the peak in pp is returned. Checks the existence in a list of peaks of a peak near a specified position. Args: p (int,int): The single peak. pp (list of (int,int)): The list of peaks. return_ioam (boolean): Whether of not to return the matching score. Returns: (int,int): The first matching element in pp or None. float: (only if return_ioam=True) The matching score or None. """ for p_ in pp: score = _ioam(p,p_) if(score>0.25): return p_ if not return_ioam else [p_ , score] return None if not return_ioam else [None, None]
def _match_peak(p, pp, return_ioam=False): """Checks a list of peaks for matches against a single peak. Given a peak p and a list of peaks pp (computed by find_peaks()) search in pp a peak matching with p, base on ioam() metric. If found, the peak in pp is returned. Checks the existence in a list of peaks of a peak near a specified position. Args: p (int,int): The single peak. pp (list of (int,int)): The list of peaks. return_ioam (boolean): Whether of not to return the matching score. Returns: (int,int): The first matching element in pp or None. float: (only if return_ioam=True) The matching score or None. """ for p_ in pp: score = _ioam(p,p_) if(score>0.25): return p_ if not return_ioam else [p_ , score] return None if not return_ioam else [None, None]
Python
def _compute_metrics(tp, fp, fn): """Computes precision, recall and f1-score from count of TP, TN and FN. Args: tp (int): The number of true positives. fp (int): The number of false positives. fn (int): The number of false negatives. Returns: dict (str -> float): Dictionary including 'precision', 'recall' and 'f1_score'. """ res = {} res['precision']=tp/(tp+fp) res['recall']=tp/(tp+fn) res['f1_score']=2*res['precision']*res['recall']/(res['precision']+res['recall']) return res
def _compute_metrics(tp, fp, fn): """Computes precision, recall and f1-score from count of TP, TN and FN. Args: tp (int): The number of true positives. fp (int): The number of false positives. fn (int): The number of false negatives. Returns: dict (str -> float): Dictionary including 'precision', 'recall' and 'f1_score'. """ res = {} res['precision']=tp/(tp+fp) res['recall']=tp/(tp+fn) res['f1_score']=2*res['precision']*res['recall']/(res['precision']+res['recall']) return res
Python
def compute_global_metrics_single(Yt, Yp): """Computes precision, recall and f1-score for the single trigger word detection case. Statistics for metric computation are determined for each sample and summed over the samples. Args: Yt (numpy.ndarray): The matrix of targets #Yt = (#samples, #timesteps, 1) Yp (numpy.ndarray): The matrix of predictions #Yp = #Yt Returns: dict (str -> float or int): The dictionary of computed metrics including the count of tp, fp and including the average shift and root mean quared shift (in timesteps) of predicted peaks wrt target peaks and including the mean peak length (in timesteps) of tp predicted peaks. dict (str -> list of int): The dictionary list of samples indices for each case: * _tp: true positive, * _fp: false postive, * _fn: false negative """ tp = 0 fp = 0 fn = 0 tp_li = [] fp_li = [] fn_li = [] delta_avg = 0.0 delta_std = 0.0 peak_len_avg = 0.0 for i in range(Yt.shape[0]): pt = find_peaks(Yt[i]) pp = find_peaks(Yp[i]) TP, FP, FN = _compare_peaks(pt, pp) tp += len(TP) fp += len(FP) fn += len(FN) if len(TP)>0: tp_li.append(i) if len(FP)>0: fp_li.append(i) if len(FN)>0: fn_li.append(i) for p1, p2 in TP: de = _delta(p1,p2) delta_avg += de delta_std += de*de peak_len_avg += p2[1]-p2[0] delta_avg /= tp delta_std = math.sqrt(delta_std/tp) peak_len_avg /= tp m = _compute_metrics(tp, fp, fn) m['_tp']=tp m['_fn']=fn m['_fp']=fp m['_tp_delta_avg']=delta_avg m['_tp_delta_std']=delta_std m['_tp_peak_len_avg']=peak_len_avg m2={} m2['_tp']=tp_li m2['_fn']=fn_li m2['_fp']=fp_li return (m, m2)
def compute_global_metrics_single(Yt, Yp): """Computes precision, recall and f1-score for the single trigger word detection case. Statistics for metric computation are determined for each sample and summed over the samples. Args: Yt (numpy.ndarray): The matrix of targets #Yt = (#samples, #timesteps, 1) Yp (numpy.ndarray): The matrix of predictions #Yp = #Yt Returns: dict (str -> float or int): The dictionary of computed metrics including the count of tp, fp and including the average shift and root mean quared shift (in timesteps) of predicted peaks wrt target peaks and including the mean peak length (in timesteps) of tp predicted peaks. dict (str -> list of int): The dictionary list of samples indices for each case: * _tp: true positive, * _fp: false postive, * _fn: false negative """ tp = 0 fp = 0 fn = 0 tp_li = [] fp_li = [] fn_li = [] delta_avg = 0.0 delta_std = 0.0 peak_len_avg = 0.0 for i in range(Yt.shape[0]): pt = find_peaks(Yt[i]) pp = find_peaks(Yp[i]) TP, FP, FN = _compare_peaks(pt, pp) tp += len(TP) fp += len(FP) fn += len(FN) if len(TP)>0: tp_li.append(i) if len(FP)>0: fp_li.append(i) if len(FN)>0: fn_li.append(i) for p1, p2 in TP: de = _delta(p1,p2) delta_avg += de delta_std += de*de peak_len_avg += p2[1]-p2[0] delta_avg /= tp delta_std = math.sqrt(delta_std/tp) peak_len_avg /= tp m = _compute_metrics(tp, fp, fn) m['_tp']=tp m['_fn']=fn m['_fp']=fp m['_tp_delta_avg']=delta_avg m['_tp_delta_std']=delta_std m['_tp_peak_len_avg']=peak_len_avg m2={} m2['_tp']=tp_li m2['_fn']=fn_li m2['_fp']=fp_li return (m, m2)
Python
def compute_global_metrics_multi(Yt, Yp): """Computes precision, recall and f1-score for the multiple trigger word detection case. Statistics for metric computation are determined for each sample and summed over the samples. Here each true positives requires several conditions: * A match between two peaks in target and prediction of the overall binary feature * The existence of a corresponding prediction peak in the right class feature * The latter peak being the dominant one among all classes and having a significant magnitude Various kinds of false positive and false negatives exist in this domain: * fp due to unmatched prediction peak in the overall binary feature * fn due to unmatched target peak in the overall binary feature * fp and fn due to a wrong class prediction peak (or a weak peak, or no peak) given a correcly matched peak in the overall binary feature. in the overall binary feature Args: Yt (numpy.ndarray): The matrix of targets #Yt = (#samples, #timesteps, 1) Yp (numpy.ndarray): The matrix of predictions #Yp = #Yt Returns: dict (str -> float or int): The dictionary of computed metrics dict (str -> list of int): The dictionary list of samples indices for each case (allowing for error analysis): * _tp: true positive, * _fpb: false postive overall binary, * _fnb: false negative overall binary, * _fc: false (both positive and negative) class """ tp = 0 fpb = 0 fnb = 0 fc = 0 tp_li = [] fnb_li = [] fpb_li = [] fc_li = [] for i in range(Yt.shape[0]): ytb = Yt[i,:,:1] ypb = Yp[i,:,:1] ytm = Yt[i,:,1:] ypm = Yp[i,:,1:] PT = find_peaks(ytb) PP = find_peaks(ypb) TP, FP, FN = _compare_peaks(PT, PP) PMP = [] #peaks of the multiple prediction n_classes = ypm.shape[-1] for u in range(n_classes): PMP.append(find_peaks(ypm[:,u])) for pt, pp in TP: #analyze multi-prediction of TP of binary prediction to confirm them pt_cen = _peak_center(pt) assert np.count_nonzero(ytm[pt_cen])==1 ct = ytm[pt_cen].argmax() #true class index pmp = _match_peak(pp,PMP[ct]) #position of matching peak in PMP[ct] if pmp is None: #if no matching peak --> false class fc+=1 fc_li.append(i) continue p_avg = ypm[pmp[0]:pmp[1]].mean(axis=0) #mean around the peak of prediction for each class if p_avg.argmax()==ct and p_avg[ct]>0.5: #check that the maximum mean is scored for the correct class and that the mean itself is over a threshold tp+=1 tp_li.append(i) else: #false class fc+=1 fc_li.append(i) fpb += len(FP) if len(FP)>0: fpb_li.append(i) fnb += len(FN) if len(FN)>0: fnb_li.append(i) m = _compute_metrics(tp, fpb+fc, fnb+fc) m['_tp']=tp m['_fbn']=fnb m['_fpb']=fpb m['_fc']=fc m2={} m2['_tp']=tp_li m2['_fnb']=fnb_li m2['_fpb']=fpb_li m2['_fc']=fc_li return (m, m2)
def compute_global_metrics_multi(Yt, Yp): """Computes precision, recall and f1-score for the multiple trigger word detection case. Statistics for metric computation are determined for each sample and summed over the samples. Here each true positives requires several conditions: * A match between two peaks in target and prediction of the overall binary feature * The existence of a corresponding prediction peak in the right class feature * The latter peak being the dominant one among all classes and having a significant magnitude Various kinds of false positive and false negatives exist in this domain: * fp due to unmatched prediction peak in the overall binary feature * fn due to unmatched target peak in the overall binary feature * fp and fn due to a wrong class prediction peak (or a weak peak, or no peak) given a correcly matched peak in the overall binary feature. in the overall binary feature Args: Yt (numpy.ndarray): The matrix of targets #Yt = (#samples, #timesteps, 1) Yp (numpy.ndarray): The matrix of predictions #Yp = #Yt Returns: dict (str -> float or int): The dictionary of computed metrics dict (str -> list of int): The dictionary list of samples indices for each case (allowing for error analysis): * _tp: true positive, * _fpb: false postive overall binary, * _fnb: false negative overall binary, * _fc: false (both positive and negative) class """ tp = 0 fpb = 0 fnb = 0 fc = 0 tp_li = [] fnb_li = [] fpb_li = [] fc_li = [] for i in range(Yt.shape[0]): ytb = Yt[i,:,:1] ypb = Yp[i,:,:1] ytm = Yt[i,:,1:] ypm = Yp[i,:,1:] PT = find_peaks(ytb) PP = find_peaks(ypb) TP, FP, FN = _compare_peaks(PT, PP) PMP = [] #peaks of the multiple prediction n_classes = ypm.shape[-1] for u in range(n_classes): PMP.append(find_peaks(ypm[:,u])) for pt, pp in TP: #analyze multi-prediction of TP of binary prediction to confirm them pt_cen = _peak_center(pt) assert np.count_nonzero(ytm[pt_cen])==1 ct = ytm[pt_cen].argmax() #true class index pmp = _match_peak(pp,PMP[ct]) #position of matching peak in PMP[ct] if pmp is None: #if no matching peak --> false class fc+=1 fc_li.append(i) continue p_avg = ypm[pmp[0]:pmp[1]].mean(axis=0) #mean around the peak of prediction for each class if p_avg.argmax()==ct and p_avg[ct]>0.5: #check that the maximum mean is scored for the correct class and that the mean itself is over a threshold tp+=1 tp_li.append(i) else: #false class fc+=1 fc_li.append(i) fpb += len(FP) if len(FP)>0: fpb_li.append(i) fnb += len(FN) if len(FN)>0: fnb_li.append(i) m = _compute_metrics(tp, fpb+fc, fnb+fc) m['_tp']=tp m['_fbn']=fnb m['_fpb']=fpb m['_fc']=fc m2={} m2['_tp']=tp_li m2['_fnb']=fnb_li m2['_fpb']=fpb_li m2['_fc']=fc_li return (m, m2)
Python
def search_peak_multi(yp, confidence_thres=0.5): """Search peaks in a prediction for the multiple trigger words case. This function helps to determine whether a trigger words has been detected in the prediction of a single sample. It is to be used in the live prediction process (not for model evaluation). Args: yp (numpy.nparray): Single sample prediction #yp = (#samples, #positive_classes+1) Returns: (int,int): The first peak as (first_ts, last_ts). float: The index of the peak class. """ yb = yp[:,:1] ym = yp[:,1:] PB = find_peaks(yb,confidence_thres=confidence_thres) if len(PB)==0: return None, None n_classes = ym.shape[-1] pb = PB[0] #focusing on the first binary peak (in time) best_score = -1 best_class = None for u in range(n_classes): PM = find_peaks(ym[:,u],confidence_thres=confidence_thres) pm, ioam = _match_peak(pb,PM,return_ioam=True) if pm is None: continue pm_avg = ym[pm[0]:pm[1]].mean() score = ioam*pm_avg if score > best_score: best_score = score best_class = u return pb, best_class
def search_peak_multi(yp, confidence_thres=0.5): """Search peaks in a prediction for the multiple trigger words case. This function helps to determine whether a trigger words has been detected in the prediction of a single sample. It is to be used in the live prediction process (not for model evaluation). Args: yp (numpy.nparray): Single sample prediction #yp = (#samples, #positive_classes+1) Returns: (int,int): The first peak as (first_ts, last_ts). float: The index of the peak class. """ yb = yp[:,:1] ym = yp[:,1:] PB = find_peaks(yb,confidence_thres=confidence_thres) if len(PB)==0: return None, None n_classes = ym.shape[-1] pb = PB[0] #focusing on the first binary peak (in time) best_score = -1 best_class = None for u in range(n_classes): PM = find_peaks(ym[:,u],confidence_thres=confidence_thres) pm, ioam = _match_peak(pb,PM,return_ioam=True) if pm is None: continue pm_avg = ym[pm[0]:pm[1]].mean() score = ioam*pm_avg if score > best_score: best_score = score best_class = u return pb, best_class
Python
def predict_audio_clip_single(model, filename, plot=True, confidence_thres=0.5): """Makes prediction on a wav audioclip with a single trigger word model. Args: model (keras.models.Model): Single trigger word prediction model. filename (str): The filename (wav format) of the audioclip to predict. plot (boolean): Whether to plot the prediction. confidence_thres (float): Confidence threshold used to detect peaks (cfr. documentation of find_peaks()). Returns: numpy.ndarray: The prediction (shape = (1, #timesteps, 1)). list of (int,int): List of peaks as (first_ts, last_ts). """ rate, audio44khz = wavfile.read(filename) assert abs(rate-44100)<1 x=spectrogram(audio44khz) #del audio44khz x = np.expand_dims(x,axis=0) print(x.shape) yp = model.predict(x, batch_size=1) pp = find_peaks(yp,confidence_thres=confidence_thres) print("# peaks", len(pp)) print("Peaks:") [print(p) for p in pp] if plot: ax = plt.subplot(2, 1, 1) plt.plot(yp[0], '-b') [plt.axvline(x=p[0], color='r') for p in pp] [plt.axvline(x=p[1], color='k') for p in pp] #plt.gca().set_title("") ax.set_ylim([-.1,1.1]) ax = plt.subplot(2, 1, 2) plt.plot(audio44khz) plt.show() return yp, pp
def predict_audio_clip_single(model, filename, plot=True, confidence_thres=0.5): """Makes prediction on a wav audioclip with a single trigger word model. Args: model (keras.models.Model): Single trigger word prediction model. filename (str): The filename (wav format) of the audioclip to predict. plot (boolean): Whether to plot the prediction. confidence_thres (float): Confidence threshold used to detect peaks (cfr. documentation of find_peaks()). Returns: numpy.ndarray: The prediction (shape = (1, #timesteps, 1)). list of (int,int): List of peaks as (first_ts, last_ts). """ rate, audio44khz = wavfile.read(filename) assert abs(rate-44100)<1 x=spectrogram(audio44khz) #del audio44khz x = np.expand_dims(x,axis=0) print(x.shape) yp = model.predict(x, batch_size=1) pp = find_peaks(yp,confidence_thres=confidence_thres) print("# peaks", len(pp)) print("Peaks:") [print(p) for p in pp] if plot: ax = plt.subplot(2, 1, 1) plt.plot(yp[0], '-b') [plt.axvline(x=p[0], color='r') for p in pp] [plt.axvline(x=p[1], color='k') for p in pp] #plt.gca().set_title("") ax.set_ylim([-.1,1.1]) ax = plt.subplot(2, 1, 2) plt.plot(audio44khz) plt.show() return yp, pp
Python
def predict_audio_clip_multi(model, filename, plot=True, confidence_thres=0.5): """Makes prediction on a wav audioclip with a multiple trigger words model. Args: model (keras.models.Model): Multiple trigger words prediction model. filename (str): The filename (wav format) of the audioclip to predict. plot (boolean): Whether to plot the prediction. confidence_thres (float): Confidence threshold used to detect peaks in global binary feature (cfr. documentation of find_peaks()). Returns: numpy.ndarray: The prediction (shape = (1, #timesteps, 1)). list of (int,int): List of peaks as (first_ts, last_ts). list of int: Class predicted for each peaks. """ rate, audio44khz = wavfile.read(filename) assert abs(rate-44100)<1 x=spectrogram(audio44khz) #del audio44khz x = np.expand_dims(x,axis=0) yp = model.predict(x, batch_size=1)[0] yb = yp[:,:1] ym = yp[:,1:] #print(yp.shape, yb.shape, ym.shape) PB = find_peaks(yb,confidence_thres=confidence_thres) PC=[] n_classes = ym.shape[-1] for pb in PB: best_score = -1 best_class = None for u in range(n_classes): PM = find_peaks(ym[:,u]) pm, ioam = _match_peak(pb,PM,return_ioam=True) if pm is None: continue pm_avg = ym[pm[0]:pm[1]].mean() score = ioam*pm_avg if score > best_score: best_score = score best_class = u PC.append(best_class) print("# peaks", len(PB)) print("Peaks:") [print(p,c) for p,c in zip(PB,PC)] if plot: # PLOT BINARY ax = plt.subplot(3, 1, 1) plt.plot(audio44khz) ax.set_title("audio clip") # PLOT BINARY ax = plt.subplot(3, 1, 2) plt.plot(yb, '-b', label='binary prediction') if len(PB)>0: plt.plot(ym[:,PC[0]], '-r', label='best class prediction') [plt.axvline(x=p[0], color='r') for p in PB] [plt.axvline(x=p[1], color='k') for p in PB] plt.legend() ax.set_ylim([-.1,1.1]) # PLOT MULTI OTHERS n_classes = ym.shape[-1] if n_classes>1: ax = plt.subplot(3, 1, 3) for u in range(n_classes-1): if len(PB)>0 and u==PC[0]: continue plt.plot(ym[:,u]) ax.set_title("other class predictions") ax.set_ylim([-.1,1.1]) plt.show() plt.figure() return yp, PB, PC
def predict_audio_clip_multi(model, filename, plot=True, confidence_thres=0.5): """Makes prediction on a wav audioclip with a multiple trigger words model. Args: model (keras.models.Model): Multiple trigger words prediction model. filename (str): The filename (wav format) of the audioclip to predict. plot (boolean): Whether to plot the prediction. confidence_thres (float): Confidence threshold used to detect peaks in global binary feature (cfr. documentation of find_peaks()). Returns: numpy.ndarray: The prediction (shape = (1, #timesteps, 1)). list of (int,int): List of peaks as (first_ts, last_ts). list of int: Class predicted for each peaks. """ rate, audio44khz = wavfile.read(filename) assert abs(rate-44100)<1 x=spectrogram(audio44khz) #del audio44khz x = np.expand_dims(x,axis=0) yp = model.predict(x, batch_size=1)[0] yb = yp[:,:1] ym = yp[:,1:] #print(yp.shape, yb.shape, ym.shape) PB = find_peaks(yb,confidence_thres=confidence_thres) PC=[] n_classes = ym.shape[-1] for pb in PB: best_score = -1 best_class = None for u in range(n_classes): PM = find_peaks(ym[:,u]) pm, ioam = _match_peak(pb,PM,return_ioam=True) if pm is None: continue pm_avg = ym[pm[0]:pm[1]].mean() score = ioam*pm_avg if score > best_score: best_score = score best_class = u PC.append(best_class) print("# peaks", len(PB)) print("Peaks:") [print(p,c) for p,c in zip(PB,PC)] if plot: # PLOT BINARY ax = plt.subplot(3, 1, 1) plt.plot(audio44khz) ax.set_title("audio clip") # PLOT BINARY ax = plt.subplot(3, 1, 2) plt.plot(yb, '-b', label='binary prediction') if len(PB)>0: plt.plot(ym[:,PC[0]], '-r', label='best class prediction') [plt.axvline(x=p[0], color='r') for p in PB] [plt.axvline(x=p[1], color='k') for p in PB] plt.legend() ax.set_ylim([-.1,1.1]) # PLOT MULTI OTHERS n_classes = ym.shape[-1] if n_classes>1: ax = plt.subplot(3, 1, 3) for u in range(n_classes-1): if len(PB)>0 and u==PC[0]: continue plt.plot(ym[:,u]) ax.set_title("other class predictions") ax.set_ylim([-.1,1.1]) plt.show() plt.figure() return yp, PB, PC
Python
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Sonos platform. Obsolete.""" _LOGGER.error( 'Loading Sonos by media_player platform config is no longer supported')
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Sonos platform. Obsolete.""" _LOGGER.error( 'Loading Sonos by media_player platform config is no longer supported')
Python
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Sonos from a config entry.""" if DATA_SONOS not in hass.data: hass.data[DATA_SONOS] = SonosData(hass) config = hass.data[SONOS_DOMAIN].get('media_player', {}) advertise_addr = config.get(CONF_ADVERTISE_ADDR) if advertise_addr: pysonos.config.EVENT_ADVERTISE_IP = advertise_addr def _discovery(now=None): """Discover players from network or configuration.""" hosts = config.get(CONF_HOSTS) def _discovered_player(soco): """Handle a (re)discovered player.""" try: entity = _get_entity_from_soco_uid(hass, soco.uid) if not entity: hass.add_job(async_add_entities, [SonosEntity(soco)]) else: hass.add_job(entity.async_seen()) except SoCoException: pass if hosts: for host in hosts: try: player = pysonos.SoCo(socket.gethostbyname(host)) if player.is_visible: # Make sure that the player is available _ = player.volume _discovered_player(player) except (OSError, SoCoException): if now is None: _LOGGER.warning("Failed to initialize '%s'", host) hass.helpers.event.call_later(DISCOVERY_INTERVAL, _discovery) else: pysonos.discover_thread( _discovered_player, interval=DISCOVERY_INTERVAL, interface_addr=config.get(CONF_INTERFACE_ADDR)) hass.async_add_executor_job(_discovery) async def async_service_handle(service, data): """Handle dispatched services.""" entity_ids = data.get('entity_id') entities = hass.data[DATA_SONOS].entities if entity_ids and entity_ids != ENTITY_MATCH_ALL: entities = [e for e in entities if e.entity_id in entity_ids] if service == SERVICE_JOIN: master = [e for e in hass.data[DATA_SONOS].entities if e.entity_id == data[ATTR_MASTER]] if master: await SonosEntity.join_multi(hass, master[0], entities) elif service == SERVICE_UNJOIN: await SonosEntity.unjoin_multi(hass, entities) elif service == SERVICE_SNAPSHOT: await SonosEntity.snapshot_multi( hass, entities, data[ATTR_WITH_GROUP]) elif service == SERVICE_RESTORE: await SonosEntity.restore_multi( hass, entities, data[ATTR_WITH_GROUP]) else: for entity in entities: if service == SERVICE_SET_TIMER: call = entity.set_sleep_timer elif service == SERVICE_CLEAR_TIMER: call = entity.clear_sleep_timer elif service == SERVICE_UPDATE_ALARM: call = entity.set_alarm elif service == SERVICE_SET_OPTION: call = entity.set_option hass.async_add_executor_job(call, data) # We are ready for the next service call hass.data[DATA_SERVICE_EVENT].set() async_dispatcher_connect(hass, SONOS_DOMAIN, async_service_handle)
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Sonos from a config entry.""" if DATA_SONOS not in hass.data: hass.data[DATA_SONOS] = SonosData(hass) config = hass.data[SONOS_DOMAIN].get('media_player', {}) advertise_addr = config.get(CONF_ADVERTISE_ADDR) if advertise_addr: pysonos.config.EVENT_ADVERTISE_IP = advertise_addr def _discovery(now=None): """Discover players from network or configuration.""" hosts = config.get(CONF_HOSTS) def _discovered_player(soco): """Handle a (re)discovered player.""" try: entity = _get_entity_from_soco_uid(hass, soco.uid) if not entity: hass.add_job(async_add_entities, [SonosEntity(soco)]) else: hass.add_job(entity.async_seen()) except SoCoException: pass if hosts: for host in hosts: try: player = pysonos.SoCo(socket.gethostbyname(host)) if player.is_visible: # Make sure that the player is available _ = player.volume _discovered_player(player) except (OSError, SoCoException): if now is None: _LOGGER.warning("Failed to initialize '%s'", host) hass.helpers.event.call_later(DISCOVERY_INTERVAL, _discovery) else: pysonos.discover_thread( _discovered_player, interval=DISCOVERY_INTERVAL, interface_addr=config.get(CONF_INTERFACE_ADDR)) hass.async_add_executor_job(_discovery) async def async_service_handle(service, data): """Handle dispatched services.""" entity_ids = data.get('entity_id') entities = hass.data[DATA_SONOS].entities if entity_ids and entity_ids != ENTITY_MATCH_ALL: entities = [e for e in entities if e.entity_id in entity_ids] if service == SERVICE_JOIN: master = [e for e in hass.data[DATA_SONOS].entities if e.entity_id == data[ATTR_MASTER]] if master: await SonosEntity.join_multi(hass, master[0], entities) elif service == SERVICE_UNJOIN: await SonosEntity.unjoin_multi(hass, entities) elif service == SERVICE_SNAPSHOT: await SonosEntity.snapshot_multi( hass, entities, data[ATTR_WITH_GROUP]) elif service == SERVICE_RESTORE: await SonosEntity.restore_multi( hass, entities, data[ATTR_WITH_GROUP]) else: for entity in entities: if service == SERVICE_SET_TIMER: call = entity.set_sleep_timer elif service == SERVICE_CLEAR_TIMER: call = entity.clear_sleep_timer elif service == SERVICE_UPDATE_ALARM: call = entity.set_alarm elif service == SERVICE_SET_OPTION: call = entity.set_option hass.async_add_executor_job(call, data) # We are ready for the next service call hass.data[DATA_SERVICE_EVENT].set() async_dispatcher_connect(hass, SONOS_DOMAIN, async_service_handle)
Python
def _discovery(now=None): """Discover players from network or configuration.""" hosts = config.get(CONF_HOSTS) def _discovered_player(soco): """Handle a (re)discovered player.""" try: entity = _get_entity_from_soco_uid(hass, soco.uid) if not entity: hass.add_job(async_add_entities, [SonosEntity(soco)]) else: hass.add_job(entity.async_seen()) except SoCoException: pass if hosts: for host in hosts: try: player = pysonos.SoCo(socket.gethostbyname(host)) if player.is_visible: # Make sure that the player is available _ = player.volume _discovered_player(player) except (OSError, SoCoException): if now is None: _LOGGER.warning("Failed to initialize '%s'", host) hass.helpers.event.call_later(DISCOVERY_INTERVAL, _discovery) else: pysonos.discover_thread( _discovered_player, interval=DISCOVERY_INTERVAL, interface_addr=config.get(CONF_INTERFACE_ADDR))
def _discovery(now=None): """Discover players from network or configuration.""" hosts = config.get(CONF_HOSTS) def _discovered_player(soco): """Handle a (re)discovered player.""" try: entity = _get_entity_from_soco_uid(hass, soco.uid) if not entity: hass.add_job(async_add_entities, [SonosEntity(soco)]) else: hass.add_job(entity.async_seen()) except SoCoException: pass if hosts: for host in hosts: try: player = pysonos.SoCo(socket.gethostbyname(host)) if player.is_visible: # Make sure that the player is available _ = player.volume _discovered_player(player) except (OSError, SoCoException): if now is None: _LOGGER.warning("Failed to initialize '%s'", host) hass.helpers.event.call_later(DISCOVERY_INTERVAL, _discovery) else: pysonos.discover_thread( _discovered_player, interval=DISCOVERY_INTERVAL, interface_addr=config.get(CONF_INTERFACE_ADDR))
Python
def soco_error(errorcodes=None): """Filter out specified UPnP errors from logs and avoid exceptions.""" def decorator(funct): """Decorate functions.""" @ft.wraps(funct) def wrapper(*args, **kwargs): """Wrap for all soco UPnP exception.""" try: return funct(*args, **kwargs) except SoCoUPnPException as err: if errorcodes and err.error_code in errorcodes: pass else: _LOGGER.error("Error on %s with %s", funct.__name__, err) except SoCoException as err: _LOGGER.error("Error on %s with %s", funct.__name__, err) return wrapper return decorator
def soco_error(errorcodes=None): """Filter out specified UPnP errors from logs and avoid exceptions.""" def decorator(funct): """Decorate functions.""" @ft.wraps(funct) def wrapper(*args, **kwargs): """Wrap for all soco UPnP exception.""" try: return funct(*args, **kwargs) except SoCoUPnPException as err: if errorcodes and err.error_code in errorcodes: pass else: _LOGGER.error("Error on %s with %s", funct.__name__, err) except SoCoException as err: _LOGGER.error("Error on %s with %s", funct.__name__, err) return wrapper return decorator
Python
def wrapper(*args, **kwargs): """Wrap for all soco UPnP exception.""" try: return funct(*args, **kwargs) except SoCoUPnPException as err: if errorcodes and err.error_code in errorcodes: pass else: _LOGGER.error("Error on %s with %s", funct.__name__, err) except SoCoException as err: _LOGGER.error("Error on %s with %s", funct.__name__, err)
def wrapper(*args, **kwargs): """Wrap for all soco UPnP exception.""" try: return funct(*args, **kwargs) except SoCoUPnPException as err: if errorcodes and err.error_code in errorcodes: pass else: _LOGGER.error("Error on %s with %s", funct.__name__, err) except SoCoException as err: _LOGGER.error("Error on %s with %s", funct.__name__, err)
Python
def _is_radio_uri(uri): """Return whether the URI is a stream (not a playlist).""" radio_schemes = ( 'x-rincon-mp3radio:', 'x-sonosapi-stream:', 'x-sonosapi-radio:', 'x-sonosapi-hls:', 'hls-radio:', 'x-rincon-stream:') return uri.startswith(radio_schemes)
def _is_radio_uri(uri): """Return whether the URI is a stream (not a playlist).""" radio_schemes = ( 'x-rincon-mp3radio:', 'x-sonosapi-stream:', 'x-sonosapi-radio:', 'x-sonosapi-hls:', 'hls-radio:', 'x-rincon-stream:') return uri.startswith(radio_schemes)
Python
def state(self): """Return the state of the entity.""" if self._status in ('PAUSED_PLAYBACK', 'STOPPED'): return STATE_PAUSED if self._status in ('PLAYING', 'TRANSITIONING'): return STATE_PLAYING return STATE_IDLE
def state(self): """Return the state of the entity.""" if self._status in ('PAUSED_PLAYBACK', 'STOPPED'): return STATE_PAUSED if self._status in ('PLAYING', 'TRANSITIONING'): return STATE_PLAYING return STATE_IDLE
Python
async def async_seen(self): """Record that this player was seen right now.""" was_available = self.available if self._seen_timer: self._seen_timer() self._seen_timer = self.hass.helpers.event.async_call_later( 2.5*DISCOVERY_INTERVAL, self.async_unseen) if not was_available: await self.hass.async_add_executor_job(self._attach_player) self.async_schedule_update_ha_state()
async def async_seen(self): """Record that this player was seen right now.""" was_available = self.available if self._seen_timer: self._seen_timer() self._seen_timer = self.hass.helpers.event.async_call_later( 2.5*DISCOVERY_INTERVAL, self.async_unseen) if not was_available: await self.hass.async_add_executor_job(self._attach_player) self.async_schedule_update_ha_state()
Python
def async_unseen(self, now): """Make this player unavailable when it was not seen recently.""" self._seen_timer = None if self._poll_timer: self._poll_timer() self._poll_timer = None def _unsub(subscriptions): for subscription in subscriptions: subscription.unsubscribe() self.hass.async_add_executor_job(_unsub, self._subscriptions) self._subscriptions = [] self.async_schedule_update_ha_state()
def async_unseen(self, now): """Make this player unavailable when it was not seen recently.""" self._seen_timer = None if self._poll_timer: self._poll_timer() self._poll_timer = None def _unsub(subscriptions): for subscription in subscriptions: subscription.unsubscribe() self.hass.async_add_executor_job(_unsub, self._subscriptions) self._subscriptions = [] self.async_schedule_update_ha_state()
Python
def _attach_player(self): """Get basic information and add event subscriptions.""" self._shuffle = self.soco.shuffle self.update_volume() self._set_favorites() self._poll_timer = self.hass.helpers.event.track_time_interval( self.update, datetime.timedelta(seconds=SCAN_INTERVAL)) # New player available, build the current group topology for entity in self.hass.data[DATA_SONOS].entities: entity.update_groups() player = self.soco def subscribe(service, action): """Add a subscription to a pysonos service.""" queue = _ProcessSonosEventQueue(action) sub = service.subscribe(auto_renew=True, event_queue=queue) self._subscriptions.append(sub) subscribe(player.avTransport, self.update_media) subscribe(player.renderingControl, self.update_volume) subscribe(player.zoneGroupTopology, self.update_groups) subscribe(player.contentDirectory, self.update_content)
def _attach_player(self): """Get basic information and add event subscriptions.""" self._shuffle = self.soco.shuffle self.update_volume() self._set_favorites() self._poll_timer = self.hass.helpers.event.track_time_interval( self.update, datetime.timedelta(seconds=SCAN_INTERVAL)) # New player available, build the current group topology for entity in self.hass.data[DATA_SONOS].entities: entity.update_groups() player = self.soco def subscribe(service, action): """Add a subscription to a pysonos service.""" queue = _ProcessSonosEventQueue(action) sub = service.subscribe(auto_renew=True, event_queue=queue) self._subscriptions.append(sub) subscribe(player.avTransport, self.update_media) subscribe(player.renderingControl, self.update_volume) subscribe(player.zoneGroupTopology, self.update_groups) subscribe(player.contentDirectory, self.update_content)
Python
def update_media(self, event=None): """Update information about currently playing media.""" transport_info = self.soco.get_current_transport_info() new_status = transport_info.get('current_transport_state') # Ignore transitions, we should get the target state soon if new_status == 'TRANSITIONING': return self._shuffle = self.soco.shuffle update_position = (new_status != self._status) self._status = new_status if self.soco.is_playing_tv: self.update_media_linein(SOURCE_TV) elif self.soco.is_playing_line_in: self.update_media_linein(SOURCE_LINEIN) else: track_info = self.soco.get_current_track_info() if _is_radio_uri(track_info['uri']): variables = event and event.variables self.update_media_radio(variables, track_info) else: self.update_media_music(update_position, track_info) self.schedule_update_ha_state() # Also update slaves for entity in self.hass.data[DATA_SONOS].entities: coordinator = entity.coordinator if coordinator and coordinator.unique_id == self.unique_id: entity.schedule_update_ha_state()
def update_media(self, event=None): """Update information about currently playing media.""" transport_info = self.soco.get_current_transport_info() new_status = transport_info.get('current_transport_state') # Ignore transitions, we should get the target state soon if new_status == 'TRANSITIONING': return self._shuffle = self.soco.shuffle update_position = (new_status != self._status) self._status = new_status if self.soco.is_playing_tv: self.update_media_linein(SOURCE_TV) elif self.soco.is_playing_line_in: self.update_media_linein(SOURCE_LINEIN) else: track_info = self.soco.get_current_track_info() if _is_radio_uri(track_info['uri']): variables = event and event.variables self.update_media_radio(variables, track_info) else: self.update_media_music(update_position, track_info) self.schedule_update_ha_state() # Also update slaves for entity in self.hass.data[DATA_SONOS].entities: coordinator = entity.coordinator if coordinator and coordinator.unique_id == self.unique_id: entity.schedule_update_ha_state()
Python
def update_media_radio(self, variables, track_info): """Update state when streaming radio.""" self._media_duration = None self._media_position = None self._media_position_updated_at = None media_info = self.soco.avTransport.GetMediaInfo([('InstanceID', 0)]) self._media_image_url = self._radio_artwork(media_info['CurrentURI']) self._media_artist = track_info.get('artist') self._media_album_name = None self._media_title = track_info.get('title') if self._media_artist and self._media_title: # artist and album name are in the data, concatenate # that do display as artist. # "Information" field in the sonos pc app self._media_artist = '{artist} - {title}'.format( artist=self._media_artist, title=self._media_title ) elif variables: # "On Now" field in the sonos pc app current_track_metadata = variables.get('current_track_meta_data') if current_track_metadata: self._media_artist = \ current_track_metadata.radio_show.split(',')[0] # For radio streams we set the radio station name as the title. current_uri_metadata = media_info["CurrentURIMetaData"] if current_uri_metadata not in ('', 'NOT_IMPLEMENTED', None): # currently soco does not have an API for this current_uri_metadata = pysonos.xml.XML.fromstring( pysonos.utils.really_utf8(current_uri_metadata)) md_title = current_uri_metadata.findtext( './/{http://purl.org/dc/elements/1.1/}title') if md_title not in ('', 'NOT_IMPLEMENTED', None): self._media_title = md_title if self._media_artist and self._media_title: # some radio stations put their name into the artist # name, e.g.: # media_title = "Station" # media_artist = "Station - Artist - Title" # detect this case and trim from the front of # media_artist for cosmetics trim = '{title} - '.format(title=self._media_title) chars = min(len(self._media_artist), len(trim)) if self._media_artist[:chars].upper() == trim[:chars].upper(): self._media_artist = self._media_artist[chars:] # Check if currently playing radio station is in favorites self._source_name = None for fav in self._favorites: if fav.reference.get_uri() == media_info['CurrentURI']: self._source_name = fav.title
def update_media_radio(self, variables, track_info): """Update state when streaming radio.""" self._media_duration = None self._media_position = None self._media_position_updated_at = None media_info = self.soco.avTransport.GetMediaInfo([('InstanceID', 0)]) self._media_image_url = self._radio_artwork(media_info['CurrentURI']) self._media_artist = track_info.get('artist') self._media_album_name = None self._media_title = track_info.get('title') if self._media_artist and self._media_title: # artist and album name are in the data, concatenate # that do display as artist. # "Information" field in the sonos pc app self._media_artist = '{artist} - {title}'.format( artist=self._media_artist, title=self._media_title ) elif variables: # "On Now" field in the sonos pc app current_track_metadata = variables.get('current_track_meta_data') if current_track_metadata: self._media_artist = \ current_track_metadata.radio_show.split(',')[0] # For radio streams we set the radio station name as the title. current_uri_metadata = media_info["CurrentURIMetaData"] if current_uri_metadata not in ('', 'NOT_IMPLEMENTED', None): # currently soco does not have an API for this current_uri_metadata = pysonos.xml.XML.fromstring( pysonos.utils.really_utf8(current_uri_metadata)) md_title = current_uri_metadata.findtext( './/{http://purl.org/dc/elements/1.1/}title') if md_title not in ('', 'NOT_IMPLEMENTED', None): self._media_title = md_title if self._media_artist and self._media_title: # some radio stations put their name into the artist # name, e.g.: # media_title = "Station" # media_artist = "Station - Artist - Title" # detect this case and trim from the front of # media_artist for cosmetics trim = '{title} - '.format(title=self._media_title) chars = min(len(self._media_artist), len(trim)) if self._media_artist[:chars].upper() == trim[:chars].upper(): self._media_artist = self._media_artist[chars:] # Check if currently playing radio station is in favorites self._source_name = None for fav in self._favorites: if fav.reference.get_uri() == media_info['CurrentURI']: self._source_name = fav.title
Python
def update_media_music(self, update_media_position, track_info): """Update state when playing music tracks.""" self._media_duration = _timespan_secs(track_info.get('duration')) position_info = self.soco.avTransport.GetPositionInfo( [('InstanceID', 0), ('Channel', 'Master')] ) rel_time = _timespan_secs(position_info.get("RelTime")) # player no longer reports position? update_media_position |= rel_time is None and \ self._media_position is not None # player started reporting position? update_media_position |= rel_time is not None and \ self._media_position is None # position jumped? if (self.state == STATE_PLAYING and rel_time is not None and self._media_position is not None): time_diff = utcnow() - self._media_position_updated_at time_diff = time_diff.total_seconds() calculated_position = self._media_position + time_diff update_media_position |= abs(calculated_position - rel_time) > 1.5 if update_media_position: self._media_position = rel_time self._media_position_updated_at = utcnow() self._media_image_url = track_info.get('album_art') self._media_artist = track_info.get('artist') self._media_album_name = track_info.get('album') self._media_title = track_info.get('title') self._source_name = None
def update_media_music(self, update_media_position, track_info): """Update state when playing music tracks.""" self._media_duration = _timespan_secs(track_info.get('duration')) position_info = self.soco.avTransport.GetPositionInfo( [('InstanceID', 0), ('Channel', 'Master')] ) rel_time = _timespan_secs(position_info.get("RelTime")) # player no longer reports position? update_media_position |= rel_time is None and \ self._media_position is not None # player started reporting position? update_media_position |= rel_time is not None and \ self._media_position is None # position jumped? if (self.state == STATE_PLAYING and rel_time is not None and self._media_position is not None): time_diff = utcnow() - self._media_position_updated_at time_diff = time_diff.total_seconds() calculated_position = self._media_position + time_diff update_media_position |= abs(calculated_position - rel_time) > 1.5 if update_media_position: self._media_position = rel_time self._media_position_updated_at = utcnow() self._media_image_url = track_info.get('album_art') self._media_artist = track_info.get('artist') self._media_album_name = track_info.get('album') self._media_title = track_info.get('title') self._source_name = None
Python
def update_groups(self, event=None): """Handle callback for topology change event.""" def _get_soco_group(): """Ask SoCo cache for existing topology.""" coordinator_uid = self.unique_id slave_uids = [] try: if self.soco.group and self.soco.group.coordinator: coordinator_uid = self.soco.group.coordinator.uid slave_uids = [p.uid for p in self.soco.group.members if p.uid != coordinator_uid] except SoCoException: pass return [coordinator_uid] + slave_uids async def _async_extract_group(event): """Extract group layout from a topology event.""" group = event and event.zone_player_uui_ds_in_group if group: return group.split(',') return await self.hass.async_add_executor_job(_get_soco_group) def _async_regroup(group): """Rebuild internal group layout.""" sonos_group = [] for uid in group: entity = _get_entity_from_soco_uid(self.hass, uid) if entity: sonos_group.append(entity) self._coordinator = None self._sonos_group = sonos_group self.async_schedule_update_ha_state() for slave_uid in group[1:]: slave = _get_entity_from_soco_uid(self.hass, slave_uid) if slave: # pylint: disable=protected-access slave._coordinator = self slave._sonos_group = sonos_group slave.async_schedule_update_ha_state() async def _async_handle_group_event(event): """Get async lock and handle event.""" async with self.hass.data[DATA_SONOS].topology_condition: group = await _async_extract_group(event) if self.unique_id == group[0]: _async_regroup(group) self.hass.data[DATA_SONOS].topology_condition.notify_all() if event: # Cancel poll timer since we do receive events if self._poll_timer: self._poll_timer() self._poll_timer = None if not hasattr(event, 'zone_player_uui_ds_in_group'): return self.hass.add_job(_async_handle_group_event(event))
def update_groups(self, event=None): """Handle callback for topology change event.""" def _get_soco_group(): """Ask SoCo cache for existing topology.""" coordinator_uid = self.unique_id slave_uids = [] try: if self.soco.group and self.soco.group.coordinator: coordinator_uid = self.soco.group.coordinator.uid slave_uids = [p.uid for p in self.soco.group.members if p.uid != coordinator_uid] except SoCoException: pass return [coordinator_uid] + slave_uids async def _async_extract_group(event): """Extract group layout from a topology event.""" group = event and event.zone_player_uui_ds_in_group if group: return group.split(',') return await self.hass.async_add_executor_job(_get_soco_group) def _async_regroup(group): """Rebuild internal group layout.""" sonos_group = [] for uid in group: entity = _get_entity_from_soco_uid(self.hass, uid) if entity: sonos_group.append(entity) self._coordinator = None self._sonos_group = sonos_group self.async_schedule_update_ha_state() for slave_uid in group[1:]: slave = _get_entity_from_soco_uid(self.hass, slave_uid) if slave: # pylint: disable=protected-access slave._coordinator = self slave._sonos_group = sonos_group slave.async_schedule_update_ha_state() async def _async_handle_group_event(event): """Get async lock and handle event.""" async with self.hass.data[DATA_SONOS].topology_condition: group = await _async_extract_group(event) if self.unique_id == group[0]: _async_regroup(group) self.hass.data[DATA_SONOS].topology_condition.notify_all() if event: # Cancel poll timer since we do receive events if self._poll_timer: self._poll_timer() self._poll_timer = None if not hasattr(event, 'zone_player_uui_ds_in_group'): return self.hass.add_job(_async_handle_group_event(event))
Python
def _get_soco_group(): """Ask SoCo cache for existing topology.""" coordinator_uid = self.unique_id slave_uids = [] try: if self.soco.group and self.soco.group.coordinator: coordinator_uid = self.soco.group.coordinator.uid slave_uids = [p.uid for p in self.soco.group.members if p.uid != coordinator_uid] except SoCoException: pass return [coordinator_uid] + slave_uids
def _get_soco_group(): """Ask SoCo cache for existing topology.""" coordinator_uid = self.unique_id slave_uids = [] try: if self.soco.group and self.soco.group.coordinator: coordinator_uid = self.soco.group.coordinator.uid slave_uids = [p.uid for p in self.soco.group.members if p.uid != coordinator_uid] except SoCoException: pass return [coordinator_uid] + slave_uids
Python
def snapshot(self, with_group): """Snapshot the state of a player.""" self._soco_snapshot = pysonos.snapshot.Snapshot(self.soco) self._soco_snapshot.snapshot() if with_group: self._snapshot_group = self._sonos_group.copy() else: self._snapshot_group = None
def snapshot(self, with_group): """Snapshot the state of a player.""" self._soco_snapshot = pysonos.snapshot.Snapshot(self.soco) self._soco_snapshot.snapshot() if with_group: self._snapshot_group = self._sonos_group.copy() else: self._snapshot_group = None
Python
def restore(self): """Restore a snapshotted state to a player.""" try: # pylint: disable=protected-access self._soco_snapshot.restore() except (TypeError, AttributeError, SoCoException) as ex: # Can happen if restoring a coordinator onto a current slave _LOGGER.warning("Error on restore %s: %s", self.entity_id, ex) self._soco_snapshot = None self._snapshot_group = None
def restore(self): """Restore a snapshotted state to a player.""" try: # pylint: disable=protected-access self._soco_snapshot.restore() except (TypeError, AttributeError, SoCoException) as ex: # Can happen if restoring a coordinator onto a current slave _LOGGER.warning("Error on restore %s: %s", self.entity_id, ex) self._soco_snapshot = None self._snapshot_group = None
Python
def timer(func): """Print the runtime of the decorated function""" @functools.wraps(func) def wrapper(*args, **kwargs): print(f'Calling {func.__name__!r}') startTime = time.perf_counter() value = func(*args, **kwargs) endTime = time.perf_counter() runTime = endTime - startTime print(f'Finished {func.__name__!r} in {runTime:.4f} secs') return value return wrapper
def timer(func): """Print the runtime of the decorated function""" @functools.wraps(func) def wrapper(*args, **kwargs): print(f'Calling {func.__name__!r}') startTime = time.perf_counter() value = func(*args, **kwargs) endTime = time.perf_counter() runTime = endTime - startTime print(f'Finished {func.__name__!r} in {runTime:.4f} secs') return value return wrapper
Python
def timer(func): """Print the runtime of the decorated function""" @functools.wraps(func) def wrapper(*args, **kwargs): startTime = time.perf_counter() value = func(*args, **kwargs) endTime = time.perf_counter() runTime = endTime - startTime print(f'Finished {func.__name__!r} in {runTime:.4f} secs') return value return wrapper
def timer(func): """Print the runtime of the decorated function""" @functools.wraps(func) def wrapper(*args, **kwargs): startTime = time.perf_counter() value = func(*args, **kwargs) endTime = time.perf_counter() runTime = endTime - startTime print(f'Finished {func.__name__!r} in {runTime:.4f} secs') return value return wrapper
Python
def debug(func): """Print the function signature and return value""" @functools.wraps(func) def wrapper(*args, **kwargs): argsRepr = [repr(a) for a in args] kwargsRepr = [f"{k}={v!r}" for k, v in kwargs.items()] signature = ", ".join(argsRepr + kwargsRepr) print(f"Calling {func.__name__}({signature})") value = func(*args, **kwargs) print(f"{func.__name__!r} returned {value!r}") return value return wrapper
def debug(func): """Print the function signature and return value""" @functools.wraps(func) def wrapper(*args, **kwargs): argsRepr = [repr(a) for a in args] kwargsRepr = [f"{k}={v!r}" for k, v in kwargs.items()] signature = ", ".join(argsRepr + kwargsRepr) print(f"Calling {func.__name__}({signature})") value = func(*args, **kwargs) print(f"{func.__name__!r} returned {value!r}") return value return wrapper
Python
def slow_down_one(func): """Sleep 1 second before calling the function""" @functools.wraps(func) def wrapper(*args, **kwargs): time.sleep(1) return func(*args, **kwargs) return wrapper
def slow_down_one(func): """Sleep 1 second before calling the function""" @functools.wraps(func) def wrapper(*args, **kwargs): time.sleep(1) return func(*args, **kwargs) return wrapper
Python
def handle_data(handle, value): """ handle -- integer, characteristic read handle the data was received on value -- bytearray, the data returned in the notification """ #print("Received data: %s" % hexlify(value)) if len(value) == 18: motorOn = bool(value[2]) print("Motor status: " + ("On" if motorOn else "Off"))
def handle_data(handle, value): """ handle -- integer, characteristic read handle the data was received on value -- bytearray, the data returned in the notification """ #print("Received data: %s" % hexlify(value)) if len(value) == 18: motorOn = bool(value[2]) print("Motor status: " + ("On" if motorOn else "Off"))
Python
def check_sampler(self, cutoff=None, N=None, p0=None, adapt=False, weak=False, fail=False): ''' Check that the sampler is behaving itself. Parameters ---------- cutoff : float, optional The number of standard deviations beyond which the posterior density is zero. N : int, optional The number of iterations for which to run the sampler before checking its output. p0 : float, optional The initial positions at which to start the sampler's walkers. adapt : bool, optional If ``True``, enable adaptive parallel tempering. weak : bool, optional If ``True``, just check that the sampler ran without errors; don't check any of the results. fail : :class:`Exception`, optional If specified, assert that the sampler fails with the given exception type. ''' if cutoff is None: cutoff = self.cutoff if N is None: N = self.N if p0 is None: p0 = self.p0 if fail: # Require the sampler to fail before it even starts. try: for x in self.sampler.sample(p0, iterations=N, adapt=adapt): assert False, \ 'Sampler should have failed by now.' except Exception as e: # If a type was specified, require that the sampler fail with this exception type. assert type(fail) is not type or type(e) is fail, \ 'Sampler failed with unexpected exception type.' return else: for p, logpost, loglike, ratios in self.sampler.sample(p0, iterations=N, adapt=adapt, swap_ratios=True): assert np.all(logpost > -np.inf) and np.all(loglike > -np.inf), \ 'Invalid posterior/likelihood values; outside posterior support.' assert np.all(ratios >= 0) and np.all(ratios <= 1), \ 'Invalid swap ratios.' assert logpost.shape == loglike.shape == p.shape[:-1], \ 'Sampler output shapes invalid.' assert p.shape[-1] == self.ndim, \ 'Sampler output shapes invalid.' assert ratios.shape[0] == logpost.shape[0] - 1 and len(ratios.shape) == 1, \ 'Sampler output shapes invalid.' assert np.all(self.sampler.betas >= 0), \ 'Negative temperatures!' assert np.all(np.diff(self.sampler.betas) != 0), \ 'Temperatures have coalesced.' assert np.all(np.diff(self.sampler.betas) < 0), \ 'Temperatures incorrectly ordered.' assert np.all(self.sampler.acor > 0), \ 'Invalid autocorrelation lengths.' if not weak: # Weaker assertions on acceptance fraction assert np.mean(self.sampler.acceptance_fraction) > 0.1, \ 'Acceptance fraction < 0.1' assert np.mean(self.sampler.tswap_acceptance_fraction) > 0.1, \ 'Temperature swap acceptance fraction < 0.1.' # TODO # assert abs(self.sampler.tswap_acceptance_fraction[0] - 0.25) < 0.05, \ # 'tswap acceptance fraction != 0.25' chain = np.reshape(self.sampler.chain[0, ...], (-1, self.sampler.chain.shape[-1])) log_volume = self.ndim * np.log(cutoff) \ + log_unit_sphere_volume(self.ndim) \ + 0.5 * np.log(np.linalg.det(self.cov)) gaussian_integral = self.ndim / 2 * np.log(2 * np.pi) \ + 0.5 * np.log(np.linalg.det(self.cov)) logZ, dlogZ = self.sampler.log_evidence_estimate() assert np.abs(logZ - (gaussian_integral - log_volume)) < 3 * dlogZ, \ 'Evidence incorrect: {:g}+/{:g} versus correct {:g}.' \ .format(logZ, gaussian_integral - log_volume, dlogZ) maxdiff = 10 ** logprecision assert np.all((np.mean(chain, axis=0) - self.mean) ** 2 / N ** 2 < maxdiff), 'Mean incorrect.' assert np.all((np.cov(chain, rowvar=0) - self.cov) ** 2 / N ** 2 < maxdiff), 'Covariance incorrect.'
def check_sampler(self, cutoff=None, N=None, p0=None, adapt=False, weak=False, fail=False): ''' Check that the sampler is behaving itself. Parameters ---------- cutoff : float, optional The number of standard deviations beyond which the posterior density is zero. N : int, optional The number of iterations for which to run the sampler before checking its output. p0 : float, optional The initial positions at which to start the sampler's walkers. adapt : bool, optional If ``True``, enable adaptive parallel tempering. weak : bool, optional If ``True``, just check that the sampler ran without errors; don't check any of the results. fail : :class:`Exception`, optional If specified, assert that the sampler fails with the given exception type. ''' if cutoff is None: cutoff = self.cutoff if N is None: N = self.N if p0 is None: p0 = self.p0 if fail: # Require the sampler to fail before it even starts. try: for x in self.sampler.sample(p0, iterations=N, adapt=adapt): assert False, \ 'Sampler should have failed by now.' except Exception as e: # If a type was specified, require that the sampler fail with this exception type. assert type(fail) is not type or type(e) is fail, \ 'Sampler failed with unexpected exception type.' return else: for p, logpost, loglike, ratios in self.sampler.sample(p0, iterations=N, adapt=adapt, swap_ratios=True): assert np.all(logpost > -np.inf) and np.all(loglike > -np.inf), \ 'Invalid posterior/likelihood values; outside posterior support.' assert np.all(ratios >= 0) and np.all(ratios <= 1), \ 'Invalid swap ratios.' assert logpost.shape == loglike.shape == p.shape[:-1], \ 'Sampler output shapes invalid.' assert p.shape[-1] == self.ndim, \ 'Sampler output shapes invalid.' assert ratios.shape[0] == logpost.shape[0] - 1 and len(ratios.shape) == 1, \ 'Sampler output shapes invalid.' assert np.all(self.sampler.betas >= 0), \ 'Negative temperatures!' assert np.all(np.diff(self.sampler.betas) != 0), \ 'Temperatures have coalesced.' assert np.all(np.diff(self.sampler.betas) < 0), \ 'Temperatures incorrectly ordered.' assert np.all(self.sampler.acor > 0), \ 'Invalid autocorrelation lengths.' if not weak: # Weaker assertions on acceptance fraction assert np.mean(self.sampler.acceptance_fraction) > 0.1, \ 'Acceptance fraction < 0.1' assert np.mean(self.sampler.tswap_acceptance_fraction) > 0.1, \ 'Temperature swap acceptance fraction < 0.1.' # TODO # assert abs(self.sampler.tswap_acceptance_fraction[0] - 0.25) < 0.05, \ # 'tswap acceptance fraction != 0.25' chain = np.reshape(self.sampler.chain[0, ...], (-1, self.sampler.chain.shape[-1])) log_volume = self.ndim * np.log(cutoff) \ + log_unit_sphere_volume(self.ndim) \ + 0.5 * np.log(np.linalg.det(self.cov)) gaussian_integral = self.ndim / 2 * np.log(2 * np.pi) \ + 0.5 * np.log(np.linalg.det(self.cov)) logZ, dlogZ = self.sampler.log_evidence_estimate() assert np.abs(logZ - (gaussian_integral - log_volume)) < 3 * dlogZ, \ 'Evidence incorrect: {:g}+/{:g} versus correct {:g}.' \ .format(logZ, gaussian_integral - log_volume, dlogZ) maxdiff = 10 ** logprecision assert np.all((np.mean(chain, axis=0) - self.mean) ** 2 / N ** 2 < maxdiff), 'Mean incorrect.' assert np.all((np.cov(chain, rowvar=0) - self.cov) ** 2 / N ** 2 < maxdiff), 'Covariance incorrect.'
Python
def default_beta_ladder(ndim, ntemps=None, Tmax=None): """ Returns a ladder of :math:`\beta \equiv 1/T` under a geometric spacing that is determined by the arguments ``ntemps`` and ``Tmax``. The temperature selection algorithm works as follows: Ideally, ``Tmax`` should be specified such that the tempered posterior looks like the prior at this temperature. If using adaptive parallel tempering, per `arXiv:1501.05823 <http://arxiv.org/abs/1501.05823>`_, choosing ``Tmax = inf`` is a safe bet, so long as ``ntemps`` is also specified. :param ndim: The number of dimensions in the parameter space. :param ntemps: (optional) If set, the number of temperatures to generate. :param Tmax: (optional) If set, the maximum temperature for the ladder. Temperatures are chosen according to the following algorithm: * If neither ``ntemps`` nor ``Tmax`` is specified, raise an exception (insufficient information). * If ``ntemps`` is specified but not ``Tmax``, return a ladder spaced so that a Gaussian posterior would have a 25% temperature swap acceptance ratio. * If ``Tmax`` is specified but not ``ntemps``: * If ``Tmax = inf``, raise an exception (insufficient information). * Else, space chains geometrically as above (for 25% acceptance) until ``Tmax`` is reached. * If ``Tmax`` and ``ntemps`` are specified: * If ``Tmax = inf``, place one chain at ``inf`` and ``ntemps-1`` in a 25% geometric spacing. * Else, use the unique geometric spacing defined by ``ntemps`` and ``Tmax``. """ if type(ndim) != int or ndim < 1: raise ValueError('Invalid number of dimensions specified.') if ntemps is None and Tmax is None: raise ValueError('Must specify one of ``ntemps`` and ``Tmax``.') if Tmax is not None and Tmax <= 1: raise ValueError('``Tmax`` must be greater than 1.') if ntemps is not None and (type(ntemps) != int or ntemps < 1): raise ValueError('Invalid number of temperatures specified.') tstep = np.array([25.2741, 7., 4.47502, 3.5236, 3.0232, 2.71225, 2.49879, 2.34226, 2.22198, 2.12628, 2.04807, 1.98276, 1.92728, 1.87946, 1.83774, 1.80096, 1.76826, 1.73895, 1.7125, 1.68849, 1.66657, 1.64647, 1.62795, 1.61083, 1.59494, 1.58014, 1.56632, 1.55338, 1.54123, 1.5298, 1.51901, 1.50881, 1.49916, 1.49, 1.4813, 1.47302, 1.46512, 1.45759, 1.45039, 1.4435, 1.4369, 1.43056, 1.42448, 1.41864, 1.41302, 1.40761, 1.40239, 1.39736, 1.3925, 1.38781, 1.38327, 1.37888, 1.37463, 1.37051, 1.36652, 1.36265, 1.35889, 1.35524, 1.3517, 1.34825, 1.3449, 1.34164, 1.33847, 1.33538, 1.33236, 1.32943, 1.32656, 1.32377, 1.32104, 1.31838, 1.31578, 1.31325, 1.31076, 1.30834, 1.30596, 1.30364, 1.30137, 1.29915, 1.29697, 1.29484, 1.29275, 1.29071, 1.2887, 1.28673, 1.2848, 1.28291, 1.28106, 1.27923, 1.27745, 1.27569, 1.27397, 1.27227, 1.27061, 1.26898, 1.26737, 1.26579, 1.26424, 1.26271, 1.26121, 1.25973]) if ndim > tstep.shape[0]: # An approximation to the temperature step at large # dimension tstep = 1.0 + 2.0*np.sqrt(np.log(4.0))/np.sqrt(ndim) else: tstep = tstep[ndim-1] appendInf = False if Tmax == np.inf: appendInf = True Tmax = None ntemps = ntemps - 1 if ntemps is not None: if Tmax is None: # Determine Tmax from ntemps. Tmax = tstep ** (ntemps - 1) else: if Tmax is None: raise ValueError('Must specify at least one of ``ntemps'' and ' 'finite ``Tmax``.') # Determine ntemps from Tmax. ntemps = int(np.log(Tmax) / np.log(tstep) + 2) betas = np.logspace(0, -np.log10(Tmax), ntemps) if appendInf: # Use a geometric spacing, but replace the top-most temperature with # infinity. betas = np.concatenate((betas, [0])) return betas
def default_beta_ladder(ndim, ntemps=None, Tmax=None): """ Returns a ladder of :math:`\beta \equiv 1/T` under a geometric spacing that is determined by the arguments ``ntemps`` and ``Tmax``. The temperature selection algorithm works as follows: Ideally, ``Tmax`` should be specified such that the tempered posterior looks like the prior at this temperature. If using adaptive parallel tempering, per `arXiv:1501.05823 <http://arxiv.org/abs/1501.05823>`_, choosing ``Tmax = inf`` is a safe bet, so long as ``ntemps`` is also specified. :param ndim: The number of dimensions in the parameter space. :param ntemps: (optional) If set, the number of temperatures to generate. :param Tmax: (optional) If set, the maximum temperature for the ladder. Temperatures are chosen according to the following algorithm: * If neither ``ntemps`` nor ``Tmax`` is specified, raise an exception (insufficient information). * If ``ntemps`` is specified but not ``Tmax``, return a ladder spaced so that a Gaussian posterior would have a 25% temperature swap acceptance ratio. * If ``Tmax`` is specified but not ``ntemps``: * If ``Tmax = inf``, raise an exception (insufficient information). * Else, space chains geometrically as above (for 25% acceptance) until ``Tmax`` is reached. * If ``Tmax`` and ``ntemps`` are specified: * If ``Tmax = inf``, place one chain at ``inf`` and ``ntemps-1`` in a 25% geometric spacing. * Else, use the unique geometric spacing defined by ``ntemps`` and ``Tmax``. """ if type(ndim) != int or ndim < 1: raise ValueError('Invalid number of dimensions specified.') if ntemps is None and Tmax is None: raise ValueError('Must specify one of ``ntemps`` and ``Tmax``.') if Tmax is not None and Tmax <= 1: raise ValueError('``Tmax`` must be greater than 1.') if ntemps is not None and (type(ntemps) != int or ntemps < 1): raise ValueError('Invalid number of temperatures specified.') tstep = np.array([25.2741, 7., 4.47502, 3.5236, 3.0232, 2.71225, 2.49879, 2.34226, 2.22198, 2.12628, 2.04807, 1.98276, 1.92728, 1.87946, 1.83774, 1.80096, 1.76826, 1.73895, 1.7125, 1.68849, 1.66657, 1.64647, 1.62795, 1.61083, 1.59494, 1.58014, 1.56632, 1.55338, 1.54123, 1.5298, 1.51901, 1.50881, 1.49916, 1.49, 1.4813, 1.47302, 1.46512, 1.45759, 1.45039, 1.4435, 1.4369, 1.43056, 1.42448, 1.41864, 1.41302, 1.40761, 1.40239, 1.39736, 1.3925, 1.38781, 1.38327, 1.37888, 1.37463, 1.37051, 1.36652, 1.36265, 1.35889, 1.35524, 1.3517, 1.34825, 1.3449, 1.34164, 1.33847, 1.33538, 1.33236, 1.32943, 1.32656, 1.32377, 1.32104, 1.31838, 1.31578, 1.31325, 1.31076, 1.30834, 1.30596, 1.30364, 1.30137, 1.29915, 1.29697, 1.29484, 1.29275, 1.29071, 1.2887, 1.28673, 1.2848, 1.28291, 1.28106, 1.27923, 1.27745, 1.27569, 1.27397, 1.27227, 1.27061, 1.26898, 1.26737, 1.26579, 1.26424, 1.26271, 1.26121, 1.25973]) if ndim > tstep.shape[0]: # An approximation to the temperature step at large # dimension tstep = 1.0 + 2.0*np.sqrt(np.log(4.0))/np.sqrt(ndim) else: tstep = tstep[ndim-1] appendInf = False if Tmax == np.inf: appendInf = True Tmax = None ntemps = ntemps - 1 if ntemps is not None: if Tmax is None: # Determine Tmax from ntemps. Tmax = tstep ** (ntemps - 1) else: if Tmax is None: raise ValueError('Must specify at least one of ``ntemps'' and ' 'finite ``Tmax``.') # Determine ntemps from Tmax. ntemps = int(np.log(Tmax) / np.log(tstep) + 2) betas = np.logspace(0, -np.log10(Tmax), ntemps) if appendInf: # Use a geometric spacing, but replace the top-most temperature with # infinity. betas = np.concatenate((betas, [0])) return betas
Python
def run_mcmc(self, *args, **kwargs): """ Identical to ``sample``, but returns the final ensemble and discards intermediate ensembles. """ for x in self.sample(*args, **kwargs): pass return x
def run_mcmc(self, *args, **kwargs): """ Identical to ``sample``, but returns the final ensemble and discards intermediate ensembles. """ for x in self.sample(*args, **kwargs): pass return x
Python
def _stretch(self, p, logpost, logl): """ Perform the stretch-move proposal on each ensemble. """ for j in [0, 1]: # Get positions of walkers to be updated and walker to be sampled. jupdate = j jsample = (j + 1) % 2 pupdate = p[:, jupdate::2, :] psample = p[:, jsample::2, :] zs = np.exp(self._random.uniform(low=-np.log(self.a), high=np.log(self.a), size=(self.ntemps, self.nwalkers//2))) qs = np.zeros((self.ntemps, self.nwalkers//2, self.dim)) for k in range(self.ntemps): js = self._random.randint(0, high=self.nwalkers // 2, size=self.nwalkers // 2) qs[k, :, :] = psample[k, js, :] + zs[k, :].reshape( (self.nwalkers // 2, 1)) * (pupdate[k, :, :] - psample[k, js, :]) qslogl, qslogp = self._evaluate(qs) qslogpost = self._tempered_likelihood(qslogl) + qslogp logpaccept = self.dim*np.log(zs) + qslogpost \ - logpost[:, jupdate::2] logr = np.log(self._random.uniform(low=0.0, high=1.0, size=(self.ntemps, self.nwalkers//2))) accepts = logr < logpaccept accepts = accepts.flatten() pupdate.reshape((-1, self.dim))[accepts, :] = \ qs.reshape((-1, self.dim))[accepts, :] logpost[:, jupdate::2].reshape((-1,))[accepts] = \ qslogpost.reshape((-1,))[accepts] logl[:, jupdate::2].reshape((-1,))[accepts] = \ qslogl.reshape((-1,))[accepts] accepts = accepts.reshape((self.ntemps, self.nwalkers//2)) self.nprop[:, jupdate::2] += 1.0 self.nprop_accepted[:, jupdate::2] += accepts
def _stretch(self, p, logpost, logl): """ Perform the stretch-move proposal on each ensemble. """ for j in [0, 1]: # Get positions of walkers to be updated and walker to be sampled. jupdate = j jsample = (j + 1) % 2 pupdate = p[:, jupdate::2, :] psample = p[:, jsample::2, :] zs = np.exp(self._random.uniform(low=-np.log(self.a), high=np.log(self.a), size=(self.ntemps, self.nwalkers//2))) qs = np.zeros((self.ntemps, self.nwalkers//2, self.dim)) for k in range(self.ntemps): js = self._random.randint(0, high=self.nwalkers // 2, size=self.nwalkers // 2) qs[k, :, :] = psample[k, js, :] + zs[k, :].reshape( (self.nwalkers // 2, 1)) * (pupdate[k, :, :] - psample[k, js, :]) qslogl, qslogp = self._evaluate(qs) qslogpost = self._tempered_likelihood(qslogl) + qslogp logpaccept = self.dim*np.log(zs) + qslogpost \ - logpost[:, jupdate::2] logr = np.log(self._random.uniform(low=0.0, high=1.0, size=(self.ntemps, self.nwalkers//2))) accepts = logr < logpaccept accepts = accepts.flatten() pupdate.reshape((-1, self.dim))[accepts, :] = \ qs.reshape((-1, self.dim))[accepts, :] logpost[:, jupdate::2].reshape((-1,))[accepts] = \ qslogpost.reshape((-1,))[accepts] logl[:, jupdate::2].reshape((-1,))[accepts] = \ qslogl.reshape((-1,))[accepts] accepts = accepts.reshape((self.ntemps, self.nwalkers//2)) self.nprop[:, jupdate::2] += 1.0 self.nprop_accepted[:, jupdate::2] += accepts
Python
def synchronized(func): """synchronized decorator function This method allows the ability to add @synchronized decorator to any method. This method will wrap the decorated function around a call to threading.Lock ensuring only a single execution of the decorated method/line of code at a time. Use for ensuring thread-safe DB operations such as inserts where a last_inserted_id type action is taking place. Arguments: func {*args, **kwargs} -- [anything passed to the func will be passed through] Returns: the wrapped method. """ import threading func.__lock__ = threading.Lock() def synced_func(*args, **kws): with func.__lock__: return func(*args, **kws) return synced_func
def synchronized(func): """synchronized decorator function This method allows the ability to add @synchronized decorator to any method. This method will wrap the decorated function around a call to threading.Lock ensuring only a single execution of the decorated method/line of code at a time. Use for ensuring thread-safe DB operations such as inserts where a last_inserted_id type action is taking place. Arguments: func {*args, **kwargs} -- [anything passed to the func will be passed through] Returns: the wrapped method. """ import threading func.__lock__ = threading.Lock() def synced_func(*args, **kws): with func.__lock__: return func(*args, **kws) return synced_func
Python
def _get_db_schema(self): """_get_db_schema() For internal use only. Fetches all tables from the sqlite_master table. then executes pragma command to discover table columns. Updates _db_schema as a dict keyed by table name and containing a list of column names. The resulting schema data will be used to sanity check field names and table names in database DAL calls. """ cur = self._conn.cursor() cur.row_factory = self._dict_factory rows = cur.execute( "SELECT name FROM sqlite_master WHERE type='table'").fetchall() if rows: tables = [] for row in rows: tables.append(row['name']) self._db_schema = {} cur.row_factory = None for table in tables: cols = [] for row in cur.execute("pragma table_info('%s')" % table).fetchall(): cols.append(row[1]) self._db_schema.update({table: cols})
def _get_db_schema(self): """_get_db_schema() For internal use only. Fetches all tables from the sqlite_master table. then executes pragma command to discover table columns. Updates _db_schema as a dict keyed by table name and containing a list of column names. The resulting schema data will be used to sanity check field names and table names in database DAL calls. """ cur = self._conn.cursor() cur.row_factory = self._dict_factory rows = cur.execute( "SELECT name FROM sqlite_master WHERE type='table'").fetchall() if rows: tables = [] for row in rows: tables.append(row['name']) self._db_schema = {} cur.row_factory = None for table in tables: cols = [] for row in cur.execute("pragma table_info('%s')" % table).fetchall(): cols.append(row[1]) self._db_schema.update({table: cols})
Python
def insert(self, table, *args, **kwargs): """ Insert a record to the database. Return the record inserted to the caller if successful. Arguments: table name (required as first argument. sqlite table name) *args tuple or list of values *or* dictionary of column names and values **kwargs To insert a record as a dictionary: insert_record('table', record=record_dict) This method will insert only the columns specified in the record dictionary Returns: Returns the inserted record. """ if table not in self._db_schema.keys(): raise ValueError( 'Table name specified %s does not exist in DB.' % table) @synchronized def _insert(table, values, cols=None): """ nested insert function inserts a row into the database. Only callable inside of insert_record. Can be called from several places, depending on how insert_record is called. Arguments: table {[type]} -- [description] cols {[type]} -- [description] values {[type]} -- [description] Returns: [type] -- [description] Raises: ValueError -- [description] """ if cols: if len(cols) != len(values): raise ValueError("%s columns specified. %s values specified. Length must match" % ( len(cols), len(values))) col_list = "" qs = "" for col in cols: col_list += "%s," % col qs += "?," col_list = col_list.strip(',') qs = qs.strip(',') sql = "INSERT into %s (%s) VALUES (%s)" % (table, col_list, qs) else: qs = "" for val in values: qs += "?," qs = qs.strip(',') sql = "INSERT INTO %s VALUES (%s)" % (table, qs) cur = self._conn.cursor() cur.row_factory = self._dict_factory cur.execute(sql, values) self._conn.commit() return cur.rowcount if 'record' in kwargs.keys(): # a record has been passed with a keyword argument errors = [] columns = [] values = [] for column in kwargs['record'].keys(): if column not in self._db_schema[table]: errors.append("Column %s not in table %s" % (column, table)) else: columns.append(column) values.append(kwargs['record'][column]) if errors: raise ValueError(str(errors)) return _insert(table, values, columns) elif args and len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], tuple)): # a list of values only return _insert(table, list(args[0])) elif args and len(args) == 1 and isinstance(args[0], dict): # a single dictionary of records supplied without keyword argument record = args[0] errors = [] columns = [] values = [] for column in record.keys(): if column not in self._db_schema[table]: errors.append("Column %s not in table %s" % (column, table)) else: columns.append(column) values.append(record[column]) if errors: raise ValueError(str(errors)) return _insert(table, values, columns)
def insert(self, table, *args, **kwargs): """ Insert a record to the database. Return the record inserted to the caller if successful. Arguments: table name (required as first argument. sqlite table name) *args tuple or list of values *or* dictionary of column names and values **kwargs To insert a record as a dictionary: insert_record('table', record=record_dict) This method will insert only the columns specified in the record dictionary Returns: Returns the inserted record. """ if table not in self._db_schema.keys(): raise ValueError( 'Table name specified %s does not exist in DB.' % table) @synchronized def _insert(table, values, cols=None): """ nested insert function inserts a row into the database. Only callable inside of insert_record. Can be called from several places, depending on how insert_record is called. Arguments: table {[type]} -- [description] cols {[type]} -- [description] values {[type]} -- [description] Returns: [type] -- [description] Raises: ValueError -- [description] """ if cols: if len(cols) != len(values): raise ValueError("%s columns specified. %s values specified. Length must match" % ( len(cols), len(values))) col_list = "" qs = "" for col in cols: col_list += "%s," % col qs += "?," col_list = col_list.strip(',') qs = qs.strip(',') sql = "INSERT into %s (%s) VALUES (%s)" % (table, col_list, qs) else: qs = "" for val in values: qs += "?," qs = qs.strip(',') sql = "INSERT INTO %s VALUES (%s)" % (table, qs) cur = self._conn.cursor() cur.row_factory = self._dict_factory cur.execute(sql, values) self._conn.commit() return cur.rowcount if 'record' in kwargs.keys(): # a record has been passed with a keyword argument errors = [] columns = [] values = [] for column in kwargs['record'].keys(): if column not in self._db_schema[table]: errors.append("Column %s not in table %s" % (column, table)) else: columns.append(column) values.append(kwargs['record'][column]) if errors: raise ValueError(str(errors)) return _insert(table, values, columns) elif args and len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], tuple)): # a list of values only return _insert(table, list(args[0])) elif args and len(args) == 1 and isinstance(args[0], dict): # a single dictionary of records supplied without keyword argument record = args[0] errors = [] columns = [] values = [] for column in record.keys(): if column not in self._db_schema[table]: errors.append("Column %s not in table %s" % (column, table)) else: columns.append(column) values.append(record[column]) if errors: raise ValueError(str(errors)) return _insert(table, values, columns)
Python
def update(self, table, *args, **kwargs): """update(table, args, kwargs) Update rows in table. first argument after table must be a dictionary of column:value pairs. named argument criteria must be an array of tuples in the form: (column, operator, value) Multiple criteria are stitched together with AND. All criteria must be true in order for operation to succeed Example: update('test', {'firstname':'Frank'}, criteria=[('id', '=', 1)]) Decorators: synchronized Arguments: table {[type]} -- [description] *args {[type]} -- [description] **kwargs {[type]} -- [description] Returns: [int] -- [number of rows affected] Raises: ValueError -- [if table name is not specified] ValueError -- [if criteria is not passed] - potentially dangerous update that would change all rows """ if table not in self._db_schema.keys(): raise ValueError( 'Table name specified %s does not exist in DB.' % table) sql = "UPDATE %s SET" % table if args and len(args) == 1 and isinstance(args[0], dict): # fields to update dict is only non keyword arg val_array = [] for (col, val) in args[0].items(): sql += " %s = ?," % col val_array.append(val) sql = sql.strip(',') if 'criteria' in kwargs.keys(): # criteria passed as keword argument num_criteria = len(kwargs['criteria']) x = 0 sql += " WHERE " criterium = [] for (field, op, criteria) in kwargs['criteria']: sql += "%s %s ? " % (str(field), str(op)) criterium.append(str(criteria)) x += 1 if x < num_criteria: sql += "AND " r = self._conn.execute(sql, val_array + criterium) self._conn.commit() return r.rowcount else: raise ValueError( "criteria not specified. Dangerous update aborted.")
def update(self, table, *args, **kwargs): """update(table, args, kwargs) Update rows in table. first argument after table must be a dictionary of column:value pairs. named argument criteria must be an array of tuples in the form: (column, operator, value) Multiple criteria are stitched together with AND. All criteria must be true in order for operation to succeed Example: update('test', {'firstname':'Frank'}, criteria=[('id', '=', 1)]) Decorators: synchronized Arguments: table {[type]} -- [description] *args {[type]} -- [description] **kwargs {[type]} -- [description] Returns: [int] -- [number of rows affected] Raises: ValueError -- [if table name is not specified] ValueError -- [if criteria is not passed] - potentially dangerous update that would change all rows """ if table not in self._db_schema.keys(): raise ValueError( 'Table name specified %s does not exist in DB.' % table) sql = "UPDATE %s SET" % table if args and len(args) == 1 and isinstance(args[0], dict): # fields to update dict is only non keyword arg val_array = [] for (col, val) in args[0].items(): sql += " %s = ?," % col val_array.append(val) sql = sql.strip(',') if 'criteria' in kwargs.keys(): # criteria passed as keword argument num_criteria = len(kwargs['criteria']) x = 0 sql += " WHERE " criterium = [] for (field, op, criteria) in kwargs['criteria']: sql += "%s %s ? " % (str(field), str(op)) criterium.append(str(criteria)) x += 1 if x < num_criteria: sql += "AND " r = self._conn.execute(sql, val_array + criterium) self._conn.commit() return r.rowcount else: raise ValueError( "criteria not specified. Dangerous update aborted.")
Python
def create_data_excels(self, path, force_rewrite=False): """Writes the parameter excel files with the default values and required indexing by passing an arbitary path .. note:: The input data files are including regional parameter files and global and connections parameter files in case of multi-node model Parameters ---------- path : str path defines the directory where model parameter files are going to be witten. It can be different from the path where set files are located force_rewrite : boolean to avoid over writing the parameters, this will stop the code if the same file already exists. In case, you need to over-write, force_rewrite = True will do it """ if os.path.exists(path): if not force_rewrite: raise ResultOverWrite( f"Folder {path} already exists. To over write" f" the parameter files, use force_rewrite=True." ) else: shutil.rmtree(path) os.mkdir(path) self._StrData._write_input_excel(path)
def create_data_excels(self, path, force_rewrite=False): """Writes the parameter excel files with the default values and required indexing by passing an arbitary path .. note:: The input data files are including regional parameter files and global and connections parameter files in case of multi-node model Parameters ---------- path : str path defines the directory where model parameter files are going to be witten. It can be different from the path where set files are located force_rewrite : boolean to avoid over writing the parameters, this will stop the code if the same file already exists. In case, you need to over-write, force_rewrite = True will do it """ if os.path.exists(path): if not force_rewrite: raise ResultOverWrite( f"Folder {path} already exists. To over write" f" the parameter files, use force_rewrite=True." ) else: shutil.rmtree(path) os.mkdir(path) self._StrData._write_input_excel(path)
Python
def read_input_data(self, path): """Reades the filled input data excel files by passing the path where they are located Parameters ------- path : str path defines the directory where the filled input parameter files are located. It can be different from the path where the parameter files with default values were written """ self._StrData._read_data(path)
def read_input_data(self, path): """Reades the filled input data excel files by passing the path where they are located Parameters ------- path : str path defines the directory where the filled input parameter files are located. It can be different from the path where the parameter files with default values were written """ self._StrData._read_data(path)
Python
def run(self, solver, verbosity=True, force_rewrite=False, **kwargs): """ Run the model by passing the solver, verbosity and force_rewrite. .. note:: The passed solver must be in the installed solvers package of the DSL (CVXPY). Parameters --------- solver : str Solver indicates for kind of solver to be used. verbosity : Boolean Verbosity overrides the default of hiding solver output force_rewrite : boolean If the force_rewrite is True, any existing results will be overwritten and the previous results will be saved in a back-up file. kwargs : Optional solver specific options. for more information refer to `cvxpy documentation <https://www.cvxpy.org/api_reference/cvxpy.problems.html?highlight=solve#cvxpy.problems.problem.Problem.solve>`_ """ # checks if the input parameters are imported to the model if not hasattr(self._StrData, "data"): raise DataNotImported( "No data is imported to the model. Use " "'read_input_data' function." ) # checks if the model is already solved when force_rewrite is false # and takes a backup of previous results if force_rewrite is true if hasattr(self, "results"): if not force_rewrite: raise ResultOverWrite( "Model is already solved." "To overwrite the results change " "'force_rewrite'= True" ) self.backup_results = deepcopy(self.results) delattr(self, "results") # checks if the given solver is in the installed solver package if solver.upper() not in installed_solvers(): raise SolverNotFound( f"Installed solvers on your system are {installed_solvers()}" ) model = BuildModel(sets=self._StrData) results = model._solve(verbosity=verbosity, solver=solver.upper(), **kwargs) self.check = results if results is not None: results = set_DataFrame( results=results, regions=self._StrData.regions, years=self._StrData.main_years, time_fraction=self._StrData.time_steps, glob_mapping=self._StrData.glob_mapping, technologies=self._StrData.Technologies, mode=self._StrData.mode, ) self.results = results
def run(self, solver, verbosity=True, force_rewrite=False, **kwargs): """ Run the model by passing the solver, verbosity and force_rewrite. .. note:: The passed solver must be in the installed solvers package of the DSL (CVXPY). Parameters --------- solver : str Solver indicates for kind of solver to be used. verbosity : Boolean Verbosity overrides the default of hiding solver output force_rewrite : boolean If the force_rewrite is True, any existing results will be overwritten and the previous results will be saved in a back-up file. kwargs : Optional solver specific options. for more information refer to `cvxpy documentation <https://www.cvxpy.org/api_reference/cvxpy.problems.html?highlight=solve#cvxpy.problems.problem.Problem.solve>`_ """ # checks if the input parameters are imported to the model if not hasattr(self._StrData, "data"): raise DataNotImported( "No data is imported to the model. Use " "'read_input_data' function." ) # checks if the model is already solved when force_rewrite is false # and takes a backup of previous results if force_rewrite is true if hasattr(self, "results"): if not force_rewrite: raise ResultOverWrite( "Model is already solved." "To overwrite the results change " "'force_rewrite'= True" ) self.backup_results = deepcopy(self.results) delattr(self, "results") # checks if the given solver is in the installed solver package if solver.upper() not in installed_solvers(): raise SolverNotFound( f"Installed solvers on your system are {installed_solvers()}" ) model = BuildModel(sets=self._StrData) results = model._solve(verbosity=verbosity, solver=solver.upper(), **kwargs) self.check = results if results is not None: results = set_DataFrame( results=results, regions=self._StrData.regions, years=self._StrData.main_years, time_fraction=self._StrData.time_steps, glob_mapping=self._StrData.glob_mapping, technologies=self._StrData.Technologies, mode=self._StrData.mode, ) self.results = results
Python
def to_csv(self, path, force_rewrite=False): """Exports the results of the model to csv files with nested folders Parameters ---------- path : str Defines the path to th 'folder' which all the results will be created. force_rewrite : boolean if False, will stop the code in case the file already exists, if True, will delete the file if alreadey exists and create a new one """ if not hasattr(self, "results"): raise WrongInputMode("model has not any results") if os.path.exists(path): if not force_rewrite: raise ResultOverWrite( f"Folder {path} already exists. To over write" f" the results, use force_rewrite=True." ) else: os.mkdir(path) dict_to_csv(self.results, path)
def to_csv(self, path, force_rewrite=False): """Exports the results of the model to csv files with nested folders Parameters ---------- path : str Defines the path to th 'folder' which all the results will be created. force_rewrite : boolean if False, will stop the code in case the file already exists, if True, will delete the file if alreadey exists and create a new one """ if not hasattr(self, "results"): raise WrongInputMode("model has not any results") if os.path.exists(path): if not force_rewrite: raise ResultOverWrite( f"Folder {path} already exists. To over write" f" the results, use force_rewrite=True." ) else: os.mkdir(path) dict_to_csv(self.results, path)
Python
def create_config_file(self, path): """Creates a config excel file for plots Parameters ---------- path : str defines the path and the name of the excel file to be created. """ techs_property = {"tech_name": list(self._StrData.glob_mapping["Technologies_glob"]["Tech_name"]), "tech_group": '', "tech_color": '', "tech_cap_unit": list(self._StrData.glob_mapping["Technologies_glob"]["Tech_cap_unit"]), "tech_production_unit": list(self._StrData.glob_mapping["Technologies_glob"]["Tech_act_unit"]),} techs_sheet = pd.DataFrame(techs_property, index=self._StrData.glob_mapping["Technologies_glob"]["Technology"], ) fuels_property = {"fuel_name": list(self._StrData.glob_mapping["Carriers_glob"]["Carr_name"]), "fuel_group": '', "fuel_color": '', "fuel_unit": list(self._StrData.glob_mapping["Carriers_glob"]["Carr_unit"]),} fuels_sheet = pd.DataFrame(fuels_property, index=self._StrData.glob_mapping["Carriers_glob"]["Carrier"], ) regions_property = {"region_name": list(self._StrData.glob_mapping["Regions"]["Region_name"]), "region_color": '',} regions_sheet = pd.DataFrame(regions_property, index=self._StrData.glob_mapping["Regions"]["Region"], ) emissions_sheet = self._StrData.glob_mapping['Emissions'].set_index(['Emission'],inplace=False) emissions_sheet = pd.DataFrame( emissions_sheet.values, index = emissions_sheet.index, columns = ['emission_name','emission_unit'] ) emissions_sheet.index.name = 'Emission' with pd.ExcelWriter(path) as file: for sheet in [ "techs_sheet", "fuels_sheet", "regions_sheet", "emissions_sheet", ]: eval(sheet).to_excel(file, sheet_name=sheet.split("_")[0].title())
def create_config_file(self, path): """Creates a config excel file for plots Parameters ---------- path : str defines the path and the name of the excel file to be created. """ techs_property = {"tech_name": list(self._StrData.glob_mapping["Technologies_glob"]["Tech_name"]), "tech_group": '', "tech_color": '', "tech_cap_unit": list(self._StrData.glob_mapping["Technologies_glob"]["Tech_cap_unit"]), "tech_production_unit": list(self._StrData.glob_mapping["Technologies_glob"]["Tech_act_unit"]),} techs_sheet = pd.DataFrame(techs_property, index=self._StrData.glob_mapping["Technologies_glob"]["Technology"], ) fuels_property = {"fuel_name": list(self._StrData.glob_mapping["Carriers_glob"]["Carr_name"]), "fuel_group": '', "fuel_color": '', "fuel_unit": list(self._StrData.glob_mapping["Carriers_glob"]["Carr_unit"]),} fuels_sheet = pd.DataFrame(fuels_property, index=self._StrData.glob_mapping["Carriers_glob"]["Carrier"], ) regions_property = {"region_name": list(self._StrData.glob_mapping["Regions"]["Region_name"]), "region_color": '',} regions_sheet = pd.DataFrame(regions_property, index=self._StrData.glob_mapping["Regions"]["Region"], ) emissions_sheet = self._StrData.glob_mapping['Emissions'].set_index(['Emission'],inplace=False) emissions_sheet = pd.DataFrame( emissions_sheet.values, index = emissions_sheet.index, columns = ['emission_name','emission_unit'] ) emissions_sheet.index.name = 'Emission' with pd.ExcelWriter(path) as file: for sheet in [ "techs_sheet", "fuels_sheet", "regions_sheet", "emissions_sheet", ]: eval(sheet).to_excel(file, sheet_name=sheet.split("_")[0].title())
Python
def parse_cns_genotype_file(filename, absent_threshold=0.2, present_threshold=0.8, maf_count=5, min_total_count = 17): # 25 peers and 3 pcs """ read the cns length and coverage file and return a inter genotype table """ individs = [] with open(filename) as f: line = f.readline() l = list(map(str.strip, line.split())) for i in range(2, len(l)): individs.append(l[i]) num_individs = len(individs) all_snps = {'chrs': [], 'positions': [], 'ends':[], 'snps': []} with open(filename) as f: for line_i, line in enumerate(f): if line_i > 0: l = list(map(str.strip, line.split())) m = re.search('^(\d+):(\d+)\-(\d+)', l[0]) if (m != None): chrom = int(m.group(1)) snp = np.zeros(num_individs, dtype='float') cns_length = float(l[1]) an = 0 # absent count pn = 0 # present count for i in range(2, num_individs+2, 1): nt = float(l[i])/float(cns_length) if nt <= absent_threshold: snp[i-2] = 0.0 an = an + 1 elif nt >=present_threshold: snp[i-2] = 1.0 pn = pn + 1 else: snp[i-2] = 3.0 #missing all_snps['chrs'].append(chrom) all_snps['positions'].append(int(m.group(2))) all_snps['ends'].append(int(m.group(3))) all_snps['snps'].append(snp) return all_snps, individs
def parse_cns_genotype_file(filename, absent_threshold=0.2, present_threshold=0.8, maf_count=5, min_total_count = 17): # 25 peers and 3 pcs """ read the cns length and coverage file and return a inter genotype table """ individs = [] with open(filename) as f: line = f.readline() l = list(map(str.strip, line.split())) for i in range(2, len(l)): individs.append(l[i]) num_individs = len(individs) all_snps = {'chrs': [], 'positions': [], 'ends':[], 'snps': []} with open(filename) as f: for line_i, line in enumerate(f): if line_i > 0: l = list(map(str.strip, line.split())) m = re.search('^(\d+):(\d+)\-(\d+)', l[0]) if (m != None): chrom = int(m.group(1)) snp = np.zeros(num_individs, dtype='float') cns_length = float(l[1]) an = 0 # absent count pn = 0 # present count for i in range(2, num_individs+2, 1): nt = float(l[i])/float(cns_length) if nt <= absent_threshold: snp[i-2] = 0.0 an = an + 1 elif nt >=present_threshold: snp[i-2] = 1.0 pn = pn + 1 else: snp[i-2] = 3.0 #missing all_snps['chrs'].append(chrom) all_snps['positions'].append(int(m.group(2))) all_snps['ends'].append(int(m.group(3))) all_snps['snps'].append(snp) return all_snps, individs
Python
def parse_cns_genotype_file_proportion(filename): """ read the cns length and coverage file and return a inter genotype table """ individs = [] with open(filename) as f: line = f.readline() l = list(map(str.strip, line.split())) for i in range(2, len(l)): individs.append(l[i]) num_individs = len(individs) all_snps = {'chrs': [], 'positions': [], 'ends':[], 'snps': []} with open(filename) as f: for line_i, line in enumerate(f): if line_i > 0: l = list(map(str.strip, line.split())) m = re.search('^(\d+):(\d+)\-(\d+)', l[0]) if (m != None): chrom = int(m.group(1)) snp = np.zeros(num_individs, dtype='float') cns_length = float(l[1]) for i in range(2, num_individs+2, 1): nt = float(l[i])/float(cns_length) snp[i-2] = nt all_snps['chrs'].append(chrom) all_snps['positions'].append(int(m.group(2))) all_snps['ends'].append(int(m.group(3))) all_snps['snps'].append(snp) return all_snps, individs
def parse_cns_genotype_file_proportion(filename): """ read the cns length and coverage file and return a inter genotype table """ individs = [] with open(filename) as f: line = f.readline() l = list(map(str.strip, line.split())) for i in range(2, len(l)): individs.append(l[i]) num_individs = len(individs) all_snps = {'chrs': [], 'positions': [], 'ends':[], 'snps': []} with open(filename) as f: for line_i, line in enumerate(f): if line_i > 0: l = list(map(str.strip, line.split())) m = re.search('^(\d+):(\d+)\-(\d+)', l[0]) if (m != None): chrom = int(m.group(1)) snp = np.zeros(num_individs, dtype='float') cns_length = float(l[1]) for i in range(2, num_individs+2, 1): nt = float(l[i])/float(cns_length) snp[i-2] = nt all_snps['chrs'].append(chrom) all_snps['positions'].append(int(m.group(2))) all_snps['ends'].append(int(m.group(3))) all_snps['snps'].append(snp) return all_snps, individs
Python
def parse_gene_present_absent_file(filename, absent_threshold=0.4): """ read the gene length and coverage file and return a inter gene present absent table """ individs = {} # taxa name to index with open(filename) as f: line = f.readline() l = list(map(str.strip, line.split())) for i in range(3, len(l)): individs[l[i]] = i-3 num_individs = len(individs) genes = {} all_genes = {'chrs': [], 'positions': [], 'ends': [], 'genes': []} with open(filename) as f: for line_i, line in enumerate(f): if line_i > 0: l = list(map(str.strip, line.split())) m = re.search('^(\S+):(\d+)\-(\d+)', l[1]) genes[l[0]] = line_i-1 if (m != None): chrom = m.group(1) gene = np.zeros(num_individs, dtype='float') gene_length = float(l[2]) for i in range(3, num_individs+3, 1): nt = float(l[i])/float(gene_length) if nt <= absent_threshold: gene[i-3] = 0.0 else: gene[i-3] = 1.0 all_genes['chrs'].append(chrom) all_genes['positions'].append(int(m.group(2))) all_genes['ends'].append(int(m.group(3))) all_genes['genes'].append(gene) return all_genes, individs, genes
def parse_gene_present_absent_file(filename, absent_threshold=0.4): """ read the gene length and coverage file and return a inter gene present absent table """ individs = {} # taxa name to index with open(filename) as f: line = f.readline() l = list(map(str.strip, line.split())) for i in range(3, len(l)): individs[l[i]] = i-3 num_individs = len(individs) genes = {} all_genes = {'chrs': [], 'positions': [], 'ends': [], 'genes': []} with open(filename) as f: for line_i, line in enumerate(f): if line_i > 0: l = list(map(str.strip, line.split())) m = re.search('^(\S+):(\d+)\-(\d+)', l[1]) genes[l[0]] = line_i-1 if (m != None): chrom = m.group(1) gene = np.zeros(num_individs, dtype='float') gene_length = float(l[2]) for i in range(3, num_individs+3, 1): nt = float(l[i])/float(gene_length) if nt <= absent_threshold: gene[i-3] = 0.0 else: gene[i-3] = 1.0 all_genes['chrs'].append(chrom) all_genes['positions'].append(int(m.group(2))) all_genes['ends'].append(int(m.group(3))) all_genes['genes'].append(gene) return all_genes, individs, genes
Python
def parse_cns_genotype_file(filename, absent_threshold=0.2, present_threshold=0.8, maf_count=5, min_total_count = 17): # 25 peers and 3 pcs """ read the cns length and coverage file and return a inter genotype table """ individs = [] with open(filename) as f: line = f.readline() l = list(map(str.strip, line.split())) for i in range(2, len(l)): individs.append(l[i]) num_individs = len(individs) all_snps = {'chrs': [], 'positions': [], 'ends':[], 'snps': []} with open(filename) as f: for line_i, line in enumerate(f): if line_i > 0: l = list(map(str.strip, line.split())) m = re.search('^(\d+):(\d+)\-(\d+)', l[0]) if (m != None): chrom = int(m.group(1)) snp = np.zeros(num_individs, dtype='float') cns_length = float(l[1]) an = 0 # absent count pn = 0 # present count for i in range(2, num_individs+2, 1): nt = float(l[i])/float(cns_length) if nt <= absent_threshold: snp[i-2] = 0.0 an = an + 1 elif nt >=present_threshold: snp[i-2] = 1.0 pn = pn + 1 else: snp[i-2] = 3.0 #missing if( an >= maf_count and pn >= maf_count and (an+pn)>=min_total_count ): all_snps['chrs'].append(chrom) all_snps['positions'].append(int(m.group(2))) all_snps['ends'].append(int(m.group(3))) all_snps['snps'].append(snp) return all_snps, individs
def parse_cns_genotype_file(filename, absent_threshold=0.2, present_threshold=0.8, maf_count=5, min_total_count = 17): # 25 peers and 3 pcs """ read the cns length and coverage file and return a inter genotype table """ individs = [] with open(filename) as f: line = f.readline() l = list(map(str.strip, line.split())) for i in range(2, len(l)): individs.append(l[i]) num_individs = len(individs) all_snps = {'chrs': [], 'positions': [], 'ends':[], 'snps': []} with open(filename) as f: for line_i, line in enumerate(f): if line_i > 0: l = list(map(str.strip, line.split())) m = re.search('^(\d+):(\d+)\-(\d+)', l[0]) if (m != None): chrom = int(m.group(1)) snp = np.zeros(num_individs, dtype='float') cns_length = float(l[1]) an = 0 # absent count pn = 0 # present count for i in range(2, num_individs+2, 1): nt = float(l[i])/float(cns_length) if nt <= absent_threshold: snp[i-2] = 0.0 an = an + 1 elif nt >=present_threshold: snp[i-2] = 1.0 pn = pn + 1 else: snp[i-2] = 3.0 #missing if( an >= maf_count and pn >= maf_count and (an+pn)>=min_total_count ): all_snps['chrs'].append(chrom) all_snps['positions'].append(int(m.group(2))) all_snps['ends'].append(int(m.group(3))) all_snps['snps'].append(snp) return all_snps, individs
Python
def normweight(G,weights='real'): """ Normalizes the "weight" attributes of edges of G by their total sum. Parameters: G (nx.DiGraph): A directed graph with a "weight" attribute on edges. weights (string): Chooses which weights are placed on edges: - 'random': Uniformly chosen in (0,1) - 'uniform': Each edge has equal weight - 'real': Normalizes existing weights Returns: G (nx.DiGraph): A directed graph such that the sum of all "weight" attributes on edges is equal to 1. """ if weights == 'random': w = np.random.uniform(1e-5, 1.0, G.number_of_edges()) w /= sum(w) c = 0 for i in list(G.edges()): G[i[0]][i[1]]['weight'] = w[c] c += 1 elif weights == 'uniform': w = 1.0/G.number_of_edges() for i in list(G.edges()): G[i[0]][i[1]]['weight'] = w else: out_degrees = [val for (node, val) in G.out_degree(weight='weight')] nrm = float(sum(out_degrees)) for i in list(G.edges(data=True)): G[i[0]][i[1]]['weight'] = i[-1]['weight']/nrm return G
def normweight(G,weights='real'): """ Normalizes the "weight" attributes of edges of G by their total sum. Parameters: G (nx.DiGraph): A directed graph with a "weight" attribute on edges. weights (string): Chooses which weights are placed on edges: - 'random': Uniformly chosen in (0,1) - 'uniform': Each edge has equal weight - 'real': Normalizes existing weights Returns: G (nx.DiGraph): A directed graph such that the sum of all "weight" attributes on edges is equal to 1. """ if weights == 'random': w = np.random.uniform(1e-5, 1.0, G.number_of_edges()) w /= sum(w) c = 0 for i in list(G.edges()): G[i[0]][i[1]]['weight'] = w[c] c += 1 elif weights == 'uniform': w = 1.0/G.number_of_edges() for i in list(G.edges()): G[i[0]][i[1]]['weight'] = w else: out_degrees = [val for (node, val) in G.out_degree(weight='weight')] nrm = float(sum(out_degrees)) for i in list(G.edges(data=True)): G[i[0]][i[1]]['weight'] = i[-1]['weight']/nrm return G
Python
def undirtodirected(edges,gccedges): """ Returns the directed subgraph containing all edges in gccedges Parameters: edges (dict): Dictionary of directed edges in G gccedges (nx.OutEdgeView): View of the edges of the undirected maximal connected component of G Returns: Gccm (nx.DiGraph): The maximal connected component as a directed graph dicoedgeccm (dict): Dictionary indexed by the edges of Gccm """ Gccm = nx.DiGraph() dicoedgeccm ={} for edge in gccedges: if edge in edges.keys(): dicoedgeccm[edge]=None # Placeholder value Gccm.add_edge(edge[0],edge[1], weight= edges[edge]) #Retourne la composante connexe maximale agregee connexe ponderee return Gccm, dicoedgeccm
def undirtodirected(edges,gccedges): """ Returns the directed subgraph containing all edges in gccedges Parameters: edges (dict): Dictionary of directed edges in G gccedges (nx.OutEdgeView): View of the edges of the undirected maximal connected component of G Returns: Gccm (nx.DiGraph): The maximal connected component as a directed graph dicoedgeccm (dict): Dictionary indexed by the edges of Gccm """ Gccm = nx.DiGraph() dicoedgeccm ={} for edge in gccedges: if edge in edges.keys(): dicoedgeccm[edge]=None # Placeholder value Gccm.add_edge(edge[0],edge[1], weight= edges[edge]) #Retourne la composante connexe maximale agregee connexe ponderee return Gccm, dicoedgeccm