How to use alphabet method in hypothesis

Best Python code snippet using hypothesis

omniglot.py

Source:omniglot.py Github

copy

Full Screen

1import scipy.io2import numpy as np3import pickle4import os5import numpy.random as npr6from hypergrad.util import dictslice, RandomState7NUM_CHARS = 558NUM_ALPHABETS = 509NUM_EXAMPLES = 1510CURATED_ALPHABETS = [6, 10, 23, 38, 39, 8, 9, 21, 22, 41]11ROTATED_ALPHABETS = [6, 10, 23, 38, 39]12FLIPPED_ALPHABETS = [6, 10, 23, 38, 39]13def datapath(fname):14 #datadir = os.path.expanduser('../data') #Michael15 datadir = os.path.abspath('../../../data/omniglot') #Michael16 #/Users/Mike/Desktop/Vavasis/Hyperparameter_optimization/drmad-master_Mar5/cpu_ver/data 17 return os.path.join(datadir, fname)18def mat_to_pickle():19 data = scipy.io.loadmat(datapath('data_background_small1.mat'))20 images = data['data'].T.astype(np.float16) # Flattened images, (24345, 784) in range [0, 1]21 alphabet_labels = np.argmax(data['target'], axis=0) # (24345, ) ints representing alphabets22 char_labels = data['targetchar'][0, :] - 1 # (24345, ) ints representing characters23 with open(datapath("omniglot_data.pkl"), "w") as f:24 pickle.dump((images, alphabet_labels, char_labels), f, 1)25def load_data(alphabets_to_load=range(NUM_ALPHABETS)):26 one_hot = lambda x, K : np.array(x[:,None] == np.arange(K)[None, :], dtype=int)27 with open(datapath("omniglot_data.pkl")) as f:28 images, alphabet_labels, char_labels = pickle.load(f)29 # print np.min(char_labels), np.max(char_labels)30 # print np.min(alphabet_labels), np.max(alphabet_labels)31 char_labels = one_hot(char_labels, NUM_CHARS)32 alphabets = []33 for i_alphabet in alphabets_to_load:34 cur_alphabet_idxs = np.where(alphabet_labels == i_alphabet)35 alphabets.append({'X' : images[cur_alphabet_idxs],36 'T' : char_labels[cur_alphabet_idxs]})37 return alphabets38def load_data_split(num_chars, RS, num_alphabets=NUM_ALPHABETS):39 alphabets_to_load = RS.choice(range(NUM_ALPHABETS), size=num_alphabets, replace=False)40 raw_data = load_data(np.sort(alphabets_to_load))41 shuffled_data = [shuffle(alphabet, RS) for alphabet in raw_data]42 data_split = zip(*[split(alphabet, num_chars) for alphabet in shuffled_data])43 normalized_data = [subtract_mean(data_subset) for data_subset in data_split]44 return normalized_data45def load_curated_alphabets(num_chars, RS):46 raw_data = load_data(CURATED_ALPHABETS)47 shuffled_data = [shuffle(alphabet, RS) for alphabet in raw_data]48 data_split = zip(*[split(alphabet, num_chars) for alphabet in shuffled_data])49 normalized_data = [subtract_mean(data_subset) for data_subset in data_split]50 return normalized_data51# def load_rotated_alphabets(num_chars, RS):52# raw_data = load_data(ROTATED_ALPHABETS)53# shuffled_data = [shuffle(alphabet, RS) for alphabet in raw_data]54# rotated_data = [do_rotation(alphabet) for alphabet in shuffled_data]55# all_data = shuffled_data + rotated_data56# data_split = zip(*[split(alphabet, num_chars) for alphabet in all_data])57# normalized_data = [subtract_mean(data_subset) for data_subset in data_split]58# return normalized_data59def load_flipped_alphabets(RS, normalize=True):60 raw_data = load_data(FLIPPED_ALPHABETS)61 shuffled_data = [shuffle(alphabet, RS) for alphabet in raw_data]62 flipped_data = [do_flip(alphabet) for alphabet in shuffled_data]63 all_data = raw_data + flipped_data[::-1]64 if normalize:65 all_data = subtract_mean(all_data)66 return all_data67def load_rotated_alphabets(RS, normalize=True, angle=90):68 raw_data = load_data(ROTATED_ALPHABETS)69 shuffled_data = [shuffle(alphabet, RS) for alphabet in raw_data]70 rotated_data = [do_rotation(alphabet, angle=angle) for alphabet in shuffled_data]71 all_data = shuffled_data + rotated_data72 if normalize:73 all_data = subtract_mean(all_data)74 return all_data75def do_rotation(alphabet, angle):76 new_alphabet = alphabet.copy()77 old_X = alphabet['X']78 if angle == 90:79 orig_shape = old_X.shape80 new_alphabet['X'] = old_X.reshape((orig_shape[0], 28, 28))\81 .transpose([0, 2, 1])[:, :, ::-1].reshape(orig_shape)82 elif angle == 180:83 new_alphabet['X'] = old_X[:, ::-1]84 else:85 assert False, "Can't rotate by {0}".format(angle)86 return new_alphabet87def do_flip(alphabet):88 new_alphabet = alphabet.copy()89 orig_shape = alphabet['X'].shape90 num_dpts = orig_shape[0]91 new_alphabet['X'] = alphabet['X'].reshape((num_dpts, 28, 28))[:, ::-1, :].reshape(orig_shape)92 return new_alphabet93def split(alphabet, num_chars):94 cum_chars = np.cumsum(num_chars)95 def select_dataset(count):96 for i, N in enumerate(cum_chars):97 if count < N: return i98 labels = np.argmax(alphabet['T'], axis=1)99 label_counts = [0] * NUM_CHARS100 split_idxs = [[] for n in num_chars]101 for i_dpt, label in enumerate(labels):102 i_dataset = select_dataset(label_counts[label])103 split_idxs[i_dataset].append(i_dpt)104 label_counts[label] += 1105 data_splits = []106 for n, idxs in zip(num_chars, split_idxs):107 data_splits.append(dictslice(alphabet, idxs))108 totals = np.sum(data_splits[-1]['T'], axis=0)109 assert np.all(np.logical_or(totals == 0, totals == n))110 return data_splits111def random_partition(data, RS, num_chars):112 shuffled_data = [shuffle_rows(alphabet, RS) for alphabet in data]113 return zip(*[split(alphabet, num_chars) for alphabet in shuffled_data])114 115def shuffle(alphabet, RS):116 N_rows, N_cols = alphabet['T'].shape117 alphabet['T'] = alphabet['T'][:, RS.permutation(N_cols)]118 return dictslice(alphabet, RS.permutation(N_rows))119def shuffle_rows(alphabet, RS):120 N_rows, N_cols = alphabet['T'].shape121 return dictslice(alphabet, RS.permutation(N_rows))122def subtract_mean(alphabets):123 all_images = np.concatenate([alphabet['X'] for alphabet in alphabets], axis=0)124 assert np.all(all_images >= 0) and np.all(all_images <= 1)125 mean_img = np.mean(all_images, axis=0)126 for alphabet in alphabets:127 alphabet['X'] = alphabet['X'] - mean_img128 return alphabets129def show_alphabets(alphabets, ax=None, n_cols=20):130 import matplotlib as mpl131 import matplotlib.pyplot as plt132 from nn_utils import plot_images133 seed = 1134 n_rows = len(alphabets)135 full_image = np.zeros((0, n_cols * 28))136 for alphabet in alphabets:137 RS = RandomState(seed)138 char_idxs = RS.randint(alphabet['X'].shape[0], size=n_cols)139 char_ids = np.argmax(alphabet['T'][char_idxs], axis=1)140 image = alphabet['X'][char_idxs].reshape((n_cols, 28, 28))141 image = np.transpose(image, axes=[1, 0, 2]).reshape((28, n_cols * 28))142 full_image = np.concatenate((full_image, image))143 144 if ax is None:145 fig = plt.figure()146 fig.set_size_inches((8, 8 * n_rows/n_cols))147 ax = fig.add_subplot(111)148 ax.imshow(full_image, cmap=mpl.cm.binary)149 ax.set_xticks(np.array([]))150 ax.set_yticks(np.array([]))151 plt.tight_layout()152 plt.savefig("all_alphabets.png")153def show_all_alphabets(perm=None, rotate=False):154 show_alphabets(load_data)155if __name__ == "__main__":...

Full Screen

Full Screen

1. Поддержка интерфейса .py

Source:1. Поддержка интерфейса .py Github

copy

Full Screen

1class SequenceIter:2 3 def __init__(self, seq):4 self.index = 05 self.seq = seq6 def __next__(self):7 if self.index >= len(self.seq):8 raise StopIteration9 symb = self.seq[self.index]10 self.index += 111 return symb12class Sequence:13 def __init__(self, name, seq):14 self.name = name15 self.seq = seq16 def __iter__(self):17 return SequenceIter(self.seq)18 def name ( self ) :19 return self.name20 def seq ( self ) :21 return self.seq22 def length (self) :23 length=len(seq)24 return length25class DNA(Sequence):26 name='DNA'27 alphabet=['A','C','G','T']28 def __init__(self,seq,):29 super().__init__(Sequence,seq)30 def statistic(self):31 for i in range(0,4):32 stat = self.seq.count(self.alphabet[i])33 print(alphabet[i],' - ',stat)34 def Mol(self):35 m=347 * self.seq.count(self.alphabet[0]) +\36 320.2 * self.seq.count(self.alphabet[1]) +\37 363.2 * self.seq.count(self.alphabet[2]) +\38 323.2 * self.seq.count(self.alphabet[3])39 print('Молекулярная масса - ',round(m,2))40 def complementary(self):41 comp = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}42 comp_seq = ''43 for i in self.seq:44 comp_seq += comp[i]45 return comp_seq46 print('Комплементарная последовательность - ', comp_seq)47 48 def Transcription(self):49 tran = []50 for i in range(0, len(self.seq)):51 if self.seq[i] == 'A':52 tran.append('U')53 elif self.seq[i] == 'T':54 tran.append('A')55 elif self.seq[i] == 'G':56 tran.append('C')57 elif self.seq[i] == 'C':58 tran.append('G')59 print('Транскрипция - ', tran)60class RNA(Sequence):61 name = 'RNA'62 alphabet = ['A', 'C', 'G', 'U']63 def __init__(self,seq,):64 super().__init__(Sequence,seq)65 def statistic(self):66 for i in range(0,4):67 stat = self.seq.count(alphabet[i])68 print(alphabet[i],' - ',stat)69 def Mol(self):70 m = 347 * self.seq.count(self.alphabet[0]) + 324.2 * self.seq.count(self.alphabet[1]) + 363.2 * self.seq.count(self.alphabet[2]) + 323.2 * self.seq.count(self.alphabet[3])71 print('Молекулярная масса - ', round(m,2))72 def Translation(self):73 d = {'UUU': 'F', 'UUC': 'F','UUA':'L','UUG':'L','CUU':'L',74 'CUC': 'L','CUA':'L', 'CUG':'L', 'AUU':'I','AUC':'I',75 'AUA': 'I','AUG':'M','GUU':'V','GUC':'V','GUA':'V','GUG':'V',76 'UCU': 'S','UCA': 'S','UCC': 'S','UCG': 'S','CCU': 'P','CCC': 'P',77 'CCA': 'P','CCG': 'P','ACU': 'T','ACC': 'T','ACA': 'T','ACG': 'T',78 'GCU': 'A','GCC': 'A','GCA': 'A','GCG': 'A', 'UAU': 'Y','UAC': 'Y',79 'CAU': 'H','CAC': 'H','CAA': 'Q','CAG': 'Q','AAU': 'N', 'AAC': 'N',80 'AAA': 'K','AAG': 'K','GAU': 'D','GAC': 'D','GAA': 'E','GAG': 'E',81 'UGU': 'C','UGC': 'C','UGG': 'W','CGU': 'R','CGC': 'R','CGA': 'R',82 'CGG': 'R','AGU': 'S','AGC': 'S','AGA': 'R','AGG': 'R','GGU': 'G',83 'GGC': 'G','GGA': 'G','GGG': 'G','UAA': 'STOP','UAG': 'STOP',84 'UGA': 'STOP'}85 protein = []86 start = 087 for i in range(len(self.seq)):88 if (self.seq[i:i + 3] == "AUG"):89 start = i90 for j in range(start, len(self.seq) - 2, 3):91 amin = d[self.seq[j:j + 3]]92 if (cods == "STOP"):93 break94 else:95 protein.append(amin)96 print('Белковая последовательность - ', protein)97class Protein(Sequence):98 name = 'Protein'99 alphabet = ['A', 'R', 'N', 'D', 'V', 'H', 'G', 'Q', 'E', 'I', 'L',100 'K', 'M', 'P', 'S', 'Y', 'T', 'W', 'F', 'C']101 def __init__(self,seq,):102 super().__init__(Sequence,seq)103 def statistic(self):104 for i in range(0,20):105 stat = self.seq.count(alphabet[i])106 print(alphabet[i],' - ',stat)107 def Mol(self):108 m=75 * self.seq.count(self.alphabet[0]) + 89 * self.seq.count(self.alphabet[1]) +\109 117.2 * self.seq.count(self.alphabet[2]) + 131.2 * self.seq.count(self.alphabet[3]) +\110 131.2 * self.seq.count(self.alphabet[4]) + 149.2 * self.seq.count(self.alphabet[5]) +\111 115.1 * self.seq.count(self.alphabet[6]) + 165.2 * self.seq.count(self.alphabet[7]) +\112 204.2 * self.seq.count(self.alphabet[8]) + 105.9 * self.seq.count(self.alphabet[9]) +\113 119 * self.seq.count(self.alphabet[10]) + 132 * self.seq.count(self.alphabet[11]) +\114 146 * self.seq.count(self.alphabet[12]) + 181.2 * self.seq.count(self.alphabet[13]) +\115 121.2 * self.seq.count(self.alphabet[14]) + 146.2 * self.seq.count(self.alphabet[15]) +\116 174.2 * self.seq.count(self.alphabet[16]) + 155.2 * self.seq.count(self.alphabet[17]) +\117 131 * self.seq.count(self.alphabet[18]) + 147 * self.seq.count(self.alphabet[19])...

Full Screen

Full Screen

Классы .py

Source:Классы .py Github

copy

Full Screen

1class Sequence:2 3 def __init__(self, name, seq):4 self.name = name5 self.seq = seq6 7 def name ( self ) :8 return self.name9 10 def seq ( self ) :11 return self.seq12 13 def length (self) :14 length=len(seq)15 return length16class DNA(Sequence):17 name='DNA'18 alphabet=['A','C','G','T']19 def __init__(self,seq,):20 super().__init__(Sequence,seq)21 def statistic(self):22 for i in range(0,4):23 stat = self.seq.count(self.alphabet[i])24 print(alphabet[i],' - ',stat)25 def Mol(self):26 m = 347 * self.seq.count(self.alphabet[0]) +\27 323.2 * self.seq.count(self.alphabet[1]) +\28 363.2 * self.seq.count(self.alphabet[2]) +\29 320.2 * self.seq.count(self.alphabet[3])30 print('Молекулярная масса - ',round(m,2))31 def complementary(self):32 comp = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A',}33 comp_seq = ''34 for i in self.seq:35 comp_seq += comp[i]36 return comp_seq37 print('Комплементарная последовательность - ', comp_seq)38 39 def Transcription(self):40 tran = []41 for i in range(0, len(self.seq)):42 if self.seq[i] == 'A':43 tran.append('U')44 elif self.seq[i] == 'C':45 tran.append('G')46 elif self.seq[i] == 'G':47 tran.append('C')48 elif self.seq[i] == 'T':49 tran.append('A')50 print('Транскрипция - ', tran)51class RNA(Sequence):52 name = 'RNA'53 alphabet = ['A', 'C', 'G', 'U']54 def __init__(self,seq,):55 super().__init__(Sequence,seq)56 def statistic(self):57 for i in range(0,4):58 stat = self.seq.count(alphabet[i])59 print(alphabet[i],' - ',stat)60 def Mol(self):61 m = 347 * self.seq.count(self.alphabet[0]) + 323.2 * self.seq.count(self.alphabet[1]) +\62 363.2 * self.seq.count(self.alphabet[2]) + 324.2 * self.seq.count(self.alphabet[3])63 print('Молекулярная масса - ', round(m,2))64 def Translation(self):65 d = {'UUU': 'F', 'UUC': 'F','UUA':'L','UUG':'L','CUU':'L',66 'CUC': 'L','CUA':'L', 'CUG':'L', 'AUU':'I','AUC':'I',67 'AUA': 'I','AUG':'M','GUU':'V','GUC':'V','GUA':'V','GUG':'V',68 'UCU': 'S','UCA': 'S','UCC': 'S','UCG': 'S','CCU': 'P','CCC': 'P',69 'CCA': 'P','CCG': 'P','ACU': 'T','ACC': 'T','ACA': 'T','ACG': 'T',70 'GCU': 'A','GCC': 'A','GCA': 'A','GCG': 'A', 'UAU': 'Y','UAC': 'Y',71 'CAU': 'H','CAC': 'H','CAA': 'Q','CAG': 'Q','AAU': 'N', 'AAC': 'N',72 'AAA': 'K','AAG': 'K','GAU': 'D','GAC': 'D','GAA': 'E','GAG': 'E',73 'UGU': 'C','UGC': 'C','UGG': 'W','CGU': 'R','CGC': 'R','CGA': 'R',74 'CGG': 'R','AGU': 'S','AGC': 'S','AGA': 'R','AGG': 'R','GGU': 'G',75 'GGC': 'G','GGA': 'G','GGG': 'G','UAA': 'STOP','UAG': 'STOP',76 'UGA': 'STOP'}77 protein = []78 start = 079 for i in range(len(self.seq)):80 if (self.seq[i:i + 3] == "AUG"):81 start = i82 for j in range(start, len(self.seq) - 2, 3):83 amin = d[self.seq[j:j + 3]]84 if (cods == "STOP"):85 break86 else:87 protein.append(amin)88 print('Белковая последовательность - ', protein)89class Protein(Sequence):90 name = 'Protein'91 alphabet = ['A', 'R', 'N', 'D', 'V', 'H', 'G', 'Q', 'E', 'I', 'L',92 'K', 'M', 'P', 'S', 'Y', 'T', 'W', 'F', 'C']93 def __init__(self,seq,):94 super().__init__(Sequence,seq)95 def statistic(self):96 for i in range(0,20):97 stat = self.seq.count(alphabet[i])98 print(alphabet[i],' - ',stat)99 def Mol(self):100 m = 89.1 * self.seq.count(self.alphabet[0]) + 174.2 * self.seq.count(self.alphabet[1]) +\101 132.1 * self.seq.count(self.alphabet[2]) + 133.1 * self.seq.count(self.alphabet[3]) +\102 117.2 * self.seq.count(self.alphabet[4]) + 155.2 * self.seq.count(self.alphabet[5]) +\103 75.1 * self.seq.count(self.alphabet[6]) + 146.1 * self.seq.count(self.alphabet[7]) +\104 147.1 * self.seq.count(self.alphabet[8]) + 131.2 * self.seq.count(self.alphabet[9]) +\105 131.2 * self.seq.count(self.alphabet[10]) + 146.1 * self.seq.count(self.alphabet[11]) +\106 149.2 * self.seq.count(self.alphabet[12]) + 115.1 * self.seq.count(self.alphabet[13]) +\107 105.1 * self.seq.count(self.alphabet[14]) + 181.2 * self.seq.count(self.alphabet[15]) +\108 119.1 * self.seq.count(self.alphabet[16]) + 204.2 * self.seq.count(self.alphabet[17]) +\109 165.2 * self.seq.count(self.alphabet[18]) + 121.2 * self.seq.count(self.alphabet[19])...

Full Screen

Full Screen

dataTables.alphabetSearch.js

Source:dataTables.alphabetSearch.js Github

copy

Full Screen

1/*! AlphabetSearch for DataTables v1.0.02 * 2014 SpryMedia Ltd - datatables.net/license3 */4/**5 * @summary AlphabetSearch6 * @description Show an set of alphabet buttons alongside a table providing7 * search input options8 * @version 1.0.09 * @file dataTables.alphabetSearch.js10 * @author SpryMedia Ltd (www.sprymedia.co.uk)11 * @contact www.sprymedia.co.uk/contact12 * @copyright Copyright 2014 SpryMedia Ltd.13 * 14 * License MIT - http://datatables.net/license/mit15 *16 * For more detailed information please see:17 * http://datatables.net/blog/2014-09-2218 */19(function(){20// Search function21$.fn.dataTable.Api.register( 'alphabetSearch()', function ( searchTerm ) {22 this.iterator( 'table', function ( context ) {23 context.alphabetSearch = searchTerm;24 } );25 return this;26} );27// Recalculate the alphabet display for updated data28$.fn.dataTable.Api.register( 'alphabetSearch.recalc()', function ( searchTerm ) {29 this.iterator( 'table', function ( context ) {30 draw(31 new $.fn.dataTable.Api( context ),32 $('div.alphabet', this.table().container())33 );34 } );35 return this;36} );37// Search plug-in38$.fn.dataTable.ext.search.push( function ( context, searchData ) {39 // Ensure that there is a search applied to this table before running it40 if ( ! context.alphabetSearch ) {41 return true;42 }43 if ( searchData[0].charAt(0) === context.alphabetSearch ) {44 return true;45 }46 return false;47} );48// Private support methods49function bin ( data ) {50 var letter, bins = {};51 for ( var i=0, ien=data.length ; i<ien ; i++ ) {52 letter = data[i].charAt(0).toUpperCase();53 if ( bins[letter] ) {54 bins[letter]++;55 }56 else {57 bins[letter] = 1;58 }59 }60 return bins;61}62function draw ( table, alphabet )63{64 alphabet.empty();65 alphabet.append( 'Search: ' );66 var columnData = table.column(0).data();67 var bins = bin( columnData );68 $('<span class="clear active"/>')69 .data( 'letter', '' )70 .data( 'match-count', columnData.length )71 .html( 'None' )72 .appendTo( alphabet );73 for ( var i=0 ; i<26 ; i++ ) {74 var letter = String.fromCharCode( 65 + i );75 $('<span/>')76 .data( 'letter', letter )77 .data( 'match-count', bins[letter] || 0 )78 .addClass( ! bins[letter] ? 'empty' : '' )79 .html( letter )80 .appendTo( alphabet );81 }82 $('<div class="alphabetInfo"></div>')83 .appendTo( alphabet );84}85$.fn.dataTable.AlphabetSearch = function ( context ) {86 var table = new $.fn.dataTable.Api( context );87 var alphabet = $('<div class="alphabet"/>');88 draw( table, alphabet );89 // Trigger a search90 alphabet.on( 'click', 'span', function () {91 alphabet.find( '.active' ).removeClass( 'active' );92 $(this).addClass( 'active' );93 table94 .alphabetSearch( $(this).data('letter') )95 .draw();96 } );97 // Mouse events to show helper information98 alphabet99 .on( 'mouseenter', 'span', function () {100 alphabet101 .find('div.alphabetInfo')102 .css( {103 opacity: 1,104 left: $(this).position().left,105 width: $(this).width()106 } )107 .html( $(this).data('match-count') );108 } )109 .on( 'mouseleave', 'span', function () {110 alphabet111 .find('div.alphabetInfo')112 .css('opacity', 0);113 } );114 // API method to get the alphabet container node115 this.node = function () {116 return alphabet;117 };118};119$.fn.DataTable.AlphabetSearch = $.fn.dataTable.AlphabetSearch;120// Register a search plug-in121$.fn.dataTable.ext.feature.push( {122 fnInit: function ( settings ) {123 var search = new $.fn.dataTable.AlphabetSearch( settings );124 return search.node();125 },126 cFeature: 'A'127} );...

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 hypothesis 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