How to use test_signals method in pytest-django

Best Python code snippet using pytest-django_python

generate_test_signals.py

Source:generate_test_signals.py Github

copy

Full Screen

1import pandas as pd2import numpy as np3from sklearn.model_selection import train_test_split4from feature_extraction import mean_absolute_value5from feature_extraction import variance6from feature_extraction import standard_error7from feature_extraction import root_mean_square8from feature_extraction import slope_sign_change9from feature_extraction import waveform_length10import matplotlib.pyplot as plt11import matplotlib.patches as mpatches12# Extract signal files13"""14from zipfile import ZipFile15file_name1 = "dataframe_no_signal_compressed.zip"16file_name2 = 'labelled_signal_data_epochs_compressed.zip'17with ZipFile(file_name1, 'r') as zip:18 zip.printdir()19 print('Extracting files from dataframe_no_signal_compressed.zip...')20 zip.extractall()21 print('Done')22with ZipFile(file_name2, 'r') as zip:23 zip.printdir()24 print('Extracting files from labelled_signal_data_epochs_compressed.zip...')25 zip.extractall()26 print('Done')27"""28# Load signal files29labelled_signals = np.loadtxt('./labelled_signal_data_epochs.txt')30df = pd.read_csv('./dataframe_no_signal.csv')31# Assemble into dataframe32df['signal'] = labelled_signals.tolist()33df['signal'] = df['signal'].apply(np.array)34df['signal'] = df['signal'].apply(lambda x: 1000*x) # Convert from V to mV35# X data will be the unique IDs, they will allow indexing of the signals properly36# y data will be class labels37cls_1_ids = df.loc[df['label']==1, 'id'].unique()38cls_2_ids = df.loc[df['label']==2, 'id'].unique()39cls_3_ids = df.loc[df['label']==3, 'id'].unique()40# ids and labels is order [1, 1, 1, 1, 1, ..., 1, 2, 2, 2, 2, 2, ..., 2]41cls_ids_12 = np.append(cls_1_ids, cls_2_ids)42cls_ids_23 = np.append(cls_2_ids, cls_3_ids)43cls_labels_12 = np.append(np.ones((cls_1_ids.size,)), np.ones((cls_2_ids.size,)) * 2)44cls_labels_23 = np.append(np.ones((cls_2_ids.size,)) * 2, np.ones((cls_3_ids.size,)) * 3)45# Split data46X_train_12, X_test_12, y_train, y_test = train_test_split(cls_ids_12, cls_labels_12, test_size=0.25, random_state=0)47X_train_23, X_test_23, y_train, y_test = train_test_split(cls_ids_23, cls_labels_23, test_size=0.25, random_state=0)48def get_train_signals_2a(cls, channel):49 """50 :param cls: class label (integer 1 or 2)51 :param channel: channel number (integer between 1 and 8)52 :return: N x 256 array of signals of selected class and channel53 """54 cls_signals = df.loc[(df['id'].isin(X_train_12)) & (df['label'] == cls), 'signal'].values.tolist()55 cls_signals = np.array(cls_signals)56 cls_signals = np.reshape(cls_signals, (cls_signals.shape[0] // 8, 8, 256))57 return cls_signals[:, channel-1, :]58def get_train_signals_2b(cls, channel):59 """60 :param cls: class label (integer 2 or 3)61 :param channel: channel number (integer between 1 and 8)62 :return: N x 256 array of signals of selected class and channel63 """64 cls_signals = df.loc[(df['id'].isin(X_train_23)) & (df['label'] == cls), 'signal'].values.tolist()65 cls_signals = np.array(cls_signals)66 cls_signals = np.reshape(cls_signals, (cls_signals.shape[0] // 8, 8, 256))67 return cls_signals[:, channel-1, :]68def test_classifier_2a(classifier_fun):69 """70 Tests accuracy of manual classifier function on test data for class 1 and 271 :param classifier_fun: function that returns class based on input 8x256 nd-array of a single signal epoch72 :return: Accuracy score73 """74 test_signals = df.loc[(df['id'].isin(X_test_12)), 'signal'].values.tolist()75 test_signals = np.array(test_signals)76 test_signals = np.reshape(test_signals, (test_signals.shape[0] // 8, 8, 256))77 # Get labels from df. Since it's repeated 8 times for each channel, only pull every 8th one78 ys = df.loc[(df['id'].isin(X_test_12)), 'label'].values79 ys = ys[::8]80 classifier_output = [classifier_fun(signal) for signal in test_signals]81 classifier_output = np.array(classifier_output)82 num_correct = np.count_nonzero(classifier_output == ys)83 accuracy = num_correct / ys.size84 print('{} correct out of {} in test dataset for 2a'.format(num_correct, ys.size))85 print('Classifier accuracy on test data: {:.3f}'.format(accuracy))86 return accuracy87def test_classifier_2b(classifier_fun):88 """89 Tests accuracy of manual classifier function on test data for class 2 and 390 :param classifier_fun: function that returns class based on input 8x256 nd-array of a single signal epoch91 :return: Accuracy score92 """93 test_signals = df.loc[(df['id'].isin(X_test_23)), 'signal'].values.tolist()94 test_signals = np.array(test_signals)95 test_signals = np.reshape(test_signals, (test_signals.shape[0] // 8, 8, 256))96 # Get labels from df. Since it's repeated 8 times for each channel, only pull every 8th one97 ys = df.loc[(df['id'].isin(X_test_23)), 'label'].values98 ys = ys[::8]99 classifier_output = [classifier_fun(signal) for signal in test_signals]100 classifier_output = np.array(classifier_output)101 num_correct = np.count_nonzero(classifier_output == ys)102 accuracy = num_correct / ys.size103 print('{} correct out of {} in test dataset for 2b'.format(num_correct, ys.size))104 print('Classifier accuracy on test data: {:.3f}'.format(accuracy))105 return accuracy106#class 1 and 2107def classifier_se_var_2a(x):108 """109 Classifies EMG segment, x, as either class 1 or 2110 :param x: 8 by 256 nd-array. Dimension 0 are the 8 channels. Dimension 1 is the signal for each channel111 :return: class label112 """113 feature_1 = standard_error(x[0, :])114 feature_2 = variance(x[0, :])115 if (feature_1 < 0.00175) and (feature_2 < 0.005):116 return 1117 else: return 2118#class 2 and 3119def classifier_mav_ssc_2b(x):120 feature_1 = mean_absolute_value(x[0, :])121 feature_2 = slope_sign_change(x[0, :])122 if (feature_1 < 0.08):123 return 2124 else: return 3125# get train signals for class 1,2 channel 1126"""127cls1_ch1 = get_train_signals_2a(1, 1)128cls2_ch1 = get_train_signals_2a(2, 1)129cls1_ch1.shape130cls1_ch1_se = np.apply_along_axis(standard_error, 1, cls1_ch1)131cls2_ch1_se = np.apply_along_axis(standard_error, 1, cls2_ch1)132cls1_ch1_var = np.apply_along_axis(variance, 1, cls1_ch1)133cls2_ch1_var = np.apply_along_axis(variance, 1, cls2_ch1)134cls1_ch1_se.shape135cls1_ch1_var.shape136"""137#get train signals for class 2,3 channel 4138cls2_ch3 = get_train_signals_2b(2, 3)139cls3_ch3 = get_train_signals_2b(3, 3)140# cls2_ch2 = get_train_signals_2b(2, 2)141# cls3_ch1 = get_train_signals_2b(3, 1)142cls2_ch3.shape143cls2_ch3_mav = np.apply_along_axis(mean_absolute_value, 1, cls2_ch3)144cls3_ch3_mav = np.apply_along_axis(mean_absolute_value, 1, cls3_ch3)145cls2_ch3_ssc= np.apply_along_axis(slope_sign_change, 1, cls2_ch3)146cls3_ch3_ssc = np.apply_along_axis(slope_sign_change, 1, cls3_ch3)147cls2_ch3_mav.shape148cls3_ch3_ssc.shape149#plot class 1,2 channel 1150"""151plt.figure(figsize=(12,8))152plt.scatter(cls1_ch1_se, cls1_ch1_var, c='green', label="Resting Features", s=4)153plt.scatter(cls2_ch1_se, cls2_ch1_var, c='red', label="Fist Features", s=4)154ax = plt.gca()155ax.add_patch(mpatches.Rectangle((0, 0), 0.00175, 0.005, fill = False, color = 'purple'))156plt.legend(loc='best')157plt.xlabel('Standard Error (CH1)')158plt.ylabel('Variance (CH1)')159plt.title("Feature plot for Class 1 (Resting) and Class 2 (Fist)")160plt.show()161"""162#plot class 2,3 channel 4163plt.figure(figsize=(12,8))164plt.scatter(cls2_ch3_mav, cls2_ch3_ssc, c='green', label="Fist Feature", s=4)165plt.scatter(cls3_ch3_mav, cls3_ch3_ssc, c='red', label="Wrist Flexion Feature", s=4)166ax = plt.gca()167# ax.add_patch(mpatches.Rectangle((0, 0), 0.00175, 0.005, fill = False, color = 'purple'))168plt.vlines(0.08, 22, 55)169plt.legend(loc='best')170plt.xlabel('Mean Absolute Value (CH3)')171plt.ylabel('Slope Sign Change (CH3)')172plt.title("Feature plot for Class 2 (Fist) and Class 3 (Wrist Flexion)")173plt.show()174#call test classifier functions175# test_classifier_2a(classifier_se_var_2a)...

Full Screen

Full Screen

test_pemethod.py

Source:test_pemethod.py Github

copy

Full Screen

...26 Ao = [1, -1.2, 0.36]27 Bo = [0, 0.5, 0.1]28 return [Ao, Bo]29@pytest.fixture30def test_signals(test_polynomials):31 # True test system parameters32 Ao = test_polynomials[0]33 Bo = test_polynomials[1]34 # Replicates the following experiment:35 # y(t) = Go(q)*u(t) + Ho(q)*e(t),36 # where u(t) is the system input and e(t) white noise37 N = 100 # Number of samples38 u = -1 + 2*rand(N, 1) # Defines input signal39 e = 0.01*randn(N, 1) # Emulates gaussian white noise with std = 0.0140 # Calculates the y ARX: G(q) = B(q)/A(q) and H(q) = 1/A(q)41 y = lfilter(Bo, Ao, u, axis=0) #+ lfilter([1], Ao, e, axis=0)42 return [u, y, Ao, Bo]43# Defines sets of arguments for tests that request the respective fixtures44# Here, the values of na to nk are varied...

Full Screen

Full Screen

base.py

Source:base.py Github

copy

Full Screen

1from test_utils.crawler import signals as test_signals2class Plugin(object):3 """4 This is a class to represent a plugin to the Crawler.5 Subclass it and define a start or stop function to be called on requests.6 Define a print_report function if your plugin outputs at the end of the run.7 """8 global_data = {}9 def __init__(self):10 #This should be refactored to call each of the subclasses.11 #Having them use the signal function signature is hacky..12 if hasattr(self, 'pre_request'):13 test_signals.pre_request.connect(self.pre_request)14 if hasattr(self, 'post_request'):15 test_signals.post_request.connect(self.post_request)16 if hasattr(self, 'start_run'):17 test_signals.start_run.connect(self.start_run)18 if hasattr(self, 'finish_run'):19 test_signals.finish_run.connect(self.finish_run)20 if hasattr(self, 'urls_parsed'):21 test_signals.urls_parsed.connect(self.urls_parsed)22 self.data = self.global_data[self.__class__.__name__] = {}23 """24 #These functions enable instance['test'] to save to instance.data25 def __setitem__(self, key, val):26 self.global_data[self.__class__.__name__][key] = val27 def __getitem__(self, key):28 return self.global_data[self.__class__.__name__][key]...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-django automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful